context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void BroadcastScalarToVector256Int32()
{
var test = new SimpleUnaryOpTest__BroadcastScalarToVector256Int32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__BroadcastScalarToVector256Int32
{
private const int VectorSize = 32;
private const int Op1ElementCount = VectorSize / sizeof(Int32);
private const int RetElementCount = VectorSize / sizeof(Int32);
private static Int32[] _data = new Int32[Op1ElementCount];
private static Vector128<Int32> _clsVar;
private Vector128<Int32> _fld;
private SimpleUnaryOpTest__DataTable<Int32, Int32> _dataTable;
static SimpleUnaryOpTest__BroadcastScalarToVector256Int32()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar), ref Unsafe.As<Int32, byte>(ref _data[0]), VectorSize);
}
public SimpleUnaryOpTest__BroadcastScalarToVector256Int32()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld), ref Unsafe.As<Int32, byte>(ref _data[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)(random.Next(0, int.MaxValue)); }
_dataTable = new SimpleUnaryOpTest__DataTable<Int32, Int32>(_data, new Int32[RetElementCount], VectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx2.BroadcastScalarToVector256<Int32>(
Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx2.BroadcastScalarToVector256<Int32>(
Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx2.BroadcastScalarToVector256<Int32>(
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.BroadcastScalarToVector256))
.MakeGenericMethod( new Type[] { typeof(Int32) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.BroadcastScalarToVector256))
.MakeGenericMethod( new Type[] { typeof(Int32) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.BroadcastScalarToVector256))
.MakeGenericMethod( new Type[] { typeof(Int32) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx2.BroadcastScalarToVector256<Int32>(
_clsVar
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr);
var result = Avx2.BroadcastScalarToVector256<Int32>(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr));
var result = Avx2.BroadcastScalarToVector256<Int32>(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr));
var result = Avx2.BroadcastScalarToVector256<Int32>(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleUnaryOpTest__BroadcastScalarToVector256Int32();
var result = Avx2.BroadcastScalarToVector256<Int32>(test._fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx2.BroadcastScalarToVector256<Int32>(_fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Int32> firstOp, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray = new Int32[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray = new Int32[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Int32[] firstOp, Int32[] result, [CallerMemberName] string method = "")
{
if (firstOp[0] != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((firstOp[0] != result[i]))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.BroadcastScalarToVector256)}<Int32>(Vector128<Int32>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
/*
* 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;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Util;
namespace QuantConnect.Data.Market
{
/// <summary>
/// Represents an entire chain of futures contracts for a single underlying
/// This type is <see cref="IEnumerable{FuturesContract}"/>
/// </summary>
public class FuturesChain : BaseData, IEnumerable<FuturesContract>
{
private readonly Dictionary<Type, Dictionary<Symbol, List<BaseData>>> _auxiliaryData = new Dictionary<Type, Dictionary<Symbol, List<BaseData>>>();
/// <summary>
/// Gets the most recent trade information for the underlying. This may
/// be a <see cref="Tick"/> or a <see cref="TradeBar"/>
/// </summary>
public BaseData Underlying
{
get; internal set;
}
/// <summary>
/// Gets all ticks for every futures contract in this chain, keyed by symbol
/// </summary>
public Ticks Ticks
{
get; private set;
}
/// <summary>
/// Gets all trade bars for every futures contract in this chain, keyed by symbol
/// </summary>
public TradeBars TradeBars
{
get; private set;
}
/// <summary>
/// Gets all quote bars for every futures contract in this chain, keyed by symbol
/// </summary>
public QuoteBars QuoteBars
{
get; private set;
}
/// <summary>
/// Gets all contracts in the chain, keyed by symbol
/// </summary>
public FuturesContracts Contracts
{
get; private set;
}
/// <summary>
/// Gets the set of symbols that passed the <see cref="Future.ContractFilter"/>
/// </summary>
public HashSet<Symbol> FilteredContracts
{
get; private set;
}
/// <summary>
/// Initializes a new default instance of the <see cref="FuturesChain"/> class
/// </summary>
private FuturesChain()
{
DataType = MarketDataType.FuturesChain;
}
/// <summary>
/// Initializes a new instance of the <see cref="FuturesChain"/> class
/// </summary>
/// <param name="canonicalFutureSymbol">The symbol for this chain.</param>
/// <param name="time">The time of this chain</param>
public FuturesChain(Symbol canonicalFutureSymbol, DateTime time)
{
Time = time;
Symbol = canonicalFutureSymbol;
DataType = MarketDataType.FuturesChain;
Ticks = new Ticks(time);
TradeBars = new TradeBars(time);
QuoteBars = new QuoteBars(time);
Contracts = new FuturesContracts(time);
FilteredContracts = new HashSet<Symbol>();
}
/// <summary>
/// Initializes a new instance of the <see cref="FuturesChain"/> class
/// </summary>
/// <param name="canonicalFutureSymbol">The symbol for this chain.</param>
/// <param name="time">The time of this chain</param>
/// <param name="trades">All trade data for the entire futures chain</param>
/// <param name="quotes">All quote data for the entire futures chain</param>
/// <param name="contracts">All contrains for this futures chain</param>
public FuturesChain(Symbol canonicalFutureSymbol, DateTime time, IEnumerable<BaseData> trades, IEnumerable<BaseData> quotes, IEnumerable<FuturesContract> contracts, IEnumerable<Symbol> filteredContracts)
{
Time = time;
Symbol = canonicalFutureSymbol;
DataType = MarketDataType.FuturesChain;
FilteredContracts = filteredContracts.ToHashSet();
Ticks = new Ticks(time);
TradeBars = new TradeBars(time);
QuoteBars = new QuoteBars(time);
Contracts = new FuturesContracts(time);
foreach (var trade in trades)
{
var tick = trade as Tick;
if (tick != null)
{
List<Tick> ticks;
if (!Ticks.TryGetValue(tick.Symbol, out ticks))
{
ticks = new List<Tick>();
Ticks[tick.Symbol] = ticks;
}
ticks.Add(tick);
continue;
}
var bar = trade as TradeBar;
if (bar != null)
{
TradeBars[trade.Symbol] = bar;
}
}
foreach (var quote in quotes)
{
var tick = quote as Tick;
if (tick != null)
{
List<Tick> ticks;
if (!Ticks.TryGetValue(tick.Symbol, out ticks))
{
ticks = new List<Tick>();
Ticks[tick.Symbol] = ticks;
}
ticks.Add(tick);
continue;
}
var bar = quote as QuoteBar;
if (bar != null)
{
QuoteBars[quote.Symbol] = bar;
}
}
foreach (var contract in contracts)
{
Contracts[contract.Symbol] = contract;
}
}
/// <summary>
/// Gets the auxiliary data with the specified type and symbol
/// </summary>
/// <typeparam name="T">The type of auxiliary data</typeparam>
/// <param name="symbol">The symbol of the auxiliary data</param>
/// <returns>The last auxiliary data with the specified type and symbol</returns>
public T GetAux<T>(Symbol symbol)
{
List<BaseData> list;
Dictionary<Symbol, List<BaseData>> dictionary;
if (!_auxiliaryData.TryGetValue(typeof(T), out dictionary) || !dictionary.TryGetValue(symbol, out list))
{
return default(T);
}
return list.OfType<T>().LastOrDefault();
}
/// <summary>
/// Gets all auxiliary data of the specified type as a dictionary keyed by symbol
/// </summary>
/// <typeparam name="T">The type of auxiliary data</typeparam>
/// <returns>A dictionary containing all auxiliary data of the specified type</returns>
public DataDictionary<T> GetAux<T>()
{
Dictionary<Symbol, List<BaseData>> d;
if (!_auxiliaryData.TryGetValue(typeof(T), out d))
{
return new DataDictionary<T>();
}
var dictionary = new DataDictionary<T>();
foreach (var kvp in d)
{
var item = kvp.Value.OfType<T>().LastOrDefault();
if (item != null)
{
dictionary.Add(kvp.Key, item);
}
}
return dictionary;
}
/// <summary>
/// Gets all auxiliary data of the specified type as a dictionary keyed by symbol
/// </summary>
/// <typeparam name="T">The type of auxiliary data</typeparam>
/// <returns>A dictionary containing all auxiliary data of the specified type</returns>
public Dictionary<Symbol, List<BaseData>> GetAuxList<T>()
{
Dictionary<Symbol, List<BaseData>> dictionary;
if (!_auxiliaryData.TryGetValue(typeof(T), out dictionary))
{
return new Dictionary<Symbol, List<BaseData>>();
}
return dictionary;
}
/// <summary>
/// Gets a list of auxiliary data with the specified type and symbol
/// </summary>
/// <typeparam name="T">The type of auxiliary data</typeparam>
/// <param name="symbol">The symbol of the auxiliary data</param>
/// <returns>The list of auxiliary data with the specified type and symbol</returns>
public List<T> GetAuxList<T>(Symbol symbol)
{
List<BaseData> list;
Dictionary<Symbol, List<BaseData>> dictionary;
if (!_auxiliaryData.TryGetValue(typeof(T), out dictionary) || !dictionary.TryGetValue(symbol, out list))
{
return new List<T>();
}
return list.OfType<T>().ToList();
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// An enumerator that can be used to iterate through the collection.
/// </returns>
public IEnumerator<FuturesContract> GetEnumerator()
{
return Contracts.Values.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Return a new instance clone of this object, used in fill forward
/// </summary>
/// <returns>A clone of the current object</returns>
public override BaseData Clone()
{
return new FuturesChain
{
Ticks = Ticks,
Contracts = Contracts,
QuoteBars = QuoteBars,
TradeBars = TradeBars,
FilteredContracts = FilteredContracts,
Symbol = Symbol,
Time = Time,
DataType = DataType,
Value = Value
};
}
/// <summary>
/// Adds the specified auxiliary data to this futures chain
/// </summary>
/// <param name="baseData">The auxiliary data to be added</param>
internal void AddAuxData(BaseData baseData)
{
var type = baseData.GetType();
Dictionary<Symbol, List<BaseData>> dictionary;
if (!_auxiliaryData.TryGetValue(type, out dictionary))
{
dictionary = new Dictionary<Symbol, List<BaseData>>();
_auxiliaryData[type] = dictionary;
}
List<BaseData> list;
if (!dictionary.TryGetValue(baseData.Symbol, out list))
{
list = new List<BaseData>();
dictionary[baseData.Symbol] = list;
}
list.Add(baseData);
}
}
}
| |
namespace Ioke.Lang {
using System.Collections;
using System.Collections.Generic;
using Ioke.Lang.Util;
public class IokeObject : ITypeChecker {
public Runtime runtime;
public IokeData data;
internal Body body = new Body();
public static readonly int FALSY_F = 1 << 0;
public static readonly int NIL_F = 1 << 1;
public static readonly int FROZEN_F = 1 << 2;
public static readonly int ACTIVATABLE_F = 1 << 3;
public static readonly int HAS_ACTIVATABLE_F = 1 << 4;
public static readonly int LEXICAL_F = 1 << 5;
public bool IsNil {
get {
return (body.flags & NIL_F) != 0;
}
}
public bool IsTrue {
get {
return (body.flags & FALSY_F) == 0;
}
}
public void SetFrozen(bool frozen) {
if (frozen) {
body.flags |= FROZEN_F;
} else {
body.flags &= ~FROZEN_F;
}
}
public bool IsActivatable {
get {
return (body.flags & ACTIVATABLE_F) != 0;
}
}
public bool IsFrozen {
get {
return (body.flags & FROZEN_F) != 0;
}
}
public bool IsSetActivatable {
get {
return (body.flags & HAS_ACTIVATABLE_F) != 0;
}
}
public void SetActivatable(bool activatable) {
body.flags |= HAS_ACTIVATABLE_F;
if (activatable) {
body.flags |= ACTIVATABLE_F;
} else {
body.flags &= ~ACTIVATABLE_F;
}
}
public bool IsLexical {
get {
return (body.flags & LEXICAL_F) != 0;
}
}
public IokeObject(Runtime runtime, string documentation) : this(runtime, documentation, IokeData.None) {
}
public IokeObject(Runtime runtime, string documentation, IokeData data) {
this.runtime = runtime;
this.body.documentation = documentation;
this.data = data;
}
public IokeData Data {
get { return data; }
set { this.data = value; }
}
public string Documentation {
get { return body.documentation; }
set { this.body.documentation = value; }
}
private bool ContainsMimic(IokeObject obj) {
if(body.mimicCount == 1) {
return obj == body.mimic;
}
if(body.mimic != null) {
return body.mimic == obj;
} else {
for(int i = 0; i < body.mimicCount; i++) {
if(body.mimics[i] == obj) {
return true;
}
}
}
return false;
}
public static IList<IokeObject> GetMimics(object on, IokeObject context) {
return As(on, context).GetMimics();
}
public IList<IokeObject> GetMimics() {
var result = new SaneList<IokeObject>();
switch(body.mimicCount) {
case 0:
break;
case 1:
result.Add(body.mimic);
break;
default:
for(int i=0; i<body.mimicCount; i++) {
result.Add(body.mimics[i]);
}
break;
}
return result;
}
public IokeObject AllocateCopy(IokeObject m, IokeObject context) {
return new IokeObject(runtime, null, data.CloneData(this, m, context));
}
public void SingleMimicsWithoutCheck(IokeObject mimic) {
body.mimic = mimic;
body.mimicCount = 1;
TransplantActivation(mimic);
}
private void AddMimic(IokeObject mimic) {
AddMimic(body.mimicCount, mimic);
}
private void AddMimic(int at, IokeObject mimic) {
switch(body.mimicCount) {
case 0:
body.mimic = mimic;
body.mimicCount = 1;
break;
case 1:
if(at == 0) {
body.mimics = new IokeObject[]{mimic, body.mimic};
} else {
body.mimics = new IokeObject[]{body.mimic, mimic};
}
body.mimicCount = 2;
body.mimic = null;
break;
default:
if(at == 0) {
int newLen = body.mimicCount + 1;
IokeObject[] newMimics;
if(body.mimics.Length < newLen) {
newMimics = new IokeObject[newLen];
} else {
newMimics = body.mimics;
}
System.Array.Copy(body.mimics, 0, newMimics, 1, newLen - 1);
body.mimics = newMimics;
newMimics[0] = mimic;
body.mimicCount++;
} else if(at == body.mimicCount) {
if(body.mimicCount == body.mimics.Length) {
IokeObject[] newMimics = new IokeObject[body.mimics.Length + 1];
System.Array.Copy(body.mimics, 0, newMimics, 0, body.mimics.Length);
body.mimics = newMimics;
}
body.mimics[body.mimicCount++] = mimic;
} else {
if(body.mimicCount == body.mimics.Length) {
IokeObject[] newMimics = new IokeObject[body.mimics.Length + 1];
System.Array.Copy(body.mimics, 0, newMimics, 0, at);
System.Array.Copy(body.mimics, at, newMimics, at+1, body.mimicCount - at);
body.mimics = newMimics;
body.mimics[at] = mimic;
} else {
System.Array.Copy(body.mimics, at, body.mimics, at + 1, body.mimicCount - at);
body.mimics[at] = mimic;
}
body.mimicCount++;
}
break;
}
}
public void MimicsWithoutCheck(IokeObject mimic) {
if(!ContainsMimic(mimic)) {
AddMimic(mimic);
TransplantActivation(mimic);
}
}
public void MimicsWithoutCheck(int index, IokeObject mimic) {
if(!ContainsMimic(mimic)) {
AddMimic(index, mimic);
TransplantActivation(mimic);
}
}
private void CheckFrozen(string modification, IokeObject message, IokeObject context) {
if(IsFrozen) {
IokeObject condition = As(IokeObject.GetCellChain(context.runtime.Condition,
message,
context,
"Error",
"ModifyOnFrozen"), context).Mimic(message, context);
condition.SetCell("message", message);
condition.SetCell("context", context);
condition.SetCell("receiver", this);
condition.SetCell("modification", context.runtime.GetSymbol(modification));
context.runtime.ErrorCondition(condition);
}
}
public static bool Same(object one, object two) {
if((one is IokeObject) && (two is IokeObject)) {
return object.ReferenceEquals(As(one, null).body, As(two, null).body);
} else {
return object.ReferenceEquals(one, two);
}
}
public void Become(IokeObject other, IokeObject message, IokeObject context) {
CheckFrozen("become!", message, context);
this.runtime = other.runtime;
this.data = other.data;
this.body = other.body;
}
private int MimicIndex(object other) {
if(body.mimicCount == 1) {
return body.mimic == other ? -2 : -1;
}
for(int i = 0; i < body.mimicCount; i++) {
if(body.mimics[i] == other) {
return i;
}
}
return -1;
}
private void RemoveMimicAt(int index) {
switch(index) {
case -2:
body.mimic = null;
body.mimicCount--;
break;
case 0:
if(body.mimicCount-- == 2) {
body.mimic = body.mimics[1];
body.mimics = null;
} else {
IokeObject[] newMimics = new IokeObject[body.mimicCount];
System.Array.Copy(body.mimics, 1, newMimics, 0, body.mimicCount);
body.mimics = newMimics;
}
break;
default:
if(index == body.mimicCount - 1) {
if(body.mimicCount-- == 2) {
body.mimic = body.mimics[0];
body.mimics = null;
} else {
body.mimics[index] = null;
}
} else {
IokeObject[] newMimics = new IokeObject[body.mimicCount];
System.Array.Copy(body.mimics, 0, newMimics, 0, index);
System.Array.Copy(body.mimics, index + 1, newMimics, index, body.mimicCount - (index + 1));
body.mimics = newMimics;
body.mimicCount--;
}
break;
}
}
public static void RemoveMimic(object on, object other, IokeObject message, IokeObject context) {
IokeObject me = As(on, context);
me.CheckFrozen("removeMimic!", message, context);
int ix = me.MimicIndex(other);
if(ix != -1) {
me.RemoveMimicAt(ix);
if(me.body.hooks != null) {
Hook.FireMimicsChanged(me, message, context, other);
Hook.FireMimicRemoved(me, message, context, other);
}
}
}
public static void RemoveAllMimics(object on, IokeObject message, IokeObject context) {
IokeObject me = As(on, context);
me.CheckFrozen("removeAllMimics!", message, context);
if(me.body.mimicCount == 1) {
Hook.FireMimicsChanged(me, message, context, me.body.mimic);
Hook.FireMimicRemoved(me, message, context, me.body.mimic);
me.body.mimicCount--;
} else {
while(me.body.mimicCount > 0) {
Hook.FireMimicsChanged(me, message, context, me.body.mimics[me.body.mimicCount-1]);
Hook.FireMimicRemoved(me, message, context, me.body.mimics[me.body.mimicCount-1]);
me.body.mimicCount--;
}
}
me.body.mimic = null;
me.body.mimics = null;
}
public static void Freeze(object on) {
if(on is IokeObject) {
As(on,null).SetFrozen(true);
}
}
public static void Thaw(object on) {
if(on is IokeObject) {
As(on, null).SetFrozen(false);
}
}
public static IokeData dataOf(object on) {
return ((IokeObject)on).data;
}
public void SetDocumentation(string docs, IokeObject message, IokeObject context) {
CheckFrozen("documentation=", message, context);
this.body.documentation = docs;
}
public static object FindSuperCellOn(object obj, IokeObject early, IokeObject context, string name) {
return As(obj, context).MarkingFindSuperCell(early, name, new bool[]{false});
}
protected object RealMarkingFindSuperCell(IokeObject early, string name, bool[] found) {
if(body.Has(name)) {
if(found[0]) {
return body.Get(name);
}
if(early == body.Get(name)) {
found[0] = true;
}
}
if(body.mimicCount == 1) {
return body.mimic.MarkingFindSuperCell(early, name, found);
} else {
for(int i = 0; i<body.mimicCount; i++) {
object cell = body.mimics[i].MarkingFindSuperCell(early, name, found);
if(cell != runtime.nul) {
return cell;
}
}
return runtime.nul;
}
}
protected object MarkingFindSuperCell(IokeObject early, string name, bool[] found) {
object nn = RealMarkingFindSuperCell(early, name, found);
if(nn == runtime.nul && IsLexical) {
return ((LexicalContext)this.data).surroundingContext.RealMarkingFindSuperCell(early, name, new bool[]{false});
}
return nn;
}
public static object FindPlace(object obj, string name) {
return As(obj, null).MarkingFindPlace(name);
}
public static object FindPlace(object obj, IokeObject m, IokeObject context, string name) {
object result = FindPlace(obj, name);
if(result == m.runtime.nul) {
IokeObject condition = As(IokeObject.GetCellChain(m.runtime.Condition,
m,
context,
"Error",
"NoSuchCell"), context).Mimic(m, context);
condition.SetCell("message", m);
condition.SetCell("context", context);
condition.SetCell("receiver", obj);
condition.SetCell("cellName", m.runtime.GetSymbol(name));
m.runtime.WithReturningRestart("ignore", context, () => {condition.runtime.ErrorCondition(condition);});
}
return result;
}
public object FindPlace(string name) {
return MarkingFindPlace(name);
}
protected object MarkingFindPlace(string name) {
if(body.Has(name)) {
if(body.Get(name) == runtime.nul) {
if(IsLexical) {
return IokeObject.FindPlace(((LexicalContext)this.data).surroundingContext, name);
}
return runtime.nul;
}
return this;
} else {
if(body.mimic != null) {
object place = body.mimic.MarkingFindPlace(name);
if(place != runtime.nul) {
return place;
}
} else {
for(int i = 0; i<body.mimicCount; i++) {
object place = body.mimics[i].MarkingFindPlace(name);
if(place != runtime.nul) {
return place;
}
}
}
if(IsLexical) {
return IokeObject.FindPlace(((LexicalContext)this.data).surroundingContext, name);
}
return runtime.nul;
}
}
public static object FindCell(IokeObject on, string name) {
object cell;
IokeObject nul = on.runtime.nul;
IokeObject c = on;
while(true) {
Body b = c.body;
if((cell = b.Get(name)) != null) {
if(cell == nul && c.IsLexical) {
c = ((LexicalContext)c.data).surroundingContext;
} else {
return cell;
}
} else {
if(b.mimic != null) {
if(c.IsLexical) {
if((cell = FindCell(b.mimic, name)) != nul) {
return cell;
}
c = ((LexicalContext)c.data).surroundingContext;
} else {
c = b.mimic;
}
} else {
for(int i = 0; i<b.mimicCount; i++) {
if((cell = FindCell(b.mimics[i], name)) != nul) {
return cell;
}
}
if(c.IsLexical) {
c = ((LexicalContext)c.data).surroundingContext;
} else {
return nul;
}
}
}
}
}
public static void RemoveCell(object on, IokeObject m, IokeObject context, string name) {
((IokeObject)on).RemoveCell(m, context, name);
}
public static void UndefineCell(object on, IokeObject m, IokeObject context, string name) {
((IokeObject)on).UndefineCell(m, context, name);
}
public void RemoveCell(IokeObject m, IokeObject context, string name) {
CheckFrozen("removeCell!", m, context);
if(body.Has(name)) {
object prev = body.Remove(name);
if(body.hooks != null) {
Hook.FireCellChanged(this, m, context, name, prev);
Hook.FireCellRemoved(this, m, context, name, prev);
}
} else {
IokeObject condition = As(IokeObject.GetCellChain(runtime.Condition,
m,
context,
"Error",
"NoSuchCell"), context).Mimic(m, context);
condition.SetCell("message", m);
condition.SetCell("context", context);
condition.SetCell("receiver", this);
condition.SetCell("cellName", runtime.GetSymbol(name));
runtime.WithReturningRestart("ignore", context, ()=>{runtime.ErrorCondition(condition);});
}
}
public void UndefineCell(IokeObject m, IokeObject context, string name) {
CheckFrozen("undefineCell!", m, context);
object prev = runtime.nil;
if(body.Has(name)) {
prev = body.Get(name);
}
body.Put(name, runtime.nul);
if(body.hooks != null) {
if(prev == null) {
prev = runtime.nil;
}
Hook.FireCellChanged(this, m, context, name, prev);
Hook.FireCellUndefined(this, m, context, name, prev);
}
}
public void RegisterMethod(IokeObject m) {
body.Put(((Method)m.data).Name, m);
}
public void AliasMethod(string originalName, string newName, IokeObject message, IokeObject context) {
CheckFrozen("aliasMethod", message, context);
IokeObject io = As(FindCell(this, originalName), context);
IokeObject newObj = io.Mimic(null, null);
newObj.data = new AliasMethod(newName, io.data, io);
body.Put(newName, newObj);
}
public void RegisterCell(string name, object o) {
body.Put(name, o);
}
public static void Assign(object on, string name, object value, IokeObject context, IokeObject message) {
As(on, context).Assign(name, value, context, message);
}
public readonly static System.Text.RegularExpressions.Regex SLIGHTLY_BAD_CHARS = new System.Text.RegularExpressions.Regex("[!=\\.\\-\\+&|\\{\\[]");
public void Assign(string name, object value, IokeObject context, IokeObject message) {
if(IsLexical) {
object place = FindPlace(name);
if(place == runtime.nul) {
place = this;
}
IokeObject.SetCell(place, name, value, context);
} else {
CheckFrozen("=", message, context);
if(!SLIGHTLY_BAD_CHARS.Match(name).Success && FindCell(this, name + "=") != runtime.nul) {
IokeObject msg = runtime.CreateMessage(new Message(runtime, name + "=", runtime.CreateMessage(Message.Wrap(As(value, context)))));
Interpreter.Send(msg, context, this);
} else {
if(body.hooks != null) {
bool contains = body.Has(name);
object prev = runtime.nil;
if(contains) {
prev = body.Get(name);
}
body.Put(name, value);
if(!contains) {
Hook.FireCellAdded(this, message, context, name);
}
Hook.FireCellChanged(this, message, context, name, prev);
} else {
body.Put(name, value);
}
}
}
}
public static object GetCell(object on, IokeObject m, IokeObject context, string name) {
return ((IokeObject)on).GetCell(m, context, name);
}
public object Self {
get {
if(IsLexical) {
return ((LexicalContext)this.data).surroundingContext.Self;
} else {
return this.body.Get("self");
}
}
}
public object GetCell(IokeObject m, IokeObject context, string name) {
object cell = FindCell(this, name);
while(cell == runtime.nul) {
IokeObject condition = As(IokeObject.GetCellChain(runtime.Condition,
m,
context,
"Error",
"NoSuchCell"), context).Mimic(m, context);
condition.SetCell("message", m);
condition.SetCell("context", context);
condition.SetCell("receiver", this);
condition.SetCell("cellName", runtime.GetSymbol(name));
object[] newCell = new object[]{cell};
runtime.WithRestartReturningArguments(()=>{runtime.ErrorCondition(condition);}, context,
new UseValue(name, newCell),
new StoreValue(name, newCell, this));
cell = newCell[0];
}
return cell;
}
public static void SetCell(object on, string name, object value, IokeObject context) {
As(on, context).SetCell(name, value);
}
public static object SetCell(object on, IokeObject m, IokeObject context, string name, object value) {
((IokeObject)on).SetCell(name, value);
return value;
}
public void SetCell(string name, object o) {
body.Put(name, o);
}
public string Kind {
set { body.Put("kind", runtime.NewText(value)); }
}
public static object GetRealContext(object o) {
if(o is IokeObject) {
return As(o, null).RealContext;
}
return o;
}
public object RealContext {
get {
if(IsLexical) {
return ((LexicalContext)this.data).ground;
} else {
return this;
}
}
}
public virtual void Init() {
data.Init(this);
}
public IList Arguments {
get { return data.Arguments(this); }
}
public string Name {
get { return data.GetName(this); }
}
public string File {
get { return data.GetFile(this); }
}
public int Line {
get { return data.GetLine(this); }
}
public int Position {
get { return data.GetPosition(this); }
}
public override string ToString() {
return data.ToString(this);
}
public static IokeObject As(object on, IokeObject context) {
if(on is IokeObject) {
return ((IokeObject)on);
} else {
throw new System.Exception("Can't handle non-IokeObjects right now");
}
}
private void TransplantActivation(IokeObject mimic) {
if(!this.IsSetActivatable && mimic.IsSetActivatable) {
this.SetActivatable(mimic.IsActivatable);
}
}
public void SingleMimics(IokeObject mimic, IokeObject message, IokeObject context) {
CheckFrozen("mimic!", message, context);
mimic.data.CheckMimic(mimic, message, context);
body.mimic = mimic;
body.mimicCount = 1;
TransplantActivation(mimic);
if(mimic.body.hooks != null) {
Hook.FireMimicked(mimic, message, context, this);
}
if(body.hooks != null) {
Hook.FireMimicsChanged(this, message, context, mimic);
Hook.FireMimicAdded(this, message, context, mimic);
}
}
public void Mimics(IokeObject mimic, IokeObject message, IokeObject context) {
CheckFrozen("mimic!", message, context);
mimic.data.CheckMimic(mimic, message, context);
if(!ContainsMimic(mimic)) {
AddMimic(mimic);
TransplantActivation(mimic);
if(mimic.body.hooks != null) {
Hook.FireMimicked(mimic, message, context, this);
}
if(body.hooks != null) {
Hook.FireMimicsChanged(this, message, context, mimic);
Hook.FireMimicAdded(this, message, context, mimic);
}
}
}
public void Mimics(int index, IokeObject mimic, IokeObject message, IokeObject context) {
CheckFrozen("prependMimic!", message, context);
mimic.data.CheckMimic(mimic, message, context);
if(!ContainsMimic(mimic)) {
AddMimic(index, mimic);
TransplantActivation(mimic);
if(mimic.body.hooks != null) {
Hook.FireMimicked(mimic, message, context, this);
}
if(body.hooks != null) {
Hook.FireMimicsChanged(this, message, context, mimic);
Hook.FireMimicAdded(this, message, context, mimic);
}
}
}
public static IokeObject Mimic(object on, IokeObject message, IokeObject context) {
return As(on, context).Mimic(message, context);
}
public IokeObject Mimic(IokeObject message, IokeObject context) {
CheckFrozen("mimic!", message, context);
IokeObject clone = AllocateCopy(message, context);
clone.SingleMimics(this, message, context);
return clone;
}
public virtual bool IsSymbol {
get { return data.IsSymbol; }
}
public virtual bool IsMessage {
get { return data.IsMessage; }
}
public static bool IsObjectMessage(object obj) {
return (obj is IokeObject) && As(obj, null).IsMessage;
}
public static bool IsObjectTrue(object on) {
return !(on is IokeObject) || As(on, null).IsTrue;
}
public string GetKind(IokeObject message, IokeObject context) {
object obj = FindCell(this, "kind");
if(IokeObject.dataOf(obj) is Text) {
return ((Text)IokeObject.dataOf(obj)).GetText();
} else {
return ((Text)IokeObject.dataOf(Interpreter.GetOrActivate(obj, context, message, this))).GetText();
}
}
public string GetKind() {
object obj = FindCell(this, "kind");
if(obj != null && IokeObject.dataOf(obj) is Text) {
return ((Text)IokeObject.dataOf(obj)).GetText();
} else {
return null;
}
}
public bool HasKind {
get { return body.Has("kind"); }
}
public class UseValue : Restart.ArgumentGivingRestart {
string variableName;
object[] place;
public UseValue(string variableName, object[] place) : base("useValue") {
this.variableName = variableName;
this.place = place;
}
public override string Report() {
return "Use value for: " + variableName;
}
public override IList<string> ArgumentNames {
get { return new SaneList<string>() {"newValue"}; }
}
public override IokeObject Invoke(IokeObject context, IList arguments) {
place[0] = arguments[0];
return context.runtime.nil;
}
}
public class StoreValue : Restart.ArgumentGivingRestart {
string variableName;
object[] place;
IokeObject obj;
public StoreValue(string variableName, object[] place, IokeObject obj) : base("useValue") {
this.variableName = variableName;
this.place = place;
this.obj = obj;
}
public override string Report() {
return "Store value for: " + variableName;
}
public override IList<string> ArgumentNames {
get { return new SaneList<string>() {"newValue"}; }
}
public override IokeObject Invoke(IokeObject context, IList arguments) {
place[0] = arguments[0];
obj.SetCell(name, place[0]);
return context.runtime.nil;
}
}
public static object GetCellChain(object on, IokeObject m, IokeObject c, params string[] names) {
object current = on;
foreach(string name in names) {
current = GetCell(current, m, c, name);
}
return current;
}
public static bool IsKind(object on, string kind, IokeObject context) {
return As(on, context).IsKind(kind);
}
public static bool IsMimic(object on, IokeObject potentialMimic, IokeObject context) {
return As(on, context).IsMimic(potentialMimic);
}
public static bool IsKind(IokeObject on, string kind) {
return As(on, on).IsKind(kind);
}
public static bool IsMimic(IokeObject on, IokeObject potentialMimic) {
return As(on, on).IsMimic(potentialMimic);
}
private bool IsKind(string kind) {
if(body.Has("kind") && kind.Equals(Text.GetText(body.Get("kind")))) {
return true;
}
if(body.mimic != null) {
return body.mimic.IsKind(kind);
} else {
for(int i = 0; i<body.mimicCount; i++) {
if(body.mimics[i].IsKind(kind)) {
return true;
}
}
}
return false;
}
private bool IsMimic(IokeObject pot) {
if(this.body == pot.body || ContainsMimic(pot)) {
return true;
}
if(body.mimic != null) {
return body.mimic.IsMimic(pot);
} else {
for(int i = 0; i<body.mimicCount; i++) {
if(body.mimics[i].IsMimic(pot)) {
return true;
}
}
}
return false;
}
public static IokeObject ConvertToRational(object on, IokeObject m, IokeObject context, bool signalCondition) {
return ((IokeObject)on).ConvertToRational(m, context, signalCondition);
}
public static IokeObject ConvertToDecimal(object on, IokeObject m, IokeObject context, bool signalCondition) {
return ((IokeObject)on).ConvertToDecimal(m, context, signalCondition);
}
public IokeObject ConvertToRational(IokeObject m, IokeObject context, bool signalCondition) {
IokeObject result = data.ConvertToRational(this, m, context, false);
if(result == null) {
if(FindCell(this, "asRational") != context.runtime.nul) {
return IokeObject.As(Interpreter.Send(context.runtime.asRationalMessage, context, this), context);
}
if(signalCondition) {
return data.ConvertToRational(this, m, context, true);
}
return context.runtime.nil;
}
return result;
}
public IokeObject ConvertToDecimal(IokeObject m, IokeObject context, bool signalCondition) {
IokeObject result = data.ConvertToDecimal(this, m, context, false);
if(result == null) {
if(FindCell(this, "asDecimal") != context.runtime.nul) {
return IokeObject.As(Interpreter.Send(context.runtime.asDecimalMessage, context, this), context);
}
if(signalCondition) {
return data.ConvertToDecimal(this, m, context, true);
}
return context.runtime.nil;
}
return result;
}
public static IokeObject ConvertToNumber(object on, IokeObject m, IokeObject context) {
return ((IokeObject)on).ConvertToNumber(m, context);
}
public IokeObject ConvertToNumber(IokeObject m, IokeObject context) {
return data.ConvertToNumber(this, m, context);
}
public static string Inspect(object on) {
if(on is IokeObject) {
IokeObject ion = (IokeObject)on;
Runtime runtime = ion.runtime;
return Text.GetText(Interpreter.Send(runtime.inspectMessage, ion, ion));
} else {
return on.ToString();
}
}
public static string Notice(object on) {
if(on is IokeObject) {
IokeObject ion = (IokeObject)on;
Runtime runtime = ion.runtime;
return Text.GetText(Interpreter.Send(runtime.noticeMessage, ion, ion));
} else {
return on.ToString();
}
}
public static IokeObject ConvertToText(object on, IokeObject m, IokeObject context, bool signalCondition) {
return ((IokeObject)on).ConvertToText(m, context, signalCondition);
}
public static IokeObject TryConvertToText(object on, IokeObject m, IokeObject context) {
return ((IokeObject)on).TryConvertToText(m, context);
}
public static IokeObject ConvertToRegexp(object on, IokeObject m, IokeObject context) {
return ((IokeObject)on).ConvertToRegexp(m, context);
}
public IokeObject ConvertToRegexp(IokeObject m, IokeObject context) {
return data.ConvertToRegexp(this, m, context);
}
public static IokeObject ConvertToSymbol(object on, IokeObject m, IokeObject context, bool signalCondition) {
return ((IokeObject)on).ConvertToSymbol(m, context, signalCondition);
}
public IokeObject ConvertToSymbol(IokeObject m, IokeObject context, bool signalCondition) {
IokeObject result = data.ConvertToSymbol(this, m, context, false);
if(result == null) {
if(FindCell(this, "asSymbol") != context.runtime.nul) {
return As(Interpreter.Send(context.runtime.asSymbolMessage, context, this), context);
}
if(signalCondition) {
return data.ConvertToSymbol(this, m, context, true);
}
return context.runtime.nil;
}
return result;
}
public IokeObject ConvertToText(IokeObject m, IokeObject context, bool signalCondition) {
IokeObject result = data.ConvertToText(this, m, context, false);
if(result == null) {
if(FindCell(this, "asText") != context.runtime.nul) {
return As(Interpreter.Send(context.runtime.asText, context, this), context);
}
if(signalCondition) {
return data.ConvertToText(this, m, context, true);
}
return context.runtime.nil;
}
return result;
}
public IokeObject TryConvertToText(IokeObject m, IokeObject context) {
return data.TryConvertToText(this, m, context);
}
public static object ConvertTo(string kind, object on, bool signalCondition, string conversionMethod, IokeObject message, IokeObject context) {
return ((IokeObject)on).ConvertTo(kind, signalCondition, conversionMethod, message, context);
}
public static object ConvertTo(object mimic, object on, bool signalCondition, string conversionMethod, IokeObject message, IokeObject context) {
return ((IokeObject)on).ConvertTo(mimic, signalCondition, conversionMethod, message, context);
}
public object ConvertTo(string kind, bool signalCondition, string conversionMethod, IokeObject message, IokeObject context) {
object result = data.ConvertTo(this, kind, false, conversionMethod, message, context);
if(result == null) {
if(conversionMethod != null && FindCell(this, conversionMethod) != context.runtime.nul) {
IokeObject msg = context.runtime.NewMessage(conversionMethod);
return Interpreter.Send(msg, context, this);
}
if(signalCondition) {
return data.ConvertTo(this, kind, true, conversionMethod, message, context);
}
return context.runtime.nul;
}
return result;
}
public object ConvertTo(object mimic, bool signalCondition, string conversionMethod, IokeObject message, IokeObject context) {
object result = data.ConvertTo(this, mimic, false, conversionMethod, message, context);
if(result == null) {
if(conversionMethod != null && FindCell(this, conversionMethod) != context.runtime.nul) {
IokeObject msg = context.runtime.NewMessage(conversionMethod);
return Interpreter.Send(msg, context, this);
}
if(signalCondition) {
return data.ConvertTo(this, mimic, true, conversionMethod, message, context);
}
return context.runtime.nul;
}
return result;
}
public object ConvertToMimic(object on, IokeObject message, IokeObject context, bool signal) {
return ConvertToThis(on, signal, message, context);
}
public object ConvertToThis(object on, IokeObject message, IokeObject context) {
return ConvertToThis(on, true, message, context);
}
public object ConvertToThis(object on, bool signalCondition, IokeObject message, IokeObject context) {
if(on is IokeObject) {
if(IokeObject.dataOf(on).GetType().Equals(data.GetType())) {
return on;
} else {
return IokeObject.ConvertTo(this, on, signalCondition, IokeObject.dataOf(on).ConvertMethod, message, context);
}
} else {
if(signalCondition) {
throw new System.Exception("oh no. -(: " + message.Name);
} else {
return context.runtime.nul;
}
}
}
public override bool Equals(object other) {
try {
return IsEqualTo(other);
} catch(System.Exception) {
return false;
}
}
public override int GetHashCode() {
return IokeHashCode();
}
public new static bool Equals(object lhs, object rhs) {
return ((IokeObject)lhs).IsEqualTo(rhs);
}
public bool IsEqualTo(object other) {
return data.IsEqualTo(this, other);
}
public int IokeHashCode() {
return data.HashCode(this);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using Newtonsoft.Json;
namespace TheDylanKit
{
/// <summary>
/// A request that has an object that will be serialized as json to form a request.
/// </summary>
public class HttpRequestMessage
{
/// <summary>
/// 'application/json' Content-Type.
/// </summary>
public const string ContentTypeApplicationJson = "application/json";
#region Fields and Properties
/// <summary>
/// The method of the HttpRequestMessage.
/// </summary>
public HttpMethod Method { get; set; }
/// <summary>
/// The URI to be requested by the HttpRequestMessage.
/// </summary>
public Uri RequestUri { get; set; }
/// <summary>
/// The version of the HttpRequestMessage.
/// </summary>
public Version Version { get; set; }
/// <summary>
/// The content that will be sent as the body.
/// This will be serialized to JSON by the HttpClient.
/// </summary>
/// <remarks>
/// When you set this, even if you set it to null, HasContent will return true.
/// To revert HasContent to returning false, call ClearContent().
/// </remarks>
public object Content {
get => _content;
set
{
HasContent = true;
_content = value;
}
}
// Content backing field.
private object _content;
/// <summary>
/// If this request message has had content set on it.
/// </summary>
public bool HasContent { get; private set; }
/// <summary>
/// The properties of the HttpRequestMessage.
/// </summary>
public IDictionary<string, object> Properties
{
get => _properties ?? (_properties = new Dictionary<string, object>());
set => _properties = value;
}
// Lazy initialized backing variable
private IDictionary<string, object> _properties;
/// <summary>
/// The headers of the HttpRequestMessage.
/// </summary>
public IDictionary<string, List<string>> Headers
{
get => _headers ?? (_headers = new Dictionary<string, List<string>>());
set => _headers = value;
}
// Lazy initialized backing variable
private IDictionary<string, List<string>> _headers;
#endregion
#region Constructors
/// <summary>
/// Initializes an empty HttpRequestMessage.
/// </summary>
public HttpRequestMessage()
{
#if uap
Version = new Version(2, 0);
#else
Version = new Version(1, 1);
#endif
}
/// <summary>
/// Initializes an HttpRequestMessage.
/// </summary>
/// <param name="content">The content to send as the body.</param>
/// <param name="method">The method to envoke.</param>
public HttpRequestMessage(object content, HttpMethod method) : this()
{
Content = content;
Method = method;
RequestUri = new Uri(string.Empty, UriKind.RelativeOrAbsolute);
}
/// <summary>
/// Initializes an HttpRequestMessage.
/// </summary>
/// <param name="method">The method to envoke.</param>
public HttpRequestMessage(HttpMethod method) : this()
{
Method = method;
RequestUri = new Uri(string.Empty, UriKind.RelativeOrAbsolute);
}
/// <summary>
/// Initializes an HttpRequestMessage.
/// </summary>
/// <param name="content">The content to send as the body.</param>
/// <param name="method">The method to envoke.</param>
/// <param name="requestUri">The uri to request.</param>
public HttpRequestMessage(object content, HttpMethod method, string requestUri) : this()
{
Content = content;
Method = method;
if (!string.IsNullOrEmpty(requestUri))
{
RequestUri = new Uri(requestUri, UriKind.RelativeOrAbsolute);
}
}
/// <summary>
/// Initializes an HttpRequestMessage.
/// </summary>
/// <param name="content">The content to send as the body.</param>
/// <param name="method">The method to envoke.</param>
/// <param name="requestUri">The uri to request.</param>
public HttpRequestMessage(object content, HttpMethod method, Uri requestUri) : this()
{
Content = content;
Method = method;
RequestUri = requestUri;
}
/// <summary>
/// Initializes an HttpRequestMessage.
/// </summary>
/// <param name="method">The method to envoke.</param>
/// <param name="requestUri">The uri to request.</param>
public HttpRequestMessage(HttpMethod method, string requestUri) : this()
{
Method = method;
if (!string.IsNullOrEmpty(requestUri))
{
RequestUri = new Uri(requestUri, UriKind.RelativeOrAbsolute);
}
}
/// <summary>
/// Initializes an HttpRequestMessage.
/// </summary>
/// <param name="method">The method to envoke.</param>
/// <param name="requestUri">The uri to request.</param>
public HttpRequestMessage(HttpMethod method, Uri requestUri) : this()
{
Method = method;
RequestUri = requestUri;
}
#endregion
/// <summary>
/// Clears the content from the request message.
/// The content object will be set to null and HasContent will return false.
/// Normally, HasContent will remain true, even if you set it to null, which means it has null content.
/// </summary>
public void ClearContent()
{
Content = null;
HasContent = false;
}
/// <summary>
/// Adds a header to the HttpRequestMessage.
/// </summary>
/// <param name="headerKey">The key of the header.</param>
/// <param name="headerValue">The value of the header.</param>
public void AddHeader(string headerKey, string headerValue)
{
List<string> headerValues;
if (!Headers.TryGetValue(headerKey, out headerValues))
{
headerValues = new List<string>();
Headers.Add(headerKey, headerValues);
}
headerValues.Add(headerValue);
}
/// <summary>
/// Adds all header values to the HttpRequestMessage.
/// </summary>
/// <param name="headerKey">The key of the header.</param>
/// <param name="headerValues">The value of the header.</param>
public void AddHeaders(string headerKey, IEnumerable<string> headerValues)
{
if (headerValues == null)
{
return;
}
List<string> currentHeaderValues;
if (!Headers.TryGetValue(headerKey, out currentHeaderValues))
{
currentHeaderValues = new List<string>();
Headers.Add(headerKey, currentHeaderValues);
}
currentHeaderValues.AddRange(headerValues);
}
/// <summary>
/// Adds all header values to the HttpRequestMessage.
/// </summary>
/// <param name="headers">All the headers to add.</param>
public void AddHeaders(IDictionary<string, IEnumerable<string>> headers)
{
if(headers == null)
{
return;
}
foreach (var headerList in headers)
{
this.AddHeaders(headerList.Key, headerList.Value);
}
}
/// <summary>
/// Adds all header values to the HttpRequestMessage.
/// </summary>
/// <param name="headers">All the headers to add.</param>
public void AddHeaders(IDictionary<string, List<string>> headers)
{
if (headers == null)
{
return;
}
foreach (var headerList in headers)
{
this.AddHeaders(headerList.Key, headerList.Value);
}
}
/// <summary>
/// Adds all header values to the HttpRequestMessage.
/// </summary>
/// <param name="headers">All the headers to add.</param>
public void AddHeaders(IDictionary<string, IList<string>> headers)
{
foreach (var headerList in headers)
{
this.AddHeaders(headerList.Key, headerList.Value);
}
}
/// <summary>
/// Removes a header from the HttpRequestMessage.
/// </summary>
/// <param name="headerKey">The key of the header.</param>
/// <param name="headerValue">The value of the header.</param>
/// <returns>If a header was removed.</returns>
public bool RemoveHeader(string headerKey, string headerValue)
{
if (!Headers.TryGetValue(headerKey, out List<string> headerValues))
{
return false;
}
return headerValues.Remove(headerValue);
}
/// <summary>
/// Removes all header values from the HttpRequestMessage with the given key.
/// </summary>
/// <param name="headerKey">The key of the header.</param>
/// <returns>If a header was removed.</returns>
public bool RemoveHeader(string headerKey)
{
if (!Headers.TryGetValue(headerKey, out List<string> headerValues))
{
return false;
}
return Headers.Remove(headerKey);
}
/// <summary>
/// Applies all the properties from this HttpRequestMessage onto the System.Net.Http.HttpRequestMessage.
/// </summary>
/// <param name="httpRequestMessage">Message to apply this object's properties onto.</param>
public void ApplyPropertiesOnto(System.Net.Http.HttpRequestMessage httpRequestMessage)
{
foreach (var prop in Properties)
{
httpRequestMessage.Properties.Add(prop);
}
}
/// <summary>
/// Applies all the headers from this HttpRequestMessage onto the System.Net.Http.HttpRequestMessage.
/// </summary>
/// <param name="httpRequestMessage">Message to apply this object's headers onto.</param>
public void ApplyHeadersOnto(System.Net.Http.HttpRequestMessage httpRequestMessage)
{
foreach (var header in Headers)
{
httpRequestMessage.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
/// <summary>
/// Applies all the headers and the properties from this HttpRequestMessage onto the System.Net.Http.HttpRequestMessage.
/// </summary>
/// <param name="httpRequestMessage">Message to apply this object's headers and properties onto.</param>
public void ApplyHeadersAndPropertiesOnto(System.Net.Http.HttpRequestMessage httpRequestMessage)
{
ApplyPropertiesOnto(httpRequestMessage);
ApplyHeadersOnto(httpRequestMessage);
}
/// <summary>
/// Returns a mostly deep clone of the HttpRequestMessage.
/// The content object will reference the same object, and references in the Properties will be the same references, however the dictionaries will be deep cloned.
/// </summary>
/// <returns>A mostly deep clone of this object.</returns>
public HttpRequestMessage DeepClone()
{
return new HttpRequestMessage()
{
Version = Version,
RequestUri = RequestUri,
Method = Method,
Content = Content,
Properties = Properties.ToDictionary(i => i.Key, i => i.Value),
Headers = Headers.ToDictionary(i => i.Key, i=> i.Value.ToList())
};
}
/// <summary>
/// Tries to create a System.Net.Http.HttpRequestMessage using this as the base.
/// If an exception occurs while serializing content, it will be output and false will be returned.
/// If it is successful, the HttpRequestMessage object will be output and true will be returned.
/// </summary>
/// <param name="httpRequestMessage">The HttpRequestMessage trying to be created.</param>
/// <param name="serializationException">An exception that can occur while serializing content.</param>
/// <returns>If the message was successfully created without any exceptions or not.</returns>
public bool TryCreateHttpRequestMessage(out System.Net.Http.HttpRequestMessage httpRequestMessage, out Exception serializationException)
{
return TryCreateHttpRequestMessage(null, out httpRequestMessage, out serializationException);
}
/// <summary>
/// Tries to create a System.Net.Http.HttpRequestMessage using this as the base.
/// If an exception occurs while serializing content, it will be output and false will be returned.
/// If it is successful, the HttpRequestMessage object will be output and true will be returned.
/// </summary>
/// <param name="jsonSerializerSettings">Settings used to serialize the content.</param>
/// <param name="httpRequestMessage">The HttpRequestMessage trying to be created.</param>
/// <param name="serializationException">An exception that can occur while serializing content.</param>
/// <returns>If the message was successfully created without any exceptions or not.</returns>
public bool TryCreateHttpRequestMessage(JsonSerializerSettings jsonSerializerSettings, out System.Net.Http.HttpRequestMessage httpRequestMessage, out Exception serializationException)
{
string serializedContent = null;
if (Content != null)
{
try
{
serializedContent = JsonConvert.SerializeObject(Content, jsonSerializerSettings);
}
catch (Exception exception)
{
serializationException = exception;
httpRequestMessage = null;
return false;
}
}
serializationException = null;
httpRequestMessage = new System.Net.Http.HttpRequestMessage(Method, RequestUri);
if (serializedContent != null)
{
var stringContent = new StringContent(serializedContent, Encoding.UTF8, ContentTypeApplicationJson);
httpRequestMessage.Content = stringContent;
}
ApplyHeadersAndPropertiesOnto(httpRequestMessage);
return true;
}
/// <summary>
/// Creates a System.Net.Http.HttpRequestMessage using this as the base.
/// This method will ignore any content on this message and instead attach the given serialized content to the message.
/// </summary>
/// <param name="serializedContent">Content to attach to the method. This will be attached as content instead of what is on this message.</param>
/// <returns>The created HttpRequestMessage.</returns>
public System.Net.Http.HttpRequestMessage CreateHttpRequestMessage(string serializedContent)
{
var httpRequestMessage = new System.Net.Http.HttpRequestMessage(Method, RequestUri);
if (serializedContent != null)
{
var stringContent = new StringContent(serializedContent, Encoding.UTF8, ContentTypeApplicationJson);
httpRequestMessage.Content = stringContent;
}
ApplyHeadersAndPropertiesOnto(httpRequestMessage);
return httpRequestMessage;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Buffers;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNetCore.Server.IIS.Core
{
internal class IISHttpServer : IServer
{
private const string WebSocketVersionString = "WEBSOCKET_VERSION";
private IISContextFactory? _iisContextFactory;
private readonly MemoryPool<byte> _memoryPool = new PinnedBlockMemoryPool();
private GCHandle _httpServerHandle;
private readonly IHostApplicationLifetime _applicationLifetime;
private readonly ILogger<IISHttpServer> _logger;
private readonly IISServerOptions _options;
private readonly IISNativeApplication _nativeApplication;
private readonly ServerAddressesFeature _serverAddressesFeature;
private readonly TaskCompletionSource _shutdownSignal = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
private bool? _websocketAvailable;
private CancellationTokenRegistration _cancellationTokenRegistration;
private bool _disposed;
public IFeatureCollection Features { get; } = new FeatureCollection();
// TODO: Remove pInProcessHandler argument
public bool IsWebSocketAvailable(NativeSafeHandle pInProcessHandler)
{
// Check if the Http upgrade feature is available in IIS.
// To check this, we can look at the server variable WEBSOCKET_VERSION
// And see if there is a version. Same check that Katana did:
// https://github.com/aspnet/AspNetKatana/blob/9f6e09af6bf203744feb5347121fe25f6eec06d8/src/Microsoft.Owin.Host.SystemWeb/OwinAppContext.cs#L125
// Actively not locking here as acquiring a lock on every request will hurt perf more than checking the
// server variables a few extra times if a bunch of requests hit the server at the same time.
if (!_websocketAvailable.HasValue)
{
_websocketAvailable = NativeMethods.HttpTryGetServerVariable(pInProcessHandler, WebSocketVersionString, out var webSocketsSupported)
&& !string.IsNullOrEmpty(webSocketsSupported);
}
return _websocketAvailable.Value;
}
public IISHttpServer(
IISNativeApplication nativeApplication,
IHostApplicationLifetime applicationLifetime,
IAuthenticationSchemeProvider authentication,
IOptions<IISServerOptions> options,
ILogger<IISHttpServer> logger
)
{
_nativeApplication = nativeApplication;
_applicationLifetime = applicationLifetime;
_logger = logger;
_options = options.Value;
_serverAddressesFeature = new ServerAddressesFeature();
if (_options.ForwardWindowsAuthentication)
{
authentication.AddScheme(new AuthenticationScheme(IISServerDefaults.AuthenticationScheme, _options.AuthenticationDisplayName, typeof(IISServerAuthenticationHandlerInternal)));
}
Features.Set<IServerAddressesFeature>(_serverAddressesFeature);
if (_options.MaxRequestBodySize > _options.IisMaxRequestSizeLimit)
{
_logger.LogWarning(CoreStrings.MaxRequestLimitWarning);
}
}
public unsafe Task StartAsync<TContext>(IHttpApplication<TContext> application, CancellationToken cancellationToken) where TContext : notnull
{
_httpServerHandle = GCHandle.Alloc(this);
_iisContextFactory = new IISContextFactory<TContext>(_memoryPool, application, _options, this, _logger);
_nativeApplication.RegisterCallbacks(
&HandleRequest,
&HandleShutdown,
&OnDisconnect,
&OnAsyncCompletion,
&OnRequestsDrained,
(IntPtr)_httpServerHandle,
(IntPtr)_httpServerHandle);
_serverAddressesFeature.Addresses = _options.ServerAddresses;
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
_nativeApplication.StopIncomingRequests();
_cancellationTokenRegistration = cancellationToken.Register((shutdownSignal) =>
{
((TaskCompletionSource)shutdownSignal!).TrySetResult();
},
_shutdownSignal);
return _shutdownSignal.Task;
}
public void Dispose()
{
if (_disposed)
{
return;
}
_disposed = true;
// Block any more calls into managed from native as we are unloading.
_nativeApplication.StopCallsIntoManaged();
_shutdownSignal.TrySetResult();
if (_httpServerHandle.IsAllocated)
{
_httpServerHandle.Free();
}
_memoryPool.Dispose();
_nativeApplication.Dispose();
}
[UnmanagedCallersOnly]
private static NativeMethods.REQUEST_NOTIFICATION_STATUS HandleRequest(IntPtr pInProcessHandler, IntPtr pvRequestContext)
{
IISHttpServer? server = null;
try
{
// Unwrap the server so we can create an http context and process the request
server = (IISHttpServer?)GCHandle.FromIntPtr(pvRequestContext).Target;
// server can be null if ungraceful shutdown.
if (server == null)
{
return NativeMethods.REQUEST_NOTIFICATION_STATUS.RQ_NOTIFICATION_FINISH_REQUEST;
}
var safehandle = new NativeSafeHandle(pInProcessHandler);
Debug.Assert(server._iisContextFactory != null, "StartAsync must be called first.");
var context = server._iisContextFactory.CreateHttpContext(safehandle);
ThreadPool.UnsafeQueueUserWorkItem(context, preferLocal: false);
return NativeMethods.REQUEST_NOTIFICATION_STATUS.RQ_NOTIFICATION_PENDING;
}
catch (Exception ex)
{
server?._logger.LogError(0, ex, $"Unexpected exception in static {nameof(IISHttpServer)}.{nameof(HandleRequest)}.");
return NativeMethods.REQUEST_NOTIFICATION_STATUS.RQ_NOTIFICATION_FINISH_REQUEST;
}
}
[UnmanagedCallersOnly]
private static int HandleShutdown(IntPtr pvRequestContext)
{
IISHttpServer? server = null;
try
{
server = (IISHttpServer?)GCHandle.FromIntPtr(pvRequestContext).Target;
// server can be null if ungraceful shutdown.
if (server == null)
{
// return value isn't checked.
return 1;
}
server._applicationLifetime.StopApplication();
}
catch (Exception ex)
{
server?._logger.LogError(0, ex, $"Unexpected exception in {nameof(IISHttpServer)}.{nameof(HandleShutdown)}.");
}
return 1;
}
[UnmanagedCallersOnly]
private static void OnDisconnect(IntPtr pvManagedHttpContext)
{
IISHttpContext? context = null;
try
{
context = (IISHttpContext?)GCHandle.FromIntPtr(pvManagedHttpContext).Target;
// Context can be null if ungraceful shutdown.
if (context == null)
{
return;
}
context.AbortIO(clientDisconnect: true);
}
catch (Exception ex)
{
context?.Server._logger.LogError(0, ex, $"Unexpected exception in {nameof(IISHttpServer)}.{nameof(OnDisconnect)}.");
}
}
[UnmanagedCallersOnly]
private static NativeMethods.REQUEST_NOTIFICATION_STATUS OnAsyncCompletion(IntPtr pvManagedHttpContext, int hr, int bytes)
{
IISHttpContext? context = null;
try
{
context = (IISHttpContext?)GCHandle.FromIntPtr(pvManagedHttpContext).Target;
// Context can be null if ungraceful shutdown.
if (context == null)
{
return NativeMethods.REQUEST_NOTIFICATION_STATUS.RQ_NOTIFICATION_FINISH_REQUEST;
}
context.OnAsyncCompletion(hr, bytes);
return NativeMethods.REQUEST_NOTIFICATION_STATUS.RQ_NOTIFICATION_PENDING;
}
catch (Exception ex)
{
context?.Server._logger.LogError(0, ex, $"Unexpected exception in {nameof(IISHttpServer)}.{nameof(OnAsyncCompletion)}.");
return NativeMethods.REQUEST_NOTIFICATION_STATUS.RQ_NOTIFICATION_FINISH_REQUEST;
}
}
[UnmanagedCallersOnly]
private static void OnRequestsDrained(IntPtr serverContext)
{
IISHttpServer? server = null;
try
{
server = (IISHttpServer?)GCHandle.FromIntPtr(serverContext).Target;
// server can be null if ungraceful shutdown.
if (server == null)
{
return;
}
server._nativeApplication.StopCallsIntoManaged();
server._shutdownSignal.TrySetResult();
server._cancellationTokenRegistration.Dispose();
}
catch (Exception ex)
{
server?._logger.LogError(0, ex, $"Unexpected exception in {nameof(IISHttpServer)}.{nameof(OnRequestsDrained)}.");
}
}
private class IISContextFactory<T> : IISContextFactory where T : notnull
{
private const string Latin1Suppport = "Microsoft.AspNetCore.Server.IIS.Latin1RequestHeaders";
private readonly IHttpApplication<T> _application;
private readonly MemoryPool<byte> _memoryPool;
private readonly IISServerOptions _options;
private readonly IISHttpServer _server;
private readonly ILogger _logger;
private readonly bool _useLatin1;
public IISContextFactory(MemoryPool<byte> memoryPool, IHttpApplication<T> application, IISServerOptions options, IISHttpServer server, ILogger logger)
{
_application = application;
_memoryPool = memoryPool;
_options = options;
_server = server;
_logger = logger;
AppContext.TryGetSwitch(Latin1Suppport, out _useLatin1);
}
public IISHttpContext CreateHttpContext(NativeSafeHandle pInProcessHandler)
{
return new IISHttpContextOfT<T>(_memoryPool, _application, pInProcessHandler, _options, _server, _logger, _useLatin1);
}
}
}
// Over engineering to avoid allocations...
internal interface IISContextFactory
{
IISHttpContext CreateHttpContext(NativeSafeHandle pInProcessHandler);
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the AprVisitaDomiciliarium class.
/// </summary>
[Serializable]
public partial class AprVisitaDomiciliariumCollection : ActiveList<AprVisitaDomiciliarium, AprVisitaDomiciliariumCollection>
{
public AprVisitaDomiciliariumCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>AprVisitaDomiciliariumCollection</returns>
public AprVisitaDomiciliariumCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
AprVisitaDomiciliarium o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the APR_VisitaDomiciliaria table.
/// </summary>
[Serializable]
public partial class AprVisitaDomiciliarium : ActiveRecord<AprVisitaDomiciliarium>, IActiveRecord
{
#region .ctors and Default Settings
public AprVisitaDomiciliarium()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public AprVisitaDomiciliarium(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public AprVisitaDomiciliarium(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public AprVisitaDomiciliarium(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("APR_VisitaDomiciliaria", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdVisitaDomiciliaria = new TableSchema.TableColumn(schema);
colvarIdVisitaDomiciliaria.ColumnName = "idVisitaDomiciliaria";
colvarIdVisitaDomiciliaria.DataType = DbType.Int32;
colvarIdVisitaDomiciliaria.MaxLength = 0;
colvarIdVisitaDomiciliaria.AutoIncrement = true;
colvarIdVisitaDomiciliaria.IsNullable = false;
colvarIdVisitaDomiciliaria.IsPrimaryKey = true;
colvarIdVisitaDomiciliaria.IsForeignKey = false;
colvarIdVisitaDomiciliaria.IsReadOnly = false;
colvarIdVisitaDomiciliaria.DefaultSetting = @"";
colvarIdVisitaDomiciliaria.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdVisitaDomiciliaria);
TableSchema.TableColumn colvarIdPaciente = new TableSchema.TableColumn(schema);
colvarIdPaciente.ColumnName = "idPaciente";
colvarIdPaciente.DataType = DbType.Int32;
colvarIdPaciente.MaxLength = 0;
colvarIdPaciente.AutoIncrement = false;
colvarIdPaciente.IsNullable = false;
colvarIdPaciente.IsPrimaryKey = false;
colvarIdPaciente.IsForeignKey = false;
colvarIdPaciente.IsReadOnly = false;
colvarIdPaciente.DefaultSetting = @"";
colvarIdPaciente.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdPaciente);
TableSchema.TableColumn colvarIdMotivoVisitaDomiciliaria = new TableSchema.TableColumn(schema);
colvarIdMotivoVisitaDomiciliaria.ColumnName = "idMotivoVisitaDomiciliaria";
colvarIdMotivoVisitaDomiciliaria.DataType = DbType.Int32;
colvarIdMotivoVisitaDomiciliaria.MaxLength = 0;
colvarIdMotivoVisitaDomiciliaria.AutoIncrement = false;
colvarIdMotivoVisitaDomiciliaria.IsNullable = false;
colvarIdMotivoVisitaDomiciliaria.IsPrimaryKey = false;
colvarIdMotivoVisitaDomiciliaria.IsForeignKey = true;
colvarIdMotivoVisitaDomiciliaria.IsReadOnly = false;
colvarIdMotivoVisitaDomiciliaria.DefaultSetting = @"";
colvarIdMotivoVisitaDomiciliaria.ForeignKeyTableName = "APR_MotivoVisitaDomiciliaria";
schema.Columns.Add(colvarIdMotivoVisitaDomiciliaria);
TableSchema.TableColumn colvarFecha = new TableSchema.TableColumn(schema);
colvarFecha.ColumnName = "Fecha";
colvarFecha.DataType = DbType.DateTime;
colvarFecha.MaxLength = 0;
colvarFecha.AutoIncrement = false;
colvarFecha.IsNullable = false;
colvarFecha.IsPrimaryKey = false;
colvarFecha.IsForeignKey = false;
colvarFecha.IsReadOnly = false;
colvarFecha.DefaultSetting = @"";
colvarFecha.ForeignKeyTableName = "";
schema.Columns.Add(colvarFecha);
TableSchema.TableColumn colvarOtroMotivo = new TableSchema.TableColumn(schema);
colvarOtroMotivo.ColumnName = "OtroMotivo";
colvarOtroMotivo.DataType = DbType.AnsiString;
colvarOtroMotivo.MaxLength = 50;
colvarOtroMotivo.AutoIncrement = false;
colvarOtroMotivo.IsNullable = true;
colvarOtroMotivo.IsPrimaryKey = false;
colvarOtroMotivo.IsForeignKey = false;
colvarOtroMotivo.IsReadOnly = false;
colvarOtroMotivo.DefaultSetting = @"";
colvarOtroMotivo.ForeignKeyTableName = "";
schema.Columns.Add(colvarOtroMotivo);
TableSchema.TableColumn colvarPersonal = new TableSchema.TableColumn(schema);
colvarPersonal.ColumnName = "Personal";
colvarPersonal.DataType = DbType.AnsiString;
colvarPersonal.MaxLength = 50;
colvarPersonal.AutoIncrement = false;
colvarPersonal.IsNullable = false;
colvarPersonal.IsPrimaryKey = false;
colvarPersonal.IsForeignKey = false;
colvarPersonal.IsReadOnly = false;
colvarPersonal.DefaultSetting = @"";
colvarPersonal.ForeignKeyTableName = "";
schema.Columns.Add(colvarPersonal);
TableSchema.TableColumn colvarObservacion = new TableSchema.TableColumn(schema);
colvarObservacion.ColumnName = "Observacion";
colvarObservacion.DataType = DbType.AnsiString;
colvarObservacion.MaxLength = 2147483647;
colvarObservacion.AutoIncrement = false;
colvarObservacion.IsNullable = true;
colvarObservacion.IsPrimaryKey = false;
colvarObservacion.IsForeignKey = false;
colvarObservacion.IsReadOnly = false;
colvarObservacion.DefaultSetting = @"";
colvarObservacion.ForeignKeyTableName = "";
schema.Columns.Add(colvarObservacion);
TableSchema.TableColumn colvarCreatedBy = new TableSchema.TableColumn(schema);
colvarCreatedBy.ColumnName = "CreatedBy";
colvarCreatedBy.DataType = DbType.AnsiString;
colvarCreatedBy.MaxLength = 50;
colvarCreatedBy.AutoIncrement = false;
colvarCreatedBy.IsNullable = true;
colvarCreatedBy.IsPrimaryKey = false;
colvarCreatedBy.IsForeignKey = false;
colvarCreatedBy.IsReadOnly = false;
colvarCreatedBy.DefaultSetting = @"";
colvarCreatedBy.ForeignKeyTableName = "";
schema.Columns.Add(colvarCreatedBy);
TableSchema.TableColumn colvarCreatedOn = new TableSchema.TableColumn(schema);
colvarCreatedOn.ColumnName = "CreatedOn";
colvarCreatedOn.DataType = DbType.DateTime;
colvarCreatedOn.MaxLength = 0;
colvarCreatedOn.AutoIncrement = false;
colvarCreatedOn.IsNullable = true;
colvarCreatedOn.IsPrimaryKey = false;
colvarCreatedOn.IsForeignKey = false;
colvarCreatedOn.IsReadOnly = false;
colvarCreatedOn.DefaultSetting = @"";
colvarCreatedOn.ForeignKeyTableName = "";
schema.Columns.Add(colvarCreatedOn);
TableSchema.TableColumn colvarModifiedBy = new TableSchema.TableColumn(schema);
colvarModifiedBy.ColumnName = "ModifiedBy";
colvarModifiedBy.DataType = DbType.AnsiString;
colvarModifiedBy.MaxLength = 50;
colvarModifiedBy.AutoIncrement = false;
colvarModifiedBy.IsNullable = true;
colvarModifiedBy.IsPrimaryKey = false;
colvarModifiedBy.IsForeignKey = false;
colvarModifiedBy.IsReadOnly = false;
colvarModifiedBy.DefaultSetting = @"";
colvarModifiedBy.ForeignKeyTableName = "";
schema.Columns.Add(colvarModifiedBy);
TableSchema.TableColumn colvarModifiedOn = new TableSchema.TableColumn(schema);
colvarModifiedOn.ColumnName = "ModifiedOn";
colvarModifiedOn.DataType = DbType.DateTime;
colvarModifiedOn.MaxLength = 0;
colvarModifiedOn.AutoIncrement = false;
colvarModifiedOn.IsNullable = true;
colvarModifiedOn.IsPrimaryKey = false;
colvarModifiedOn.IsForeignKey = false;
colvarModifiedOn.IsReadOnly = false;
colvarModifiedOn.DefaultSetting = @"";
colvarModifiedOn.ForeignKeyTableName = "";
schema.Columns.Add(colvarModifiedOn);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("APR_VisitaDomiciliaria",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdVisitaDomiciliaria")]
[Bindable(true)]
public int IdVisitaDomiciliaria
{
get { return GetColumnValue<int>(Columns.IdVisitaDomiciliaria); }
set { SetColumnValue(Columns.IdVisitaDomiciliaria, value); }
}
[XmlAttribute("IdPaciente")]
[Bindable(true)]
public int IdPaciente
{
get { return GetColumnValue<int>(Columns.IdPaciente); }
set { SetColumnValue(Columns.IdPaciente, value); }
}
[XmlAttribute("IdMotivoVisitaDomiciliaria")]
[Bindable(true)]
public int IdMotivoVisitaDomiciliaria
{
get { return GetColumnValue<int>(Columns.IdMotivoVisitaDomiciliaria); }
set { SetColumnValue(Columns.IdMotivoVisitaDomiciliaria, value); }
}
[XmlAttribute("Fecha")]
[Bindable(true)]
public DateTime Fecha
{
get { return GetColumnValue<DateTime>(Columns.Fecha); }
set { SetColumnValue(Columns.Fecha, value); }
}
[XmlAttribute("OtroMotivo")]
[Bindable(true)]
public string OtroMotivo
{
get { return GetColumnValue<string>(Columns.OtroMotivo); }
set { SetColumnValue(Columns.OtroMotivo, value); }
}
[XmlAttribute("Personal")]
[Bindable(true)]
public string Personal
{
get { return GetColumnValue<string>(Columns.Personal); }
set { SetColumnValue(Columns.Personal, value); }
}
[XmlAttribute("Observacion")]
[Bindable(true)]
public string Observacion
{
get { return GetColumnValue<string>(Columns.Observacion); }
set { SetColumnValue(Columns.Observacion, value); }
}
[XmlAttribute("CreatedBy")]
[Bindable(true)]
public string CreatedBy
{
get { return GetColumnValue<string>(Columns.CreatedBy); }
set { SetColumnValue(Columns.CreatedBy, value); }
}
[XmlAttribute("CreatedOn")]
[Bindable(true)]
public DateTime? CreatedOn
{
get { return GetColumnValue<DateTime?>(Columns.CreatedOn); }
set { SetColumnValue(Columns.CreatedOn, value); }
}
[XmlAttribute("ModifiedBy")]
[Bindable(true)]
public string ModifiedBy
{
get { return GetColumnValue<string>(Columns.ModifiedBy); }
set { SetColumnValue(Columns.ModifiedBy, value); }
}
[XmlAttribute("ModifiedOn")]
[Bindable(true)]
public DateTime? ModifiedOn
{
get { return GetColumnValue<DateTime?>(Columns.ModifiedOn); }
set { SetColumnValue(Columns.ModifiedOn, value); }
}
#endregion
#region ForeignKey Properties
/// <summary>
/// Returns a AprMotivoVisitaDomiciliarium ActiveRecord object related to this AprVisitaDomiciliarium
///
/// </summary>
public DalSic.AprMotivoVisitaDomiciliarium AprMotivoVisitaDomiciliarium
{
get { return DalSic.AprMotivoVisitaDomiciliarium.FetchByID(this.IdMotivoVisitaDomiciliaria); }
set { SetColumnValue("idMotivoVisitaDomiciliaria", value.IdMotivoVisitaDomiciliaria); }
}
#endregion
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(int varIdPaciente,int varIdMotivoVisitaDomiciliaria,DateTime varFecha,string varOtroMotivo,string varPersonal,string varObservacion,string varCreatedBy,DateTime? varCreatedOn,string varModifiedBy,DateTime? varModifiedOn)
{
AprVisitaDomiciliarium item = new AprVisitaDomiciliarium();
item.IdPaciente = varIdPaciente;
item.IdMotivoVisitaDomiciliaria = varIdMotivoVisitaDomiciliaria;
item.Fecha = varFecha;
item.OtroMotivo = varOtroMotivo;
item.Personal = varPersonal;
item.Observacion = varObservacion;
item.CreatedBy = varCreatedBy;
item.CreatedOn = varCreatedOn;
item.ModifiedBy = varModifiedBy;
item.ModifiedOn = varModifiedOn;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdVisitaDomiciliaria,int varIdPaciente,int varIdMotivoVisitaDomiciliaria,DateTime varFecha,string varOtroMotivo,string varPersonal,string varObservacion,string varCreatedBy,DateTime? varCreatedOn,string varModifiedBy,DateTime? varModifiedOn)
{
AprVisitaDomiciliarium item = new AprVisitaDomiciliarium();
item.IdVisitaDomiciliaria = varIdVisitaDomiciliaria;
item.IdPaciente = varIdPaciente;
item.IdMotivoVisitaDomiciliaria = varIdMotivoVisitaDomiciliaria;
item.Fecha = varFecha;
item.OtroMotivo = varOtroMotivo;
item.Personal = varPersonal;
item.Observacion = varObservacion;
item.CreatedBy = varCreatedBy;
item.CreatedOn = varCreatedOn;
item.ModifiedBy = varModifiedBy;
item.ModifiedOn = varModifiedOn;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdVisitaDomiciliariaColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn IdPacienteColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn IdMotivoVisitaDomiciliariaColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn FechaColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn OtroMotivoColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn PersonalColumn
{
get { return Schema.Columns[5]; }
}
public static TableSchema.TableColumn ObservacionColumn
{
get { return Schema.Columns[6]; }
}
public static TableSchema.TableColumn CreatedByColumn
{
get { return Schema.Columns[7]; }
}
public static TableSchema.TableColumn CreatedOnColumn
{
get { return Schema.Columns[8]; }
}
public static TableSchema.TableColumn ModifiedByColumn
{
get { return Schema.Columns[9]; }
}
public static TableSchema.TableColumn ModifiedOnColumn
{
get { return Schema.Columns[10]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdVisitaDomiciliaria = @"idVisitaDomiciliaria";
public static string IdPaciente = @"idPaciente";
public static string IdMotivoVisitaDomiciliaria = @"idMotivoVisitaDomiciliaria";
public static string Fecha = @"Fecha";
public static string OtroMotivo = @"OtroMotivo";
public static string Personal = @"Personal";
public static string Observacion = @"Observacion";
public static string CreatedBy = @"CreatedBy";
public static string CreatedOn = @"CreatedOn";
public static string ModifiedBy = @"ModifiedBy";
public static string ModifiedOn = @"ModifiedOn";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
//---------------------------------------------------------------------
// <copyright file="EntityParameter.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
namespace System.Data.EntityClient
{
using System.Data;
using System.Data.Common;
using System.Data.Common.CommandTrees;
using System.Data.Common.Internal;
using System.Data.Metadata.Edm;
using System.Diagnostics;
/// <summary>
/// Class representing a parameter used in EntityCommand
/// </summary>
public sealed partial class EntityParameter : DbParameter, IDbDataParameter
{
private string _parameterName;
private DbType? _dbType;
private EdmType _edmType;
private byte? _precision;
private byte? _scale;
private bool _isDirty;
/// <summary>
/// Constructs the EntityParameter object
/// </summary>
public EntityParameter()
{
}
/// <summary>
/// Constructs the EntityParameter object with the given parameter name and the type of the parameter
/// </summary>
/// <param name="parameterName">The name of the parameter</param>
/// <param name="dbType">The type of the parameter</param>
public EntityParameter(string parameterName, DbType dbType)
{
SetParameterNameWithValidation(parameterName, "parameterName");
this.DbType = dbType;
}
/// <summary>
/// Constructs the EntityParameter object with the given parameter name, the type of the parameter, and the size of the
/// parameter
/// </summary>
/// <param name="parameterName">The name of the parameter</param>
/// <param name="dbType">The type of the parameter</param>
/// <param name="size">The size of the parameter</param>
public EntityParameter(string parameterName, DbType dbType, int size)
{
SetParameterNameWithValidation(parameterName, "parameterName");
this.DbType = dbType;
this.Size = size;
}
/// <summary>
/// Constructs the EntityParameter object with the given parameter name, the type of the parameter, the size of the
/// parameter, and the name of the source column
/// </summary>
/// <param name="parameterName">The name of the parameter</param>
/// <param name="dbType">The type of the parameter</param>
/// <param name="size">The size of the parameter</param>
/// <param name="sourceColumn">The name of the source column mapped to the data set, used for loading the parameter value</param>
public EntityParameter(string parameterName, DbType dbType, int size, string sourceColumn)
{
SetParameterNameWithValidation(parameterName, "parameterName");
this.DbType = dbType;
this.Size = size;
this.SourceColumn = sourceColumn;
}
/// <summary>
/// Constructs the EntityParameter object with the given parameter name, the type of the parameter, the size of the
/// parameter, and the name of the source column
/// </summary>
/// <param name="parameterName">The name of the parameter</param>
/// <param name="dbType">The type of the parameter</param>
/// <param name="size">The size of the parameter</param>
/// <param name="direction">The direction of the parameter, whether it's input/output/both/return value</param>
/// <param name="isNullable">If the parameter is nullable</param>
/// <param name="precision">The floating point precision of the parameter, valid only if the parameter type is a floating point type</param>
/// <param name="scale">The scale of the parameter, valid only if the parameter type is a floating point type</param>
/// <param name="sourceColumn">The name of the source column mapped to the data set, used for loading the parameter value</param>
/// <param name="sourceVersion">The data row version to use when loading the parameter value</param>
/// <param name="value">The value of the parameter</param>
public EntityParameter(string parameterName,
DbType dbType,
int size,
ParameterDirection direction,
bool isNullable,
byte precision,
byte scale,
string sourceColumn,
DataRowVersion sourceVersion,
object value)
{
SetParameterNameWithValidation(parameterName, "parameterName");
this.DbType = dbType;
this.Size = size;
this.Direction = direction;
this.IsNullable = isNullable;
this.Precision = precision;
this.Scale = scale;
this.SourceColumn = sourceColumn;
this.SourceVersion = sourceVersion;
this.Value = value;
}
/// <summary>
/// The name of the parameter
/// </summary>
public override string ParameterName
{
get
{
return this._parameterName ?? "";
}
set
{
SetParameterNameWithValidation(value, "value");
}
}
/// <summary>
/// Helper method to validate the parameter name; Ideally we'd only call this once, but
/// we have to put an argumentName on the Argument exception, and the property setter would
/// need "value" which confuses folks when they call the constructor that takes the value
/// of the parameter. c'est la vie.
/// </summary>
/// <param name="parameterName"></param>
/// <param name="argumentName"></param>
private void SetParameterNameWithValidation(string parameterName, string argumentName)
{
if (!string.IsNullOrEmpty(parameterName) && !DbCommandTree.IsValidParameterName(parameterName))
{
throw EntityUtil.Argument(System.Data.Entity.Strings.EntityClient_InvalidParameterName(parameterName), argumentName);
}
PropertyChanging();
this._parameterName = parameterName;
}
/// <summary>
/// The type of the parameter, EdmType may also be set, and may provide more detailed information.
/// </summary>
public override DbType DbType
{
get
{
// if the user has not set the dbType but has set the dbType, use the edmType to try to deduce a dbType
if (!this._dbType.HasValue)
{
if (this._edmType != null)
{
return GetDbTypeFromEdm(_edmType);
}
// If the user has set neither the DbType nor the EdmType,
// then we attempt to deduce it from the value, but we won't set it in the
// member field as that's used to keep track of what the user set explicitly
else
{
// If we can't deduce the type because there are no values, we still have to return something, just assume it's string type
if (_value == null)
return DbType.String;
try
{
return TypeHelpers.ConvertClrTypeToDbType(_value.GetType());
}
catch (ArgumentException e)
{
throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.EntityClient_CannotDeduceDbType, e);
}
}
}
return (DbType)this._dbType;
}
set
{
PropertyChanging();
this._dbType = value;
}
}
/// <summary>
/// The type of the parameter, expressed as an EdmType.
/// May be null (which is what it will be if unset). This means
/// that the DbType contains all the type information.
/// Non-null values must not contradict DbType (only restate or specialize).
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Edm")]
public EdmType EdmType
{
get
{
return this._edmType;
}
set
{
if (value != null && !Helper.IsScalarType(value))
{
throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.EntityClient_EntityParameterEdmTypeNotScalar(value.FullName));
}
PropertyChanging();
this._edmType = value;
}
}
/// <summary>
/// The precision of the parameter if the parameter is a floating point type
/// </summary>
public new byte Precision
{
get
{
byte result = this._precision.HasValue ? this._precision.Value : (byte)0;
return result;
}
set
{
PropertyChanging();
this._precision = value;
}
}
/// <summary>
/// The scale of the parameter if the parameter is a floating point type
/// </summary>
public new byte Scale
{
get
{
byte result = this._scale.HasValue ? this._scale.Value : (byte)0;
return result;
}
set
{
PropertyChanging();
this._scale = value;
}
}
/// <summary>
/// The value of the parameter
/// </summary>
public override object Value
{
get
{
return this._value;
}
set
{
// If the user hasn't set the DbType, then we have to figure out if the DbType will change as a result
// of the change in the value. What we want to achieve is that changes to the value will not cause
// it to be dirty, but changes to the value that causes the apparent DbType to change, then should be
// dirty.
if (!this._dbType.HasValue && this._edmType == null)
{
// If the value is null, then we assume it's string type
DbType oldDbType = DbType.String;
if (_value != null)
{
oldDbType = TypeHelpers.ConvertClrTypeToDbType(_value.GetType());
}
// If the value is null, then we assume it's string type
DbType newDbType = DbType.String;
if (value != null)
{
newDbType = TypeHelpers.ConvertClrTypeToDbType(value.GetType());
}
if (oldDbType != newDbType)
{
PropertyChanging();
}
}
this._value = value;
}
}
/// <summary>
/// Gets whether this collection has been changes since the last reset
/// </summary>
internal bool IsDirty
{
get
{
return _isDirty;
}
}
/// <summary>
/// Indicates whether the DbType property has been set by the user;
/// </summary>
internal bool IsDbTypeSpecified
{
get
{
return this._dbType.HasValue;
}
}
/// <summary>
/// Indicates whether the Direction property has been set by the user;
/// </summary>
internal bool IsDirectionSpecified
{
get
{
return this._direction != 0;
}
}
/// <summary>
/// Indicates whether the IsNullable property has been set by the user;
/// </summary>
internal bool IsIsNullableSpecified
{
get
{
return this._isNullable.HasValue;
}
}
/// <summary>
/// Indicates whether the Precision property has been set by the user;
/// </summary>
internal bool IsPrecisionSpecified
{
get
{
return this._precision.HasValue;
}
}
/// <summary>
/// Indicates whether the Scale property has been set by the user;
/// </summary>
internal bool IsScaleSpecified
{
get
{
return this._scale.HasValue;
}
}
/// <summary>
/// Indicates whether the Size property has been set by the user;
/// </summary>
internal bool IsSizeSpecified
{
get
{
return this._size.HasValue;
}
}
/// <summary>
/// Resets the DbType property to its original settings
/// </summary>
public override void ResetDbType()
{
if (_dbType != null || _edmType != null)
{
PropertyChanging();
}
_edmType = null;
_dbType = null;
}
/// <summary>
/// Clones this parameter object
/// </summary>
/// <returns>The new cloned object</returns>
internal EntityParameter Clone()
{
return new EntityParameter(this);
}
/// <summary>
/// Clones this parameter object
/// </summary>
/// <returns>The new cloned object</returns>
private void CloneHelper(EntityParameter destination)
{
CloneHelperCore(destination);
destination._parameterName = _parameterName;
destination._dbType = _dbType;
destination._edmType = _edmType;
destination._precision = _precision;
destination._scale = _scale;
}
/// <summary>
/// Marks that this parameter has been changed
/// </summary>
private void PropertyChanging()
{
_isDirty = true;
}
/// <summary>
/// Determines the size of the given object
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
private int ValueSize(object value)
{
return ValueSizeCore(value);
}
/// <summary>
/// Get the type usage for this parameter in model terms.
/// </summary>
/// <returns>The type usage for this parameter</returns>
//NOTE: Because GetTypeUsage throws CommandValidationExceptions, it should only be called from EntityCommand during command execution
internal TypeUsage GetTypeUsage()
{
TypeUsage typeUsage;
if (!this.IsTypeConsistent)
{
throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.EntityClient_EntityParameterInconsistentEdmType(
_edmType.FullName, _parameterName));
}
if (this._edmType != null)
{
typeUsage = TypeUsage.Create(this._edmType);
}
else if (!DbTypeMap.TryGetModelTypeUsage(this.DbType, out typeUsage))
{
// Spatial types have only DbType 'Object', and cannot be represented in the static type map.
PrimitiveType primitiveParameterType;
if (this.DbType == DbType.Object &&
this.Value != null &&
ClrProviderManifest.Instance.TryGetPrimitiveType(this.Value.GetType(), out primitiveParameterType) &&
Helper.IsSpatialType(primitiveParameterType))
{
typeUsage = EdmProviderManifest.Instance.GetCanonicalModelTypeUsage(primitiveParameterType.PrimitiveTypeKind);
}
else
{
throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.EntityClient_UnsupportedDbType(this.DbType.ToString(), ParameterName));
}
}
Debug.Assert(typeUsage != null, "DbType.TryGetModelTypeUsage returned true for null TypeUsage?");
return typeUsage;
}
/// <summary>
/// Reset the dirty flag on the collection
/// </summary>
internal void ResetIsDirty()
{
_isDirty = false;
}
private bool IsTypeConsistent
{
get
{
if (this._edmType != null && this._dbType.HasValue)
{
DbType dbType = GetDbTypeFromEdm(_edmType);
if (dbType == DbType.String)
{
// would need facets to distinguish the various sorts of string,
// a generic string EdmType is consistent with any string DbType.
return _dbType == DbType.String || _dbType == DbType.AnsiString
|| dbType == DbType.AnsiStringFixedLength || dbType == DbType.StringFixedLength;
}
else
{
return _dbType == dbType;
}
}
return true;
}
}
private static DbType GetDbTypeFromEdm(EdmType edmType)
{
PrimitiveType primitiveType = Helper.AsPrimitive(edmType);
DbType dbType;
if (Helper.IsSpatialType(primitiveType))
{
return DbType.Object;
}
else if (DbCommandDefinition.TryGetDbTypeFromPrimitiveType(primitiveType, out dbType))
{
return dbType;
}
// we shouldn't ever get here. Assert in a debug build, and pick a type.
Debug.Assert(false, "The provided edmType is of an unknown primitive type.");
return default(DbType);
}
}
}
| |
namespace Fonet.Render.Pdf.Fonts {
internal class CourierBold : Base14Font {
private static readonly int[] DefaultWidths;
private static readonly CodePointMapping mapping
= CodePointMapping.GetMapping("WinAnsiEncoding");
public CourierBold()
: base("Courier-Bold", "WinAnsiEncoding", 562, 626, -142, 32, 255, DefaultWidths, mapping) {}
static CourierBold() {
DefaultWidths = new int[256];
DefaultWidths[0x0041] = 600;
DefaultWidths[0x00C6] = 600;
DefaultWidths[0x00C1] = 600;
DefaultWidths[0x00C2] = 600;
DefaultWidths[0x00C4] = 600;
DefaultWidths[0x00C0] = 600;
DefaultWidths[0x00C5] = 600;
DefaultWidths[0x00C3] = 600;
DefaultWidths[0x0042] = 600;
DefaultWidths[0x0043] = 600;
DefaultWidths[0x00C7] = 600;
DefaultWidths[0x0044] = 600;
DefaultWidths[0x0045] = 600;
DefaultWidths[0x00C9] = 600;
DefaultWidths[0x00CA] = 600;
DefaultWidths[0x00CB] = 600;
DefaultWidths[0x00C8] = 600;
DefaultWidths[0x00D0] = 600;
DefaultWidths[0x0080] = 600;
DefaultWidths[0x0046] = 600;
DefaultWidths[0x0047] = 600;
DefaultWidths[0x0048] = 600;
DefaultWidths[0x0049] = 600;
DefaultWidths[0x00CD] = 600;
DefaultWidths[0x00CE] = 600;
DefaultWidths[0x00CF] = 600;
DefaultWidths[0x00CC] = 600;
DefaultWidths[0x004A] = 600;
DefaultWidths[0x004B] = 600;
DefaultWidths[0x004C] = 600;
DefaultWidths[0x004D] = 600;
DefaultWidths[0x004E] = 600;
DefaultWidths[0x00D1] = 600;
DefaultWidths[0x004F] = 600;
DefaultWidths[0x008C] = 600;
DefaultWidths[0x00D3] = 600;
DefaultWidths[0x00D4] = 600;
DefaultWidths[0x00D6] = 600;
DefaultWidths[0x00D2] = 600;
DefaultWidths[0x00D8] = 600;
DefaultWidths[0x00D5] = 600;
DefaultWidths[0x0050] = 600;
DefaultWidths[0x0051] = 600;
DefaultWidths[0x0052] = 600;
DefaultWidths[0x0053] = 600;
DefaultWidths[0x008A] = 600;
DefaultWidths[0x0054] = 600;
DefaultWidths[0x00DE] = 600;
DefaultWidths[0x0055] = 600;
DefaultWidths[0x00DA] = 600;
DefaultWidths[0x00DB] = 600;
DefaultWidths[0x00DC] = 600;
DefaultWidths[0x00D9] = 600;
DefaultWidths[0x0056] = 600;
DefaultWidths[0x0057] = 600;
DefaultWidths[0x0058] = 600;
DefaultWidths[0x0059] = 600;
DefaultWidths[0x00DD] = 600;
DefaultWidths[0x009F] = 600;
DefaultWidths[0x005A] = 600;
DefaultWidths[0x0061] = 600;
DefaultWidths[0x00E1] = 600;
DefaultWidths[0x00E2] = 600;
DefaultWidths[0x00B4] = 600;
DefaultWidths[0x00E4] = 600;
DefaultWidths[0x00E6] = 600;
DefaultWidths[0x00E0] = 600;
DefaultWidths[0x0026] = 600;
DefaultWidths[0x00E5] = 600;
DefaultWidths[0xAB] = 600;
DefaultWidths[0xAF] = 600;
DefaultWidths[0xAC] = 600;
DefaultWidths[0xAE] = 600;
DefaultWidths[0xAD] = 600;
DefaultWidths[0x005E] = 600;
DefaultWidths[0x007E] = 600;
DefaultWidths[0x002A] = 600;
DefaultWidths[0x0040] = 600;
DefaultWidths[0x00E3] = 600;
DefaultWidths[0x0062] = 600;
DefaultWidths[0x005C] = 600;
DefaultWidths[0x007C] = 600;
DefaultWidths[0x007B] = 600;
DefaultWidths[0x007D] = 600;
DefaultWidths[0x005B] = 600;
DefaultWidths[0x005D] = 600;
DefaultWidths[0x00A6] = 600;
DefaultWidths[0x0095] = 600;
DefaultWidths[0x0063] = 600;
DefaultWidths[0x00E7] = 600;
DefaultWidths[0x00B8] = 600;
DefaultWidths[0x00A2] = 600;
DefaultWidths[0x0088] = 600;
DefaultWidths[0x003A] = 600;
DefaultWidths[0x002C] = 600;
DefaultWidths[0x00A9] = 600;
DefaultWidths[0x00A4] = 600;
DefaultWidths[0x0064] = 600;
DefaultWidths[0x0086] = 600;
DefaultWidths[0x0087] = 600;
DefaultWidths[0x00B0] = 600;
DefaultWidths[0x00A8] = 600;
DefaultWidths[0x00F7] = 600;
DefaultWidths[0x0024] = 600;
DefaultWidths[0x0065] = 600;
DefaultWidths[0x00E9] = 600;
DefaultWidths[0x00EA] = 600;
DefaultWidths[0x00EB] = 600;
DefaultWidths[0x00E8] = 600;
DefaultWidths[0x0038] = 600;
DefaultWidths[0x0085] = 600;
DefaultWidths[0x0097] = 600;
DefaultWidths[0x0096] = 600;
DefaultWidths[0x003D] = 600;
DefaultWidths[0x00F0] = 600;
DefaultWidths[0x0021] = 600;
DefaultWidths[0x00A1] = 600;
DefaultWidths[0x0066] = 600;
DefaultWidths[0x0035] = 600;
DefaultWidths[0x0083] = 600;
DefaultWidths[0x0034] = 600;
DefaultWidths[0xA4] = 600;
DefaultWidths[0x0067] = 600;
DefaultWidths[0x00DF] = 600;
DefaultWidths[0x0060] = 600;
DefaultWidths[0x003E] = 600;
DefaultWidths[0x00AB] = 600;
DefaultWidths[0x00BB] = 600;
DefaultWidths[0x008B] = 600;
DefaultWidths[0x009B] = 600;
DefaultWidths[0x0068] = 600;
DefaultWidths[0x002D] = 600;
DefaultWidths[0x0069] = 600;
DefaultWidths[0x00ED] = 600;
DefaultWidths[0x00EE] = 600;
DefaultWidths[0x00EF] = 600;
DefaultWidths[0x00EC] = 600;
DefaultWidths[0x006A] = 600;
DefaultWidths[0x006B] = 600;
DefaultWidths[0x006C] = 600;
DefaultWidths[0x003C] = 600;
DefaultWidths[0x00AC] = 600;
DefaultWidths[0x006D] = 600;
DefaultWidths[0x00AF] = 600;
DefaultWidths[0x2D] = 600;
DefaultWidths[0x00B5] = 600;
DefaultWidths[0x00D7] = 600;
DefaultWidths[0x006E] = 600;
DefaultWidths[0x0039] = 600;
DefaultWidths[0x00F1] = 600;
DefaultWidths[0x0023] = 600;
DefaultWidths[0x006F] = 600;
DefaultWidths[0x00F3] = 600;
DefaultWidths[0x00F4] = 600;
DefaultWidths[0x00F6] = 600;
DefaultWidths[0x009C] = 600;
DefaultWidths[0x00F2] = 600;
DefaultWidths[0x0031] = 600;
DefaultWidths[0x00BD] = 600;
DefaultWidths[0x00BC] = 600;
DefaultWidths[0x00B9] = 600;
DefaultWidths[0x00AA] = 600;
DefaultWidths[0x00BA] = 600;
DefaultWidths[0x00F8] = 600;
DefaultWidths[0x00F5] = 600;
DefaultWidths[0x0070] = 600;
DefaultWidths[0x00B6] = 600;
DefaultWidths[0x0028] = 600;
DefaultWidths[0x0029] = 600;
DefaultWidths[0x0025] = 600;
DefaultWidths[0x002E] = 600;
DefaultWidths[0x00B7] = 600;
DefaultWidths[0x0089] = 600;
DefaultWidths[0x002B] = 600;
DefaultWidths[0x00B1] = 600;
DefaultWidths[0x0071] = 600;
DefaultWidths[0x003F] = 600;
DefaultWidths[0x00BF] = 600;
DefaultWidths[0x0022] = 600;
DefaultWidths[0x0084] = 600;
DefaultWidths[0x0093] = 600;
DefaultWidths[0x0094] = 600;
DefaultWidths[0x0091] = 600;
DefaultWidths[0x0092] = 600;
DefaultWidths[0x0082] = 600;
DefaultWidths[0x0027] = 600;
DefaultWidths[0x0072] = 600;
DefaultWidths[0x00AE] = 600;
DefaultWidths[0x0073] = 600;
DefaultWidths[0x009A] = 600;
DefaultWidths[0x00A7] = 600;
DefaultWidths[0x003B] = 600;
DefaultWidths[0x0037] = 600;
DefaultWidths[0x0036] = 600;
DefaultWidths[0x002F] = 600;
DefaultWidths[0x0020] = 600;
DefaultWidths[0x00A0] = 600;
DefaultWidths[0x00A3] = 600;
DefaultWidths[0x0074] = 600;
DefaultWidths[0x00FE] = 600;
DefaultWidths[0x0033] = 600;
DefaultWidths[0x00BE] = 600;
DefaultWidths[0x00B3] = 600;
DefaultWidths[0x0098] = 600;
DefaultWidths[0x0099] = 600;
DefaultWidths[0x0032] = 600;
DefaultWidths[0x00B2] = 600;
DefaultWidths[0x0075] = 600;
DefaultWidths[0x00FA] = 600;
DefaultWidths[0x00FB] = 600;
DefaultWidths[0x00FC] = 600;
DefaultWidths[0x00F9] = 600;
DefaultWidths[0x005F] = 600;
DefaultWidths[0x0076] = 600;
DefaultWidths[0x0077] = 600;
DefaultWidths[0x0078] = 600;
DefaultWidths[0x0079] = 600;
DefaultWidths[0x00FD] = 600;
DefaultWidths[0x00FF] = 600;
DefaultWidths[0x00A5] = 600;
DefaultWidths[0x007A] = 600;
DefaultWidths[0x0030] = 600;
}
}
}
| |
// 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.Collections.Generic;
using System.Reflection.Runtime.TypeInfos;
namespace System.Reflection.Runtime.BindingFlagSupport
{
//=================================================================================================================
// This class encapsulates the minimum set of arcane desktop CLR policies needed to implement the Get*(BindingFlags) apis.
//
// In particular, it encapsulates behaviors such as what exactly determines the "visibility" of a property and event, and
// what determines whether and how they are overridden.
//=================================================================================================================
internal abstract class MemberPolicies<M> where M : MemberInfo
{
//=================================================================================================================
// Subclasses for specific MemberInfo types must override these:
//=================================================================================================================
//
// Returns all of the directly declared members on the given TypeInfo.
//
public abstract IEnumerable<M> GetDeclaredMembers(TypeInfo typeInfo);
//
// Returns all of the directly declared members on the given TypeInfo whose name matches optionalNameFilter. If optionalNameFilter is null,
// returns all directly declared members.
//
public abstract IEnumerable<M> CoreGetDeclaredMembers(RuntimeTypeInfo type, NameFilter optionalNameFilter, RuntimeTypeInfo reflectedType);
//
// Policy to decide whether a member is considered "virtual", "virtual new" and what its member visibility is.
// (For "visibility", we reuse the MethodAttributes enum since Reflection lacks an element-agnostic enum for this.
// Only the MemberAccessMask bits are set.)
//
public abstract void GetMemberAttributes(M member, out MethodAttributes visibility, out bool isStatic, out bool isVirtual, out bool isNewSlot);
//
// Policy to decide whether "derivedMember" is a virtual override of "baseMember." Used to implement MethodInfo.GetBaseDefinition(),
// parent chain traversal for discovering inherited custom attributes, and suppressing lookup results in the Type.Get*() api family.
//
// Does not consider explicit overrides (methodimpls.) Does not consider "overrides" of interface methods.
//
public abstract bool ImplicitlyOverrides(M baseMember, M derivedMember);
//
// Policy to decide how BindingFlags should be reinterpreted for a given member type.
// This is overridden for nested types which all match on any combination Instance | Static and are never inherited.
// It is also overridden for constructors which are never inherited.
//
public virtual BindingFlags ModifyBindingFlags(BindingFlags bindingFlags)
{
return bindingFlags;
}
//
// Policy to decide if BindingFlags is always interpreted as having set DeclaredOnly.
//
public abstract bool AlwaysTreatAsDeclaredOnly { get; }
//
// Policy to decide how or if members in more derived types hide same-named members in base types.
// Due to desktop compat concerns, the definitions are a bit more arbitrary than we'd like.
//
public abstract bool IsSuppressedByMoreDerivedMember(M member, M[] priorMembers, int startIndex, int endIndex);
//
// Policy to decide whether to throw an AmbiguousMatchException on an ambiguous Type.Get*() call.
// Does not apply to GetConstructor/GetMethod/GetProperty calls that have a non-null Type[] array passed to it.
//
// If method returns true, the Get() api will pick the member that's in the most derived type.
// If method returns false, the Get() api throws AmbiguousMatchException.
//
public abstract bool OkToIgnoreAmbiguity(M m1, M m2);
//
// Helper method for determining whether two methods are signature-compatible.
//
protected static bool AreNamesAndSignaturesEqual(MethodInfo method1, MethodInfo method2)
{
if (method1.Name != method2.Name)
return false;
ParameterInfo[] p1 = method1.GetParametersNoCopy();
ParameterInfo[] p2 = method2.GetParametersNoCopy();
if (p1.Length != p2.Length)
return false;
bool isGenericMethod1 = method1.IsGenericMethodDefinition;
bool isGenericMethod2 = method2.IsGenericMethodDefinition;
if (isGenericMethod1 != isGenericMethod2)
return false;
if (!isGenericMethod1)
{
for (int i = 0; i < p1.Length; i++)
{
Type parameterType1 = p1[i].ParameterType;
Type parameterType2 = p2[i].ParameterType;
if (!(parameterType1.Equals(parameterType2)))
{
return false;
}
}
}
else
{
if (method1.GetGenericArguments().Length != method2.GetGenericArguments().Length)
return false;
for (int i = 0; i < p1.Length; i++)
{
Type parameterType1 = p1[i].ParameterType;
Type parameterType2 = p2[i].ParameterType;
if (!GenericMethodAwareAreParameterTypesEqual(parameterType1, parameterType2))
{
return false;
}
}
}
return true;
}
//
// This helper compares the types of the corresponding parameters of two methods to see if one method is signature equivalent to the other.
// This is needed when comparing the signatures of two generic methods as Type.Equals() is not up to that job.
//
private static bool GenericMethodAwareAreParameterTypesEqual(Type t1, Type t2)
{
// Fast-path - if Reflection has already deemed them equivalent, we can trust its result.
if (t1.Equals(t2))
return true;
// If we got here, Reflection determined the types not equivalent. Most of the time, that's the result we want.
// There is however, one wrinkle. If the type is or embeds a generic method parameter type, Reflection will always report them
// non-equivalent, since generic parameter type comparison always compares both the position and the declaring method. For our purposes, though,
// we only want to consider the position.
// Fast-path: if the types don't embed any generic parameters, we can go ahead and use Reflection's result.
if (!(t1.ContainsGenericParameters && t2.ContainsGenericParameters))
return false;
if ((t1.IsArray && t2.IsArray) || (t1.IsByRef && t2.IsByRef) || (t1.IsPointer && t2.IsPointer))
{
if (t1.IsSzArray != t2.IsSzArray)
return false;
if (t1.IsArray && (t1.GetArrayRank() != t2.GetArrayRank()))
return false;
return GenericMethodAwareAreParameterTypesEqual(t1.GetElementType(), t2.GetElementType());
}
if (t1.IsConstructedGenericType)
{
// We can use regular old Equals() rather than recursing into GenericMethodAwareAreParameterTypesEqual() since the
// generic type definition will always be a plain old named type and won't embed any generic method parameters.
if (!(t1.GetGenericTypeDefinition().Equals(t2.GetGenericTypeDefinition())))
return false;
Type[] ga1 = t1.GenericTypeArguments;
Type[] ga2 = t2.GenericTypeArguments;
if (ga1.Length != ga2.Length)
return false;
for (int i = 0; i < ga1.Length; i++)
{
if (!GenericMethodAwareAreParameterTypesEqual(ga1[i], ga2[i]))
return false;
}
return true;
}
if (t1.IsGenericParameter && t2.IsGenericParameter)
{
if (t1.DeclaringMethod != null && t2.DeclaringMethod != null)
{
// A generic method parameter. The DeclaringMethods will be different but we don't care about that - we can assume that
// the declaring method will be the method that declared the parameter's whose type we're testing. We only need to
// compare the positions.
return t1.GenericParameterPosition == t2.GenericParameterPosition;
}
return false;
}
// If we got here, either t1 and t2 are different flavors of types or they are both simple named types.
// Either way, we can trust Reflection's result here.
return false;
}
static MemberPolicies()
{
Type t = typeof(M);
if (t.Equals(typeof(FieldInfo)))
{
MemberTypeIndex = BindingFlagSupport.MemberTypeIndex.Field;
Default = (MemberPolicies<M>)(Object)(new FieldPolicies());
}
else if (t.Equals(typeof(MethodInfo)))
{
MemberTypeIndex = BindingFlagSupport.MemberTypeIndex.Method;
Default = (MemberPolicies<M>)(Object)(new MethodPolicies());
}
else if (t.Equals(typeof(ConstructorInfo)))
{
MemberTypeIndex = BindingFlagSupport.MemberTypeIndex.Constructor;
Default = (MemberPolicies<M>)(Object)(new ConstructorPolicies());
}
else if (t.Equals(typeof(PropertyInfo)))
{
MemberTypeIndex = BindingFlagSupport.MemberTypeIndex.Property; ;
Default = (MemberPolicies<M>)(Object)(new PropertyPolicies());
}
else if (t.Equals(typeof(EventInfo)))
{
MemberTypeIndex = BindingFlagSupport.MemberTypeIndex.Event;
Default = (MemberPolicies<M>)(Object)(new EventPolicies());
}
else if (t.Equals(typeof(Type)))
{
MemberTypeIndex = BindingFlagSupport.MemberTypeIndex.NestedType;
Default = (MemberPolicies<M>)(Object)(new NestedTypePolicies());
}
else
{
Debug.Assert(false, "Unknown MemberInfo type.");
}
}
//
// This is a singleton class one for each MemberInfo category: Return the appropriate one.
//
public static readonly MemberPolicies<M> Default;
//
// This returns a fixed value from 0 to MemberIndex.Count-1 with each possible type of M
// being assigned a unique index (see the MemberTypeIndex for possible values). This is useful
// for converting a type reference to M to an array index or switch case label.
//
public static readonly int MemberTypeIndex;
}
}
| |
// 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 gax = Google.Api.Gax;
using gcav = Google.Cloud.AIPlatform.V1;
using sys = System;
namespace Google.Cloud.AIPlatform.V1
{
/// <summary>Resource name for the <c>PipelineJob</c> resource.</summary>
public sealed partial class PipelineJobName : gax::IResourceName, sys::IEquatable<PipelineJobName>
{
/// <summary>The possible contents of <see cref="PipelineJobName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}</c>.
/// </summary>
ProjectLocationPipelineJob = 1,
}
private static gax::PathTemplate s_projectLocationPipelineJob = new gax::PathTemplate("projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}");
/// <summary>Creates a <see cref="PipelineJobName"/> 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="PipelineJobName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static PipelineJobName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new PipelineJobName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="PipelineJobName"/> with the pattern
/// <c>projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="pipelineJobId">The <c>PipelineJob</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="PipelineJobName"/> constructed from the provided ids.</returns>
public static PipelineJobName FromProjectLocationPipelineJob(string projectId, string locationId, string pipelineJobId) =>
new PipelineJobName(ResourceNameType.ProjectLocationPipelineJob, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), pipelineJobId: gax::GaxPreconditions.CheckNotNullOrEmpty(pipelineJobId, nameof(pipelineJobId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="PipelineJobName"/> with pattern
/// <c>projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="pipelineJobId">The <c>PipelineJob</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="PipelineJobName"/> with pattern
/// <c>projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string pipelineJobId) =>
FormatProjectLocationPipelineJob(projectId, locationId, pipelineJobId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="PipelineJobName"/> with pattern
/// <c>projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="pipelineJobId">The <c>PipelineJob</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="PipelineJobName"/> with pattern
/// <c>projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}</c>.
/// </returns>
public static string FormatProjectLocationPipelineJob(string projectId, string locationId, string pipelineJobId) =>
s_projectLocationPipelineJob.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(pipelineJobId, nameof(pipelineJobId)));
/// <summary>Parses the given resource name string into a new <see cref="PipelineJobName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="pipelineJobName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="PipelineJobName"/> if successful.</returns>
public static PipelineJobName Parse(string pipelineJobName) => Parse(pipelineJobName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="PipelineJobName"/> instance; optionally allowing
/// an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="pipelineJobName">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="PipelineJobName"/> if successful.</returns>
public static PipelineJobName Parse(string pipelineJobName, bool allowUnparsed) =>
TryParse(pipelineJobName, allowUnparsed, out PipelineJobName 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="PipelineJobName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="pipelineJobName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="PipelineJobName"/>, 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 pipelineJobName, out PipelineJobName result) =>
TryParse(pipelineJobName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="PipelineJobName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="pipelineJobName">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="PipelineJobName"/>, 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 pipelineJobName, bool allowUnparsed, out PipelineJobName result)
{
gax::GaxPreconditions.CheckNotNull(pipelineJobName, nameof(pipelineJobName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationPipelineJob.TryParseName(pipelineJobName, out resourceName))
{
result = FromProjectLocationPipelineJob(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(pipelineJobName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private PipelineJobName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string pipelineJobId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
LocationId = locationId;
PipelineJobId = pipelineJobId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="PipelineJobName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="pipelineJobId">The <c>PipelineJob</c> ID. Must not be <c>null</c> or empty.</param>
public PipelineJobName(string projectId, string locationId, string pipelineJobId) : this(ResourceNameType.ProjectLocationPipelineJob, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), pipelineJobId: gax::GaxPreconditions.CheckNotNullOrEmpty(pipelineJobId, nameof(pipelineJobId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>PipelineJob</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string PipelineJobId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>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.ProjectLocationPipelineJob: return s_projectLocationPipelineJob.Expand(ProjectId, LocationId, PipelineJobId);
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 PipelineJobName);
/// <inheritdoc/>
public bool Equals(PipelineJobName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(PipelineJobName a, PipelineJobName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(PipelineJobName a, PipelineJobName b) => !(a == b);
}
/// <summary>Resource name for the <c>Network</c> resource.</summary>
public sealed partial class NetworkName : gax::IResourceName, sys::IEquatable<NetworkName>
{
/// <summary>The possible contents of <see cref="NetworkName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>projects/{project}/global/networks/{network}</c>.</summary>
ProjectNetwork = 1,
}
private static gax::PathTemplate s_projectNetwork = new gax::PathTemplate("projects/{project}/global/networks/{network}");
/// <summary>Creates a <see cref="NetworkName"/> 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="NetworkName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static NetworkName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new NetworkName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="NetworkName"/> with the pattern <c>projects/{project}/global/networks/{network}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="networkId">The <c>Network</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="NetworkName"/> constructed from the provided ids.</returns>
public static NetworkName FromProjectNetwork(string projectId, string networkId) =>
new NetworkName(ResourceNameType.ProjectNetwork, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), networkId: gax::GaxPreconditions.CheckNotNullOrEmpty(networkId, nameof(networkId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="NetworkName"/> with pattern
/// <c>projects/{project}/global/networks/{network}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="networkId">The <c>Network</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="NetworkName"/> with pattern
/// <c>projects/{project}/global/networks/{network}</c>.
/// </returns>
public static string Format(string projectId, string networkId) => FormatProjectNetwork(projectId, networkId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="NetworkName"/> with pattern
/// <c>projects/{project}/global/networks/{network}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="networkId">The <c>Network</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="NetworkName"/> with pattern
/// <c>projects/{project}/global/networks/{network}</c>.
/// </returns>
public static string FormatProjectNetwork(string projectId, string networkId) =>
s_projectNetwork.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(networkId, nameof(networkId)));
/// <summary>Parses the given resource name string into a new <see cref="NetworkName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/global/networks/{network}</c></description></item>
/// </list>
/// </remarks>
/// <param name="networkName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="NetworkName"/> if successful.</returns>
public static NetworkName Parse(string networkName) => Parse(networkName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="NetworkName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/global/networks/{network}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="networkName">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="NetworkName"/> if successful.</returns>
public static NetworkName Parse(string networkName, bool allowUnparsed) =>
TryParse(networkName, allowUnparsed, out NetworkName 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="NetworkName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/global/networks/{network}</c></description></item>
/// </list>
/// </remarks>
/// <param name="networkName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="NetworkName"/>, 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 networkName, out NetworkName result) => TryParse(networkName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="NetworkName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/global/networks/{network}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="networkName">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="NetworkName"/>, 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 networkName, bool allowUnparsed, out NetworkName result)
{
gax::GaxPreconditions.CheckNotNull(networkName, nameof(networkName));
gax::TemplatedResourceName resourceName;
if (s_projectNetwork.TryParseName(networkName, out resourceName))
{
result = FromProjectNetwork(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(networkName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private NetworkName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string networkId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
NetworkId = networkId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="NetworkName"/> class from the component parts of pattern
/// <c>projects/{project}/global/networks/{network}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="networkId">The <c>Network</c> ID. Must not be <c>null</c> or empty.</param>
public NetworkName(string projectId, string networkId) : this(ResourceNameType.ProjectNetwork, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), networkId: gax::GaxPreconditions.CheckNotNullOrEmpty(networkId, nameof(networkId)))
{
}
/// <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>Network</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string NetworkId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>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.ProjectNetwork: return s_projectNetwork.Expand(ProjectId, NetworkId);
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 NetworkName);
/// <inheritdoc/>
public bool Equals(NetworkName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(NetworkName a, NetworkName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(NetworkName a, NetworkName b) => !(a == b);
}
public partial class PipelineJob
{
/// <summary>
/// <see cref="gcav::PipelineJobName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcav::PipelineJobName PipelineJobName
{
get => string.IsNullOrEmpty(Name) ? null : gcav::PipelineJobName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="NetworkName"/>-typed view over the <see cref="Network"/> resource name property.
/// </summary>
public NetworkName NetworkAsNetworkName
{
get => string.IsNullOrEmpty(Network) ? null : NetworkName.Parse(Network, allowUnparsed: true);
set => Network = value?.ToString() ?? "";
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Xml.Serialization;
namespace SIL.Text
{
public class MultiTextBase : INotifyPropertyChanged, IComparable
{
/// <summary>
/// We have this pesky "backreference" solely to enable fast
/// searching in our current version of db4o (5.5), which
/// can find strings fast, but can't be queried for the owner
/// quickly, if there is an intervening collection. Since
/// each string in WeSay is part of a collection of writing
/// system alternatives, that means we can't quickly get
/// an answer, for example, to the question Get all
/// the Entries that contain a senes which matches the gloss "cat".
///
/// Using this field, we can do a query asking for all
/// the LanguageForms matching "cat".
/// This can all be done in a single, fast query.
/// In code, we can then follow the
/// LanguageForm._parent up to the MultiTextBase, then this _parent
/// up to it's owner, etc., on up the hierarchy to get the Entries.
///
/// Subclasses should provide a property which set the proper class.
///
/// 23 Jan 07, note: starting to switch to using these for notifying parent of changes, too.
/// </summary>
/// <summary>
/// For INotifyPropertyChanged
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
private LanguageForm[] _forms;
public MultiTextBase()
{
_forms = new LanguageForm[0];
}
public void Add(Object objectFromSerializer) {}
public static bool IsEmpty(MultiTextBase mt)
{
return mt == null || mt.Empty;
}
public static MultiTextBase Create(Dictionary<string, string> forms)
{
MultiTextBase m = new MultiTextBase();
CopyForms(forms, m);
return m;
}
protected static void CopyForms(Dictionary<string, string> forms, MultiTextBase m)
{
if (forms != null && forms.Keys != null)
{
foreach (string key in forms.Keys)
{
LanguageForm f = m.Find(key);
if (f != null)
{
f.Form = forms[key];
}
else
{
m.SetAlternative(key, forms[key]);
}
}
}
}
public bool GetAnnotationOfAlternativeIsStarred(string id)
{
LanguageForm alt = Find(id);
if (alt == null)
{
return false;
}
return alt.IsStarred;
}
public void SetAnnotationOfAlternativeIsStarred(string id, bool isStarred)
{
LanguageForm alt = Find(id);
if (isStarred)
{
if (alt == null)
{
AddLanguageForm(new LanguageForm(id, String.Empty, this));
alt = Find(id);
Debug.Assert(alt != null);
}
alt.IsStarred = true;
}
else
{
if (alt != null)
{
if (alt.Form == String.Empty) //non-starred and empty? Nuke it.
{
RemoveLanguageForm(alt);
}
else
{
alt.IsStarred = false;
}
}
else
{
//nothing to do. Missing altertive == not starred.
}
}
NotifyPropertyChanged(id);
}
[XmlArrayItem(typeof (LanguageForm), ElementName = "tobedetermined")]
public string this[string writingSystemId]
{
get => GetExactAlternative(writingSystemId);
set => SetAlternative(writingSystemId, value);
}
public LanguageForm Find(string writingSystemId)
{
foreach (LanguageForm f in Forms)
{
if (f.WritingSystemId.ToLowerInvariant() == writingSystemId.ToLowerInvariant())
{
return f;
}
}
return null;
}
/// <summary>
/// Throws exception if alternative does not exist.
/// </summary>
/// <param name="writingSystemId"></param>
/// <returns></returns>
// public string GetExactAlternative(string writingSystemId)
// {
// if (!Contains(writingSystemId))
// {
// throw new ArgumentOutOfRangeException("Use Contains() to first check if the MultiTextBase has a language form for this writing system.");
// }
//
// return GetBestAlternative(writingSystemId, false, null);
// }
public bool ContainsAlternative(string writingSystemId)
{
return (Find(writingSystemId) != null);
}
/// <summary>
/// Get exact alternative or String.Empty
/// </summary>
/// <param name="writingSystemId"></param>
/// <returns></returns>
public string GetExactAlternative(string writingSystemId)
{
return GetAlternative(writingSystemId, false, null);
}
/// <summary>
/// Gets the Spans for the exact alternative or null.
/// </summary>
public List<LanguageForm.FormatSpan> GetExactAlternativeSpans(string writingSystemId)
{
LanguageForm alt = Find(writingSystemId);
if (null == alt)
return null;
else
return alt.Spans;
}
/// <summary>
/// Gives the string of the requested id if it exists, else the 'first'(?) one that does exist, else Empty String
/// </summary>
/// <returns></returns>
public string GetBestAlternative(string writingSystemId)
{
return GetAlternative(writingSystemId, true, string.Empty);
}
public string GetBestAlternative(string writingSystemId, string notFirstChoiceSuffix)
{
return GetAlternative(writingSystemId, true, notFirstChoiceSuffix);
}
/// <summary>
/// Get a string out
/// </summary>
/// <returns>the string of the requested id if it exists,
/// else the 'first'(?) one that does exist + the suffix,
/// else the given suffix </returns>
private string GetAlternative(string writingSystemId, bool doShowSomethingElseIfMissing,
string notFirstChoiceSuffix)
{
LanguageForm alt = Find(writingSystemId);
if (null == alt)
{
if (doShowSomethingElseIfMissing)
{
return GetFirstAlternative() + notFirstChoiceSuffix;
}
else
{
return string.Empty;
}
}
string form = alt.Form;
if (form == null || (form.Trim().Length == 0))
{
if (doShowSomethingElseIfMissing)
{
return GetFirstAlternative() + notFirstChoiceSuffix;
}
else
{
return string.Empty;
}
}
else
{
return form;
}
}
public string GetFirstAlternative()
{
foreach (LanguageForm form in Forms)
{
if (form.Form.Trim().Length > 0)
{
return form.Form;
}
}
return string.Empty;
}
public string GetBestAlternativeString(IEnumerable<string> orderedListOfWritingSystemIds)
{
LanguageForm form = GetBestAlternative(orderedListOfWritingSystemIds);
if (form == null)
return string.Empty;
return form.Form;
}
/// <summary>
/// Try to get an alternative according to the ws's given(e.g. the enabled writing systems for a field)
/// </summary>
/// <param name="orderedListOfWritingSystemIds"></param>
/// <returns>May return null!</returns>
public LanguageForm GetBestAlternative(IEnumerable<string> orderedListOfWritingSystemIds)
{
foreach (string id in orderedListOfWritingSystemIds)
{
LanguageForm alt = Find(id);
if (null != alt)
return alt;
}
// //just send back an empty
// foreach (string id in orderedListOfWritingSystemIds)
// {
// return new LanguageForm(id, string.Empty );
// }
return null;
}
public bool Empty => Count == 0;
public int Count => Forms.Length;
/// <summary>
/// just for deserialization
/// </summary>
[XmlElement(typeof (LanguageForm), ElementName="form")]
public LanguageForm[] Forms
{
get
{
if (_forms == null)
{
throw new ApplicationException("The LanguageForms[] attribute of this entry was null. This is a symptom of a mismatch between a cache and WeSay model. Please delete the cache.");
}
return _forms;
}
set => _forms = value;
}
public void SetAlternative(string writingSystemId, string form)
{
Debug.Assert(!string.IsNullOrEmpty(writingSystemId), "The writing system id was empty.");
Debug.Assert(writingSystemId.Trim() == writingSystemId,
"The writing system id had leading or trailing whitespace");
//enhance: check to see if there has actually been a change
LanguageForm alt = Find(writingSystemId);
if (string.IsNullOrEmpty(form)) // we don't use space to store empty strings.
{
if (alt != null && !alt.IsStarred)
{
RemoveLanguageForm(alt);
}
}
else
{
if (alt != null)
{
alt.Form = form;
}
else
{
AddLanguageForm(new LanguageForm(writingSystemId, form, this));
}
}
NotifyPropertyChanged(writingSystemId);
}
public void RemoveLanguageForm(LanguageForm languageForm)
{
Debug.Assert(Forms.Length > 0);
LanguageForm[] forms = new LanguageForm[Forms.Length - 1];
for (int i = 0, j = 0; i < forms.Length; i++,j++)
{
if (Forms[j] == languageForm)
{
j++;
}
forms[i] = Forms[j];
}
_forms = forms;
}
protected void AddLanguageForm(LanguageForm languageForm)
{
LanguageForm[] forms = new LanguageForm[Forms.Length + 1];
for (int i = 0; i < Forms.Length; i++)
{
forms[i] = Forms[i];
}
//actually copy the contents, as we must now be the parent
forms[Forms.Length] = new LanguageForm(languageForm, this);
Array.Sort(forms);
_forms = forms;
}
protected void NotifyPropertyChanged(string writingSystemId)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(writingSystemId));
}
}
public IEnumerator GetEnumerator()
{
return Forms.GetEnumerator();
}
public int CompareTo(object o)
{
if(o == null)
{
return 1;
}
if (!(o is MultiTextBase))
{
throw new ArgumentException("Can not compare to objects other than MultiTextBase.");
}
MultiTextBase other = (MultiTextBase) o;
int formLengthOrder = this.Forms.Length.CompareTo(other.Forms.Length);
if(formLengthOrder != 0)
{
return formLengthOrder;
}
for(int i = 0; i < Forms.Length; i++)
{
int languageFormOrder = Forms[i].CompareTo(other.Forms[i]);
if(languageFormOrder != 0)
{
return languageFormOrder;
}
}
return 0;
}
public override string ToString()
{
return GetFirstAlternative();
}
public LanguageForm[] GetOrderedAndFilteredForms(IEnumerable<string> writingSystemIdsInOrder)
{
List<LanguageForm> forms = new List<LanguageForm>();
foreach (string id in writingSystemIdsInOrder)
{
LanguageForm form = Find(id);
if(form!=null)
{
forms.Add(form);
}
}
return forms.ToArray();
}
public void MergeInWithAppend(MultiTextBase incoming, string separator)
{
foreach (LanguageForm form in incoming)
{
LanguageForm f = Find(form.WritingSystemId);
if (f != null)
{
f.Form += separator + form.Form;
}
else
{
AddLanguageForm(form); //this actually copies the meat of the form
}
}
}
public void MergeIn(MultiTextBase incoming)
{
foreach (LanguageForm form in incoming)
{
LanguageForm f = Find(form.WritingSystemId);
if (f != null)
{
f.Form = form.Form;
}
else
{
AddLanguageForm(form); //this actually copies the meat of the form
}
}
}
/// <summary>
/// Will merge the two mt's if they are compatible; if they collide anywhere, leaves the original untouched
/// and returns false
/// </summary>
/// <param name="incoming"></param>
/// <returns></returns>
public bool TryMergeIn(MultiTextBase incoming)
{
//abort if they collide
if (!CanBeUnifiedWith(incoming))
return false;
MergeIn(incoming);
return true;
}
/// <summary>
/// False if they have different forms on any single writing system. If true, they can be safely merged.
/// </summary>
/// <param name="incoming"></param>
/// <returns></returns>
public bool CanBeUnifiedWith(MultiTextBase incoming)
{
foreach (var form in incoming.Forms)
{
if (!ContainsAlternative(form.WritingSystemId))
continue;//no problem, we don't have one of those
if (GetExactAlternative(form.WritingSystemId) != form.Form)
return false;
}
return true;
}
public override bool Equals(Object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof(MultiTextBase)) return false;
return Equals((MultiTextBase)obj);
}
public bool Equals(MultiTextBase other)
{
if (other == null) return false;
if (other.Count != Count) return false;
if (!_forms.SequenceEqual(other.Forms)) return false;
return true;
}
public override int GetHashCode()
{
// https://stackoverflow.com/a/263416/487503
unchecked // Overflow is fine, just wrap
{
var hash = 23;
hash *= 29 + Count.GetHashCode();
hash *= 29 + Forms?.GetHashCode() ?? 0;
return hash;
}
}
public bool HasFormWithSameContent(MultiTextBase other)
{
if (other.Count == 0 && Count == 0)
{
return true;
}
foreach (LanguageForm form in other)
{
if (ContainsEqualForm(form))
{
return true;
}
}
return false;
}
public bool ContainsEqualForm(LanguageForm other)
{
foreach (LanguageForm form in Forms)
{
if (other.Equals(form))
{
return true;
}
}
return false;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics.CodeAnalysis;
namespace System.Net.Sockets
{
// The System.Net.Sockets.UdpClient class provides access to UDP services at a higher abstraction
// level than the System.Net.Sockets.Socket class. System.Net.Sockets.UdpClient is used to
// connect to a remote host and to receive connections from a remote client.
public class UdpClient : IDisposable
{
private const int MaxUDPSize = 0x10000;
private Socket _clientSocket;
private bool _active;
private byte[] _buffer = new byte[MaxUDPSize];
private AddressFamily _family = AddressFamily.InterNetwork;
// Initializes a new instance of the System.Net.Sockets.UdpClientclass.
public UdpClient() : this(AddressFamily.InterNetwork)
{
}
// Initializes a new instance of the System.Net.Sockets.UdpClientclass.
public UdpClient(AddressFamily family)
{
// Validate the address family.
if (family != AddressFamily.InterNetwork && family != AddressFamily.InterNetworkV6)
{
throw new ArgumentException(SR.Format(SR.net_protocol_invalid_family, "UDP"), "family");
}
_family = family;
CreateClientSocket();
}
// Creates a new instance of the UdpClient class that communicates on the
// specified port number.
//
// NOTE: We should obsolete this. This also breaks IPv6-only scenarios.
// But fixing it has many complications that we have decided not
// to fix it and instead obsolete it later.
public UdpClient(int port) : this(port, AddressFamily.InterNetwork)
{
}
// Creates a new instance of the UdpClient class that communicates on the
// specified port number.
public UdpClient(int port, AddressFamily family)
{
// Validate input parameters.
if (!TcpValidationHelpers.ValidatePortNumber(port))
{
throw new ArgumentOutOfRangeException("port");
}
// Validate the address family.
if (family != AddressFamily.InterNetwork && family != AddressFamily.InterNetworkV6)
{
throw new ArgumentException(SR.net_protocol_invalid_family, "family");
}
IPEndPoint localEP;
_family = family;
if (_family == AddressFamily.InterNetwork)
{
localEP = new IPEndPoint(IPAddress.Any, port);
}
else
{
localEP = new IPEndPoint(IPAddress.IPv6Any, port);
}
CreateClientSocket();
Client.Bind(localEP);
}
// Creates a new instance of the UdpClient class that communicates on the
// specified end point.
public UdpClient(IPEndPoint localEP)
{
// Validate input parameters.
if (localEP == null)
{
throw new ArgumentNullException("localEP");
}
// IPv6 Changes: Set the AddressFamily of this object before
// creating the client socket.
_family = localEP.AddressFamily;
CreateClientSocket();
Client.Bind(localEP);
}
// Creates a new instance of the System.Net.Sockets.UdpClient class and connects to the
// specified remote host on the specified port.
public UdpClient(string hostname, int port)
{
// Validate input parameters.
if (hostname == null)
{
throw new ArgumentNullException("hostname");
}
if (!TcpValidationHelpers.ValidatePortNumber(port))
{
throw new ArgumentOutOfRangeException("port");
}
// NOTE: Need to create different kinds of sockets based on the addresses
// returned from DNS. As a result, we defer the creation of the
// socket until the Connect method.
Connect(hostname, port);
}
// Used by the class to provide the underlying network socket.
public Socket Client
{
get
{
return _clientSocket;
}
set
{
_clientSocket = value;
}
}
// Used by the class to indicate that a connection to a remote host has been made.
protected bool Active
{
get
{
return _active;
}
set
{
_active = value;
}
}
public int Available
{
get
{
return _clientSocket.Available;
}
}
public short Ttl
{
get
{
return _clientSocket.Ttl;
}
set
{
_clientSocket.Ttl = value;
}
}
public bool DontFragment
{
get
{
return _clientSocket.DontFragment;
}
set
{
_clientSocket.DontFragment = value;
}
}
public bool MulticastLoopback
{
get
{
return _clientSocket.MulticastLoopback;
}
set
{
_clientSocket.MulticastLoopback = value;
}
}
public bool EnableBroadcast
{
get
{
return _clientSocket.EnableBroadcast;
}
set
{
_clientSocket.EnableBroadcast = value;
}
}
public bool ExclusiveAddressUse
{
get
{
return _clientSocket.ExclusiveAddressUse;
}
set
{
_clientSocket.ExclusiveAddressUse = value;
}
}
public void AllowNatTraversal(bool allowed)
{
if (allowed)
{
_clientSocket.SetIPProtectionLevel(IPProtectionLevel.Unrestricted);
}
else
{
_clientSocket.SetIPProtectionLevel(IPProtectionLevel.EdgeRestricted);
}
}
private bool _cleanedUp = false;
private void FreeResources()
{
// The only resource we need to free is the network stream, since this
// is based on the client socket, closing the stream will cause us
// to flush the data to the network, close the stream and (in the
// NetoworkStream code) close the socket as well.
if (_cleanedUp)
{
return;
}
Socket chkClientSocket = Client;
if (chkClientSocket != null)
{
// If the NetworkStream wasn't retrieved, the Socket might
// still be there and needs to be closed to release the effect
// of the Bind() call and free the bound IPEndPoint.
chkClientSocket.InternalShutdown(SocketShutdown.Both);
chkClientSocket.Dispose();
Client = null;
}
_cleanedUp = true;
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
GlobalLog.Print("UdpClient::Dispose()");
FreeResources();
GC.SuppressFinalize(this);
}
}
// Establishes a connection to the specified port on the specified host.
public void Connect(string hostname, int port)
{
// Validate input parameters.
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (hostname == null)
{
throw new ArgumentNullException("hostname");
}
if (!TcpValidationHelpers.ValidatePortNumber(port))
{
throw new ArgumentOutOfRangeException("port");
}
// IPv6 Changes: instead of just using the first address in the list,
// we must now look for addresses that use a compatible
// address family to the client socket.
// However, in the case of the <hostname,port> constructor
// we will have deferred creating the socket and will
// do that here instead.
// In addition, the redundant CheckForBroadcast call was
// removed here since it is called from Connect().
IPAddress[] addresses = Dns.GetHostAddressesAsync(hostname).GetAwaiter().GetResult();
Exception lastex = null;
Socket ipv6Socket = null;
Socket ipv4Socket = null;
try
{
if (_clientSocket == null)
{
if (Socket.OSSupportsIPv4)
{
ipv4Socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
}
if (Socket.OSSupportsIPv6)
{
ipv6Socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp);
}
}
foreach (IPAddress address in addresses)
{
try
{
if (_clientSocket == null)
{
// We came via the <hostname,port> constructor. Set the
// address family appropriately, create the socket and
// try to connect.
if (address.AddressFamily == AddressFamily.InterNetwork && ipv4Socket != null)
{
ipv4Socket.Connect(address, port);
_clientSocket = ipv4Socket;
if (ipv6Socket != null)
{
ipv6Socket.Dispose();
}
}
else if (ipv6Socket != null)
{
ipv6Socket.Connect(address, port);
_clientSocket = ipv6Socket;
if (ipv4Socket != null)
{
ipv4Socket.Dispose();
}
}
_family = address.AddressFamily;
_active = true;
break;
}
else if (address.AddressFamily == _family)
{
// Only use addresses with a matching family.
Connect(new IPEndPoint(address, port));
_active = true;
break;
}
}
catch (Exception ex)
{
if (ExceptionCheck.IsFatal(ex))
{
throw;
}
lastex = ex;
}
}
}
catch (Exception ex)
{
if (ExceptionCheck.IsFatal(ex))
{
throw;
}
lastex = ex;
}
finally
{
// Cleanup temp sockets on failure. The main socket gets closed when the UDPClient
// gets closed.
// Did we connect?
if (!_active)
{
if (ipv6Socket != null)
{
ipv6Socket.Dispose();
}
if (ipv4Socket != null)
{
ipv4Socket.Dispose();
}
// The connect failed - rethrow the last error we had.
if (lastex != null)
{
throw lastex;
}
else
{
throw new SocketException((int)SocketError.NotConnected);
}
}
}
}
// Establishes a connection with the host at the specified address on the
// specified port.
public void Connect(IPAddress addr, int port)
{
// Validate input parameters.
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (addr == null)
{
throw new ArgumentNullException("addr");
}
if (!TcpValidationHelpers.ValidatePortNumber(port))
{
throw new ArgumentOutOfRangeException("port");
}
// IPv6 Changes: Removed redundant call to CheckForBroadcast() since
// it is made in the real Connect() method.
IPEndPoint endPoint = new IPEndPoint(addr, port);
Connect(endPoint);
}
// Establishes a connection to a remote end point.
public void Connect(IPEndPoint endPoint)
{
// Validate input parameters.
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (endPoint == null)
{
throw new ArgumentNullException("endPoint");
}
// IPv6 Changes: Actually, no changes but we might want to check for
// compatible protocols here rather than push it down
// to WinSock.
CheckForBroadcast(endPoint.Address);
Client.Connect(endPoint);
_active = true;
}
private bool _isBroadcast;
private void CheckForBroadcast(IPAddress ipAddress)
{
// Here we check to see if the user is trying to use a Broadcast IP address
// we only detect IPAddress.Broadcast (which is not the only Broadcast address)
// and in that case we set SocketOptionName.Broadcast on the socket to allow its use.
// if the user really wants complete control over Broadcast addresses he needs to
// inherit from UdpClient and gain control over the Socket and do whatever is appropriate.
if (Client != null && !_isBroadcast && IsBroadcast(ipAddress))
{
// We need to set the Broadcast socket option.
// Note that once we set the option on the Socket we never reset it.
_isBroadcast = true;
Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
}
}
private bool IsBroadcast(IPAddress address)
{
if (address.AddressFamily == AddressFamily.InterNetworkV6)
{
// No such thing as a broadcast address for IPv6.
return false;
}
else
{
return address.Equals(IPAddress.Broadcast);
}
}
// Sends a UDP datagram to the host at the remote end point.
public int Send(byte[] dgram, int bytes, IPEndPoint endPoint)
{
// Validate input parameters.
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (dgram == null)
{
throw new ArgumentNullException("dgram");
}
if (_active && endPoint != null)
{
// Do not allow sending packets to arbitrary host when connected.
throw new InvalidOperationException(SR.net_udpconnected);
}
if (endPoint == null)
{
return Client.Send(dgram, 0, bytes, SocketFlags.None);
}
CheckForBroadcast(endPoint.Address);
return Client.SendTo(dgram, 0, bytes, SocketFlags.None, endPoint);
}
// Sends a UDP datagram to the specified port on the specified remote host.
public int Send(byte[] dgram, int bytes, string hostname, int port)
{
// Validate input parameters.
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (dgram == null)
{
throw new ArgumentNullException("dgram");
}
if (_active && ((hostname != null) || (port != 0)))
{
// Do not allow sending packets to arbitrary host when connected.
throw new InvalidOperationException(SR.net_udpconnected);
}
if (hostname == null || port == 0)
{
return Client.Send(dgram, 0, bytes, SocketFlags.None);
}
IPAddress[] addresses = Dns.GetHostAddressesAsync(hostname).GetAwaiter().GetResult();
int i = 0;
for (; i < addresses.Length && addresses[i].AddressFamily != _family; i++) ;
if (addresses.Length == 0 || i == addresses.Length)
{
throw new ArgumentException(SR.net_invalidAddressList, "hostname");
}
CheckForBroadcast(addresses[i]);
IPEndPoint ipEndPoint = new IPEndPoint(addresses[i], port);
return Client.SendTo(dgram, 0, bytes, SocketFlags.None, ipEndPoint);
}
// Sends a UDP datagram to a remote host.
public int Send(byte[] dgram, int bytes)
{
// Validate input parameters.
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (dgram == null)
{
throw new ArgumentNullException("dgram");
}
if (!_active)
{
// Only allowed on connected socket.
throw new InvalidOperationException(SR.net_notconnected);
}
return Client.Send(dgram, 0, bytes, SocketFlags.None);
}
public IAsyncResult BeginSend(byte[] datagram, int bytes, IPEndPoint endPoint, AsyncCallback requestCallback, object state)
{
// Validate input parameters.
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (datagram == null)
{
throw new ArgumentNullException("datagram");
}
if (bytes > datagram.Length || bytes < 0)
{
throw new ArgumentOutOfRangeException("bytes");
}
if (_active && endPoint != null)
{
// Do not allow sending packets to arbitrary host when connected.
throw new InvalidOperationException(SR.net_udpconnected);
}
if (endPoint == null)
{
return Client.BeginSend(datagram, 0, bytes, SocketFlags.None, requestCallback, state);
}
CheckForBroadcast(endPoint.Address);
return Client.BeginSendTo(datagram, 0, bytes, SocketFlags.None, endPoint, requestCallback, state);
}
public IAsyncResult BeginSend(byte[] datagram, int bytes, string hostname, int port, AsyncCallback requestCallback, object state)
{
if (_active && ((hostname != null) || (port != 0)))
{
// Do not allow sending packets to arbitrary host when connected.
throw new InvalidOperationException(SR.net_udpconnected);
}
IPEndPoint ipEndPoint = null;
if (hostname != null && port != 0)
{
IPAddress[] addresses = Dns.GetHostAddressesAsync(hostname).GetAwaiter().GetResult();
int i = 0;
for (; i < addresses.Length && addresses[i].AddressFamily != _family; i++)
{
}
if (addresses.Length == 0 || i == addresses.Length)
{
throw new ArgumentException(SR.net_invalidAddressList, "hostname");
}
CheckForBroadcast(addresses[i]);
ipEndPoint = new IPEndPoint(addresses[i], port);
}
return BeginSend(datagram, bytes, ipEndPoint, requestCallback, state);
}
public IAsyncResult BeginSend(byte[] datagram, int bytes, AsyncCallback requestCallback, object state)
{
return BeginSend(datagram, bytes, null, requestCallback, state);
}
public int EndSend(IAsyncResult asyncResult)
{
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (_active)
{
return Client.EndSend(asyncResult);
}
else
{
return Client.EndSendTo(asyncResult);
}
}
// Returns a datagram sent by a server.
public byte[] Receive(ref IPEndPoint remoteEP)
{
// Validate input parameters.
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
// Due to the nature of the ReceiveFrom() call and the ref parameter convention,
// we need to cast an IPEndPoint to its base class EndPoint and cast it back down
// to IPEndPoint.
EndPoint tempRemoteEP;
if (_family == AddressFamily.InterNetwork)
{
tempRemoteEP = IPEndPointStatics.Any;
}
else
{
tempRemoteEP = IPEndPointStatics.IPv6Any;
}
int received = Client.ReceiveFrom(_buffer, MaxUDPSize, 0, ref tempRemoteEP);
remoteEP = (IPEndPoint)tempRemoteEP;
// Because we don't return the actual length, we need to ensure the returned buffer
// has the appropriate length.
if (received < MaxUDPSize)
{
byte[] newBuffer = new byte[received];
Buffer.BlockCopy(_buffer, 0, newBuffer, 0, received);
return newBuffer;
}
return _buffer;
}
public IAsyncResult BeginReceive(AsyncCallback requestCallback, object state)
{
// Validate input parameters.
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
// Due to the nature of the ReceiveFrom() call and the ref parameter convention,
// we need to cast an IPEndPoint to its base class EndPoint and cast it back down
// to IPEndPoint.
EndPoint tempRemoteEP;
if (_family == AddressFamily.InterNetwork)
{
tempRemoteEP = IPEndPointStatics.Any;
}
else
{
tempRemoteEP = IPEndPointStatics.IPv6Any;
}
return Client.BeginReceiveFrom(_buffer, 0, MaxUDPSize, SocketFlags.None, ref tempRemoteEP, requestCallback, state);
}
public byte[] EndReceive(IAsyncResult asyncResult, ref IPEndPoint remoteEP)
{
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
EndPoint tempRemoteEP;
if (_family == AddressFamily.InterNetwork)
{
tempRemoteEP = IPEndPointStatics.Any;
}
else
{
tempRemoteEP = IPEndPointStatics.IPv6Any;
}
int received = Client.EndReceiveFrom(asyncResult, ref tempRemoteEP);
remoteEP = (IPEndPoint)tempRemoteEP;
// Because we don't return the actual length, we need to ensure the returned buffer
// has the appropriate length.
if (received < MaxUDPSize)
{
byte[] newBuffer = new byte[received];
Buffer.BlockCopy(_buffer, 0, newBuffer, 0, received);
return newBuffer;
}
return _buffer;
}
// Joins a multicast address group.
public void JoinMulticastGroup(IPAddress multicastAddr)
{
// Validate input parameters.
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (multicastAddr == null)
{
throw new ArgumentNullException("multicastAddr");
}
// IPv6 Changes: we need to create the correct MulticastOption and
// must also check for address family compatibility.
if (multicastAddr.AddressFamily != _family)
{
throw new ArgumentException(SR.Format(SR.net_protocol_invalid_multicast_family, "UDP"), "multicastAddr");
}
if (_family == AddressFamily.InterNetwork)
{
MulticastOption mcOpt = new MulticastOption(multicastAddr);
Client.SetSocketOption(
SocketOptionLevel.IP,
SocketOptionName.AddMembership,
mcOpt);
}
else
{
IPv6MulticastOption mcOpt = new IPv6MulticastOption(multicastAddr);
Client.SetSocketOption(
SocketOptionLevel.IPv6,
SocketOptionName.AddMembership,
mcOpt);
}
}
public void JoinMulticastGroup(IPAddress multicastAddr, IPAddress localAddress)
{
// Validate input parameters.
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (_family != AddressFamily.InterNetwork)
{
throw new SocketException((int)SocketError.OperationNotSupported);
}
MulticastOption mcOpt = new MulticastOption(multicastAddr, localAddress);
Client.SetSocketOption(
SocketOptionLevel.IP,
SocketOptionName.AddMembership,
mcOpt);
}
// Joins an IPv6 multicast address group.
public void JoinMulticastGroup(int ifindex, IPAddress multicastAddr)
{
// Validate input parameters.
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (multicastAddr == null)
{
throw new ArgumentNullException("multicastAddr");
}
if (ifindex < 0)
{
throw new ArgumentException(SR.net_value_cannot_be_negative, "ifindex");
}
// Ensure that this is an IPv6 client, otherwise throw WinSock
// Operation not supported socked exception.
if (_family != AddressFamily.InterNetworkV6)
{
throw new SocketException((int)SocketError.OperationNotSupported);
}
IPv6MulticastOption mcOpt = new IPv6MulticastOption(multicastAddr, ifindex);
Client.SetSocketOption(
SocketOptionLevel.IPv6,
SocketOptionName.AddMembership,
mcOpt);
}
// Joins a multicast address group with the specified time to live (TTL).
public void JoinMulticastGroup(IPAddress multicastAddr, int timeToLive)
{
// parameter validation;
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (multicastAddr == null)
{
throw new ArgumentNullException("multicastAddr");
}
if (!RangeValidationHelpers.ValidateRange(timeToLive, 0, 255))
{
throw new ArgumentOutOfRangeException("timeToLive");
}
// Join the Multicast Group.
JoinMulticastGroup(multicastAddr);
// Set Time To Live (TTL).
Client.SetSocketOption(
(_family == AddressFamily.InterNetwork) ? SocketOptionLevel.IP : SocketOptionLevel.IPv6,
SocketOptionName.MulticastTimeToLive,
timeToLive);
}
// Leaves a multicast address group.
public void DropMulticastGroup(IPAddress multicastAddr)
{
// Validate input parameters.
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (multicastAddr == null)
{
throw new ArgumentNullException("multicastAddr");
}
// IPv6 Changes: we need to create the correct MulticastOption and
// must also check for address family compatibility.
if (multicastAddr.AddressFamily != _family)
{
throw new ArgumentException(SR.Format(SR.net_protocol_invalid_multicast_family, "UDP"), "multicastAddr");
}
if (_family == AddressFamily.InterNetwork)
{
MulticastOption mcOpt = new MulticastOption(multicastAddr);
Client.SetSocketOption(
SocketOptionLevel.IP,
SocketOptionName.DropMembership,
mcOpt);
}
else
{
IPv6MulticastOption mcOpt = new IPv6MulticastOption(multicastAddr);
Client.SetSocketOption(
SocketOptionLevel.IPv6,
SocketOptionName.DropMembership,
mcOpt);
}
}
// Leaves an IPv6 multicast address group.
public void DropMulticastGroup(IPAddress multicastAddr, int ifindex)
{
// Validate input parameters.
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (multicastAddr == null)
{
throw new ArgumentNullException("multicastAddr");
}
if (ifindex < 0)
{
throw new ArgumentException(SR.net_value_cannot_be_negative, "ifindex");
}
// Ensure that this is an IPv6 client, otherwise throw WinSock
// Operation not supported socked exception.
if (_family != AddressFamily.InterNetworkV6)
{
throw new SocketException((int)SocketError.OperationNotSupported);
}
IPv6MulticastOption mcOpt = new IPv6MulticastOption(multicastAddr, ifindex);
Client.SetSocketOption(
SocketOptionLevel.IPv6,
SocketOptionName.DropMembership,
mcOpt);
}
public Task<int> SendAsync(byte[] datagram, int bytes)
{
return Task<int>.Factory.FromAsync(BeginSend, EndSend, datagram, bytes, null);
}
public Task<int> SendAsync(byte[] datagram, int bytes, IPEndPoint endPoint)
{
return Task<int>.Factory.FromAsync(BeginSend, EndSend, datagram, bytes, endPoint, null);
}
public Task<int> SendAsync(byte[] datagram, int bytes, string hostname, int port)
{
return Task<int>.Factory.FromAsync((callback, state) => BeginSend(datagram, bytes, hostname, port, callback, state), EndSend, null);
}
public Task<UdpReceiveResult> ReceiveAsync()
{
return Task<UdpReceiveResult>.Factory.FromAsync((callback, state) => BeginReceive(callback, state), (ar) =>
{
IPEndPoint remoteEP = null;
Byte[] buffer = EndReceive(ar, ref remoteEP);
return new UdpReceiveResult(buffer, remoteEP);
}, null);
}
private void CreateClientSocket()
{
// Common initialization code.
//
// IPv6 Changes: Use the AddressFamily of this class rather than hardcode.
Client = new Socket(_family, SocketType.Dgram, ProtocolType.Udp);
}
}
}
| |
/*
* Copyright (c) 2007-2009, openmetaverse.org
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
namespace OpenMetaverse.Voice
{
public partial class VoiceGateway
{
#region Enums
public enum LoginState
{
LoggedOut = 0,
LoggedIn = 1,
Error = 4
}
public enum SessionState
{
Idle = 1,
Answering = 2,
InProgress = 3,
Connected = 4,
Disconnected = 5,
Hold = 6,
Refer = 7,
Ringing = 8
}
public enum ParticipantState
{
Idle = 1,
Pending = 2,
Incoming = 3,
Answering = 4,
InProgress = 5,
Ringing = 6,
Connected = 7,
Disconnecting = 8,
Disconnected = 9
}
public enum ParticipantType
{
User = 0,
Moderator = 1,
Focus = 2
}
public enum ResponseType
{
None = 0,
ConnectorCreate,
ConnectorInitiateShutdown,
MuteLocalMic,
MuteLocalSpeaker,
SetLocalMicVolume,
SetLocalSpeakerVolume,
GetCaptureDevices,
GetRenderDevices,
SetRenderDevice,
SetCaptureDevice,
CaptureAudioStart,
CaptureAudioStop,
SetMicLevel,
SetSpeakerLevel,
AccountLogin,
AccountLogout,
RenderAudioStart,
RenderAudioStop,
SessionCreate,
SessionConnect,
SessionTerminate,
SetParticipantVolumeForMe,
SetParticipantMuteForMe,
Set3DPosition
}
#endregion Enums
#region Logging
public class VoiceLoggingSettings
{
/// <summary>Enable logging</summary>
public bool Enabled;
/// <summary>The folder where any logs will be created</summary>
public string Folder;
/// <summary>This will be prepended to beginning of each log file</summary>
public string FileNamePrefix;
/// <summary>The suffix or extension to be appended to each log file</summary>
public string FileNameSuffix;
/// <summary>
/// 0: NONE - No logging
/// 1: ERROR - Log errors only
/// 2: WARNING - Log errors and warnings
/// 3: INFO - Log errors, warnings and info
/// 4: DEBUG - Log errors, warnings, info and debug
/// </summary>
public int LogLevel;
/// <summary>
/// Constructor for default logging settings
/// </summary>
public VoiceLoggingSettings()
{
Enabled = false;
Folder = String.Empty;
FileNamePrefix = "Connector";
FileNameSuffix = ".log";
LogLevel = 0;
}
}
#endregion Logging
public class VoiceResponseEventArgs : EventArgs
{
public readonly ResponseType Type;
public readonly int ReturnCode;
public readonly int StatusCode;
public readonly string Message;
// All Voice Response events carry these properties.
public VoiceResponseEventArgs(ResponseType type, int rcode, int scode, string text)
{
this.Type = type;
this.ReturnCode = rcode;
this.StatusCode = scode;
this.Message = text;
}
}
#region Session Event Args
public class VoiceSessionEventArgs : VoiceResponseEventArgs
{
public readonly string SessionHandle;
public VoiceSessionEventArgs(int rcode, int scode, string text, string shandle) :
base(ResponseType.SessionCreate, rcode, scode, text)
{
this.SessionHandle = shandle;
}
}
public class NewSessionEventArgs : EventArgs
{
public readonly string AccountHandle;
public readonly string SessionHandle;
public readonly string URI;
public readonly string Name;
public readonly string AudioMedia;
public NewSessionEventArgs(string AccountHandle, string SessionHandle, string URI, bool IsChannel, string Name, string AudioMedia)
{
this.AccountHandle = AccountHandle;
this.SessionHandle = SessionHandle;
this.URI = URI;
this.Name = Name;
this.AudioMedia = AudioMedia;
}
}
public class SessionMediaEventArgs : EventArgs
{
public readonly string SessionHandle;
public readonly bool HasText;
public readonly bool HasAudio;
public readonly bool HasVideo;
public readonly bool Terminated;
public SessionMediaEventArgs(string SessionHandle, bool HasText, bool HasAudio, bool HasVideo, bool Terminated)
{
this.SessionHandle = SessionHandle;
this.HasText = HasText;
this.HasAudio = HasAudio;
this.HasVideo = HasVideo;
this.Terminated = Terminated;
}
}
public class SessionStateChangeEventArgs : EventArgs
{
public readonly string SessionHandle;
public readonly int StatusCode;
public readonly string StatusString;
public readonly SessionState State;
public readonly string URI;
public readonly bool IsChannel;
public readonly string ChannelName;
public SessionStateChangeEventArgs(string SessionHandle, int StatusCode, string StatusString, SessionState State, string URI, bool IsChannel, string ChannelName)
{
this.SessionHandle = SessionHandle;
this.StatusCode = StatusCode;
this.StatusString = StatusString;
this.State = State;
this.URI = URI;
this.IsChannel = IsChannel;
this.ChannelName = ChannelName;
}
}
// Participants
public class ParticipantAddedEventArgs : EventArgs
{
public readonly string SessionHandle;
public readonly string SessionGroupHandle;
public readonly string URI;
public readonly string AccountName;
public readonly string DisplayName;
public readonly ParticipantType Type;
public readonly string Appllication;
public ParticipantAddedEventArgs(
string SessionGroupHandle,
string SessionHandle,
string ParticipantUri,
string AccountName,
string DisplayName,
ParticipantType type,
string Application)
{
this.SessionGroupHandle = SessionGroupHandle;
this.SessionHandle = SessionHandle;
this.URI = ParticipantUri;
this.AccountName = AccountName;
this.DisplayName = DisplayName;
this.Type = type;
this.Appllication = Application;
}
}
public class ParticipantRemovedEventArgs : EventArgs
{
public readonly string SessionGroupHandle;
public readonly string SessionHandle;
public readonly string URI;
public readonly string AccountName;
public readonly string Reason;
public ParticipantRemovedEventArgs(
string SessionGroupHandle,
string SessionHandle,
string ParticipantUri,
string AccountName,
string Reason)
{
this.SessionGroupHandle = SessionGroupHandle;
this.SessionHandle = SessionHandle;
this.URI = ParticipantUri;
this.AccountName = AccountName;
this.Reason = Reason;
}
}
public class ParticipantStateChangeEventArgs : EventArgs
{
public readonly string SessionHandle;
public readonly int StatusCode;
public readonly string StatusString;
public readonly ParticipantState State;
public readonly string URI;
public readonly string AccountName;
public readonly string DisplayName;
public readonly ParticipantType Type;
public ParticipantStateChangeEventArgs(string SessionHandle, int StatusCode, string StatusString,
ParticipantState State, string ParticipantURI, string AccountName,
string DisplayName, ParticipantType ParticipantType)
{
this.SessionHandle = SessionHandle;
this.StatusCode = StatusCode;
this.StatusString = StatusString;
this.State = State;
this.URI = ParticipantURI;
this.AccountName = AccountName;
this.DisplayName = DisplayName;
this.Type = ParticipantType;
}
}
public class ParticipantPropertiesEventArgs : EventArgs
{
public readonly string SessionHandle;
public readonly string URI;
public readonly bool IsLocallyMuted;
public readonly bool IsModeratorMuted;
public readonly bool IsSpeaking;
public readonly int Volume;
public readonly float Energy;
public ParticipantPropertiesEventArgs(string SessionHandle, string ParticipantURI,
bool IsLocallyMuted, bool IsModeratorMuted, bool IsSpeaking, int Volume, float Energy)
{
this.SessionHandle = SessionHandle;
this.URI = ParticipantURI;
this.IsLocallyMuted = IsLocallyMuted;
this.IsModeratorMuted = IsModeratorMuted;
this.IsSpeaking = IsSpeaking;
this.Volume = Volume;
this.Energy = Energy;
}
}
public class ParticipantUpdatedEventArgs : EventArgs
{
public readonly string SessionHandle;
public readonly string URI;
public readonly bool IsMuted;
public readonly bool IsSpeaking;
public readonly int Volume;
public readonly float Energy;
public ParticipantUpdatedEventArgs(string sessionHandle, string URI, bool isMuted, bool isSpeaking, int volume, float energy)
{
this.SessionHandle = sessionHandle;
this.URI = URI;
this.IsMuted = isMuted;
this.IsSpeaking = isSpeaking;
this.Volume = volume;
this.Energy = energy;
}
}
public class SessionAddedEventArgs : EventArgs
{
public readonly string SessionGroupHandle;
public readonly string SessionHandle;
public readonly string URI;
public readonly bool IsChannel;
public readonly bool IsIncoming;
public SessionAddedEventArgs(string sessionGroupHandle, string sessionHandle,
string URI, bool isChannel, bool isIncoming)
{
this.SessionGroupHandle = sessionGroupHandle;
this.SessionHandle = sessionHandle;
this.URI = URI;
this.IsChannel = isChannel;
this.IsIncoming = isIncoming;
}
}
public class SessionRemovedEventArgs : EventArgs
{
public readonly string SessionGroupHandle;
public readonly string SessionHandle;
public readonly string URI;
public SessionRemovedEventArgs(
string SessionGroupHandle,
string SessionHandle,
string Uri)
{
this.SessionGroupHandle = SessionGroupHandle;
this.SessionHandle = SessionHandle;
this.URI = Uri;
}
}
public class SessionUpdatedEventArgs : EventArgs
{
public readonly string SessionGroupHandle;
public readonly string SessionHandle;
public readonly string URI;
public readonly bool IsMuted;
public readonly int Volume;
public readonly bool TransmitEnabled;
public readonly bool IsFocused;
public SessionUpdatedEventArgs(string SessionGroupHandle,
string SessionHandle, string URI, bool IsMuted, int Volume,
bool TransmitEnabled, bool IsFocused)
{
this.SessionGroupHandle = SessionGroupHandle;
this.SessionHandle = SessionHandle;
this.URI = URI;
this.IsMuted = IsMuted;
this.Volume = Volume;
this.TransmitEnabled = TransmitEnabled;
this.IsFocused = IsFocused;
}
}
public class SessionGroupAddedEventArgs : EventArgs
{
public readonly string AccountHandle;
public readonly string SessionGroupHandle;
public readonly string Type;
public SessionGroupAddedEventArgs(string acctHandle, string sessionGroupHandle, string type)
{
this.AccountHandle = acctHandle;
this.SessionGroupHandle = sessionGroupHandle;
this.Type = type;
}
}
#endregion Session Event Args
#region Connector Delegates
public class VoiceConnectorEventArgs : VoiceResponseEventArgs
{
private readonly string m_Version;
private readonly string m_ConnectorHandle;
public string Version { get { return m_Version; } }
public string Handle { get { return m_ConnectorHandle; } }
public VoiceConnectorEventArgs(int rcode, int scode, string text, string version, string handle) :
base(ResponseType.ConnectorCreate, rcode, scode, text)
{
m_Version = version;
m_ConnectorHandle = handle;
}
}
#endregion Connector Delegates
#region Aux Event Args
public class VoiceDevicesEventArgs : VoiceResponseEventArgs
{
private readonly string m_CurrentDevice;
private readonly List<string> m_Available;
public string CurrentDevice { get { return m_CurrentDevice; } }
public List<string> Devices { get { return m_Available; } }
public VoiceDevicesEventArgs(ResponseType type, int rcode, int scode, string text, string current, List<string> avail) :
base(type, rcode, scode, text)
{
m_CurrentDevice = current;
m_Available = avail;
}
}
/// Audio Properties Events are sent after audio capture is started. These events are used to display a microphone VU meter
public class AudioPropertiesEventArgs : EventArgs
{
public readonly bool IsMicActive;
public readonly float MicEnergy;
public readonly int MicVolume;
public readonly int SpeakerVolume;
public AudioPropertiesEventArgs(bool MicIsActive, float MicEnergy, int MicVolume, int SpeakerVolume)
{
this.IsMicActive = MicIsActive;
this.MicEnergy = MicEnergy;
this.MicVolume = MicVolume;
this.SpeakerVolume = SpeakerVolume;
}
}
#endregion Aux Event Args
#region Account Event Args
public class VoiceAccountEventArgs : VoiceResponseEventArgs
{
private readonly string m_AccountHandle;
public string AccountHandle { get { return m_AccountHandle; } }
public VoiceAccountEventArgs(int rcode, int scode, string text, string ahandle) :
base(ResponseType.AccountLogin, rcode, scode, text)
{
this.m_AccountHandle = ahandle;
}
}
public class AccountLoginStateChangeEventArgs : EventArgs
{
public readonly string AccountHandle;
public readonly int StatusCode;
public readonly string StatusString;
public readonly LoginState State;
public AccountLoginStateChangeEventArgs(string AccountHandle, int StatusCode, string StatusString, LoginState State)
{
this.AccountHandle = AccountHandle;
this.StatusCode = StatusCode;
this.StatusString = StatusString;
this.State = State;
}
}
#endregion Account Event Args
/// <summary>
/// Event for most mundane request reposnses.
/// </summary>
public event EventHandler<VoiceResponseEventArgs> OnVoiceResponse;
#region Session Events
public event EventHandler<VoiceSessionEventArgs> OnSessionCreateResponse;
public event EventHandler<NewSessionEventArgs> OnSessionNewEvent;
public event EventHandler<SessionStateChangeEventArgs> OnSessionStateChangeEvent;
public event EventHandler<ParticipantStateChangeEventArgs> OnSessionParticipantStateChangeEvent;
public event EventHandler<ParticipantPropertiesEventArgs> OnSessionParticipantPropertiesEvent;
public event EventHandler<ParticipantUpdatedEventArgs> OnSessionParticipantUpdatedEvent;
public event EventHandler<ParticipantAddedEventArgs> OnSessionParticipantAddedEvent;
public event EventHandler<ParticipantRemovedEventArgs> OnSessionParticipantRemovedEvent;
public event EventHandler<SessionGroupAddedEventArgs> OnSessionGroupAddedEvent;
public event EventHandler<SessionAddedEventArgs> OnSessionAddedEvent;
public event EventHandler<SessionRemovedEventArgs> OnSessionRemovedEvent;
public event EventHandler<SessionUpdatedEventArgs> OnSessionUpdatedEvent;
public event EventHandler<SessionMediaEventArgs> OnSessionMediaEvent;
#endregion Session Events
#region Connector Events
/// <summary>Response to Connector.Create request</summary>
public event EventHandler<VoiceConnectorEventArgs> OnConnectorCreateResponse;
#endregion Connector Events
#region Aux Events
/// <summary>Response to Aux.GetCaptureDevices request</summary>
public event EventHandler<VoiceDevicesEventArgs> OnAuxGetCaptureDevicesResponse;
/// <summary>Response to Aux.GetRenderDevices request</summary>
public event EventHandler<VoiceDevicesEventArgs> OnAuxGetRenderDevicesResponse;
/// <summary>Audio Properties Events are sent after audio capture is started.
/// These events are used to display a microphone VU meter</summary>
public event EventHandler<AudioPropertiesEventArgs> OnAuxAudioPropertiesEvent;
#endregion Aux Events
#region Account Events
/// <summary>Response to Account.Login request</summary>
public event EventHandler<VoiceAccountEventArgs> OnAccountLoginResponse;
/// <summary>This event message is sent whenever the login state of the
/// particular Account has transitioned from one value to another</summary>
public event EventHandler<AccountLoginStateChangeEventArgs> OnAccountLoginStateChangeEvent;
#endregion Account Events
#region XML Serialization Classes
private XmlSerializer EventSerializer = new XmlSerializer(typeof(VoiceEvent));
private XmlSerializer ResponseSerializer = new XmlSerializer(typeof(VoiceResponse));
[XmlRoot("Event")]
public class VoiceEvent
{
[XmlAttribute("type")]
public string Type;
public string AccountHandle;
public string Application;
public string StatusCode;
public string StatusString;
public string State;
public string SessionHandle;
public string SessionGroupHandle;
public string URI;
public string Uri; // Yes, they send it with both capitalizations
public string IsChannel;
public string IsIncoming;
public string Incoming;
public string IsMuted;
public string Name;
public string AudioMedia;
public string ChannelName;
public string ParticipantUri;
public string AccountName;
public string DisplayName;
public string ParticipantType;
public string IsLocallyMuted;
public string IsModeratorMuted;
public string IsSpeaking;
public string Volume;
public string Energy;
public string MicIsActive;
public string MicEnergy;
public string MicVolume;
public string SpeakerVolume;
public string HasText;
public string HasAudio;
public string HasVideo;
public string Terminated;
public string Reason;
public string TransmitEnabled;
public string IsFocused;
}
[XmlRoot("Response")]
public class VoiceResponse
{
[XmlAttribute("requestId")]
public string RequestId;
[XmlAttribute("action")]
public string Action;
public string ReturnCode;
public VoiceResponseResults Results;
public VoiceInputXml InputXml;
}
public class CaptureDevice
{
public string Device;
}
public class RenderDevice
{
public string Device;
}
public class VoiceResponseResults
{
public string VersionID;
public string StatusCode;
public string StatusString;
public string ConnectorHandle;
public string AccountHandle;
public string SessionHandle;
public List<CaptureDevice> CaptureDevices;
public CaptureDevice CurrentCaptureDevice;
public List<RenderDevice> RenderDevices;
public RenderDevice CurrentRenderDevice;
}
public class VoiceInputXml
{
public VoiceRequest Request;
}
[XmlRoot("Request")]
public class VoiceRequest
{
[XmlAttribute("requestId")]
public string RequestId;
[XmlAttribute("action")]
public string Action;
public string RenderDeviceSpecifier;
public string CaptureDeviceSpecifier;
public string Duration;
public string Level;
public string ClientName;
public string AccountManagementServer;
public string MinimumPort;
public string MaximumPort;
public VoiceLoggingSettings Logging;
public string ConnectorHandle;
public string Value;
public string AccountName;
public string AccountPassword;
public string AudioSessionAnswerMode;
public string AccountURI;
public string ParticipantPropertyFrequency;
public string EnableBuddiesAndPresence;
public string URI;
public string Name;
public string Password;
public string JoinAudio;
public string JoinText;
public string PasswordHashAlgorithm;
public string SoundFilePath;
public string Loop;
public string SessionHandle;
public string OrientationType;
public VoicePosition SpeakerPosition;
public VoicePosition ListenerPosition;
public string ParticipantURI;
public string Volume;
}
#endregion XML Serialization Classes
}
public class VoicePosition
{
/// <summary>Positional vector of the users position</summary>
public Vector3d Position;
/// <summary>Velocity vector of the position</summary>
public Vector3d Velocity;
/// <summary>At Orientation (X axis) of the position</summary>
public Vector3d AtOrientation;
/// <summary>Up Orientation (Y axis) of the position</summary>
public Vector3d UpOrientation;
/// <summary>Left Orientation (Z axis) of the position</summary>
public Vector3d LeftOrientation;
}
}
| |
namespace EIDSS.Reports.Document.Veterinary.LivestockInvestigation
{
partial class VaccinationReport
{
/// <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 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(VaccinationReport));
this.Detail = new DevExpress.XtraReports.UI.DetailBand();
this.xrTable1 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell12 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell17 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell18 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell15 = new DevExpress.XtraReports.UI.XRTableCell();
this.PageHeader = new DevExpress.XtraReports.UI.PageHeaderBand();
this.PageFooter = new DevExpress.XtraReports.UI.PageFooterBand();
this.ReportHeader = new DevExpress.XtraReports.UI.ReportHeaderBand();
this.xrLabel1 = new DevExpress.XtraReports.UI.XRLabel();
this.xrTableHeader = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell11 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell14 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell16 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell13 = new DevExpress.XtraReports.UI.XRTableCell();
this.vaccinationDataSet1 = new EIDSS.Reports.Document.Veterinary.LivestockInvestigation.VaccinationDataSet();
this.sp_rep_VET_AvianCase_VaccinationTableAdapter = new EIDSS.Reports.Document.Veterinary.LivestockInvestigation.VaccinationDataSetTableAdapters.sp_rep_VET_AvianCase_VaccinationTableAdapter();
this.topMarginBand1 = new DevExpress.XtraReports.UI.TopMarginBand();
this.bottomMarginBand1 = new DevExpress.XtraReports.UI.BottomMarginBand();
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTableHeader)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.vaccinationDataSet1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
//
// Detail
//
this.Detail.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable1});
resources.ApplyResources(this.Detail, "Detail");
this.Detail.Name = "Detail";
this.Detail.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.Detail.StylePriority.UseFont = false;
this.Detail.StylePriority.UsePadding = false;
this.Detail.StylePriority.UseTextAlignment = false;
//
// xrTable1
//
this.xrTable1.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
resources.ApplyResources(this.xrTable1, "xrTable1");
this.xrTable1.Name = "xrTable1";
this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow2});
this.xrTable1.StylePriority.UseBorders = false;
//
// xrTableRow2
//
this.xrTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell5,
this.xrTableCell6,
this.xrTableCell10,
this.xrTableCell12,
this.xrTableCell7,
this.xrTableCell8,
this.xrTableCell17,
this.xrTableCell18,
this.xrTableCell15});
resources.ApplyResources(this.xrTableRow2, "xrTableRow2");
this.xrTableRow2.Name = "xrTableRow2";
//
// xrTableCell5
//
this.xrTableCell5.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetVaccination.Diagnosis")});
resources.ApplyResources(this.xrTableCell5, "xrTableCell5");
this.xrTableCell5.Name = "xrTableCell5";
//
// xrTableCell6
//
this.xrTableCell6.Angle = 90F;
this.xrTableCell6.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetVaccination.datVaccinationDate", "{0:dd/MM/yyyy}")});
resources.ApplyResources(this.xrTableCell6, "xrTableCell6");
this.xrTableCell6.Name = "xrTableCell6";
this.xrTableCell6.StylePriority.UseTextAlignment = false;
//
// xrTableCell10
//
this.xrTableCell10.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetVaccination.strSpecies")});
resources.ApplyResources(this.xrTableCell10, "xrTableCell10");
this.xrTableCell10.Name = "xrTableCell10";
this.xrTableCell10.StylePriority.UseTextAlignment = false;
//
// xrTableCell12
//
this.xrTableCell12.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetVaccination.intNumberVaccinated")});
resources.ApplyResources(this.xrTableCell12, "xrTableCell12");
this.xrTableCell12.Name = "xrTableCell12";
this.xrTableCell12.StylePriority.UseTextAlignment = false;
//
// xrTableCell7
//
this.xrTableCell7.Angle = 90F;
this.xrTableCell7.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetVaccination.strType")});
resources.ApplyResources(this.xrTableCell7, "xrTableCell7");
this.xrTableCell7.Name = "xrTableCell7";
this.xrTableCell7.StylePriority.UseTextAlignment = false;
//
// xrTableCell8
//
this.xrTableCell8.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetVaccination.strRouteAdministered")});
resources.ApplyResources(this.xrTableCell8, "xrTableCell8");
this.xrTableCell8.Name = "xrTableCell8";
//
// xrTableCell17
//
this.xrTableCell17.Angle = 90F;
this.xrTableCell17.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetVaccination.strLotNumber")});
resources.ApplyResources(this.xrTableCell17, "xrTableCell17");
this.xrTableCell17.Name = "xrTableCell17";
this.xrTableCell17.StylePriority.UseTextAlignment = false;
//
// xrTableCell18
//
this.xrTableCell18.Angle = 90F;
this.xrTableCell18.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetVaccination.strManufacturer")});
resources.ApplyResources(this.xrTableCell18, "xrTableCell18");
this.xrTableCell18.Name = "xrTableCell18";
this.xrTableCell18.StylePriority.UseTextAlignment = false;
//
// xrTableCell15
//
this.xrTableCell15.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetVaccination.strNote")});
resources.ApplyResources(this.xrTableCell15, "xrTableCell15");
this.xrTableCell15.Name = "xrTableCell15";
//
// PageHeader
//
resources.ApplyResources(this.PageHeader, "PageHeader");
this.PageHeader.Name = "PageHeader";
this.PageHeader.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F);
this.PageHeader.StylePriority.UseFont = false;
//
// PageFooter
//
resources.ApplyResources(this.PageFooter, "PageFooter");
this.PageFooter.Name = "PageFooter";
this.PageFooter.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F);
//
// ReportHeader
//
this.ReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrLabel1,
this.xrTableHeader});
resources.ApplyResources(this.ReportHeader, "ReportHeader");
this.ReportHeader.Name = "ReportHeader";
this.ReportHeader.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.ReportHeader.StylePriority.UseFont = false;
this.ReportHeader.StylePriority.UsePadding = false;
this.ReportHeader.StylePriority.UseTextAlignment = false;
//
// xrLabel1
//
this.xrLabel1.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.xrLabel1, "xrLabel1");
this.xrLabel1.Name = "xrLabel1";
this.xrLabel1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xrLabel1.StylePriority.UseBorders = false;
this.xrLabel1.StylePriority.UseFont = false;
//
// xrTableHeader
//
this.xrTableHeader.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
resources.ApplyResources(this.xrTableHeader, "xrTableHeader");
this.xrTableHeader.Name = "xrTableHeader";
this.xrTableHeader.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow1});
this.xrTableHeader.StylePriority.UseBorders = false;
//
// xrTableRow1
//
this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell4,
this.xrTableCell1,
this.xrTableCell9,
this.xrTableCell11,
this.xrTableCell2,
this.xrTableCell3,
this.xrTableCell14,
this.xrTableCell16,
this.xrTableCell13});
resources.ApplyResources(this.xrTableRow1, "xrTableRow1");
this.xrTableRow1.Name = "xrTableRow1";
//
// xrTableCell4
//
resources.ApplyResources(this.xrTableCell4, "xrTableCell4");
this.xrTableCell4.Multiline = true;
this.xrTableCell4.Name = "xrTableCell4";
//
// xrTableCell1
//
this.xrTableCell1.Angle = 90F;
resources.ApplyResources(this.xrTableCell1, "xrTableCell1");
this.xrTableCell1.Name = "xrTableCell1";
//
// xrTableCell9
//
resources.ApplyResources(this.xrTableCell9, "xrTableCell9");
this.xrTableCell9.Name = "xrTableCell9";
//
// xrTableCell11
//
this.xrTableCell11.Angle = 90F;
resources.ApplyResources(this.xrTableCell11, "xrTableCell11");
this.xrTableCell11.Name = "xrTableCell11";
//
// xrTableCell2
//
this.xrTableCell2.Angle = 90F;
resources.ApplyResources(this.xrTableCell2, "xrTableCell2");
this.xrTableCell2.Name = "xrTableCell2";
//
// xrTableCell3
//
resources.ApplyResources(this.xrTableCell3, "xrTableCell3");
this.xrTableCell3.Name = "xrTableCell3";
//
// xrTableCell14
//
this.xrTableCell14.Angle = 90F;
resources.ApplyResources(this.xrTableCell14, "xrTableCell14");
this.xrTableCell14.Name = "xrTableCell14";
//
// xrTableCell16
//
this.xrTableCell16.Angle = 90F;
resources.ApplyResources(this.xrTableCell16, "xrTableCell16");
this.xrTableCell16.Name = "xrTableCell16";
//
// xrTableCell13
//
resources.ApplyResources(this.xrTableCell13, "xrTableCell13");
this.xrTableCell13.Name = "xrTableCell13";
//
// vaccinationDataSet1
//
this.vaccinationDataSet1.DataSetName = "VaccinationDataSet";
this.vaccinationDataSet1.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
//
// sp_rep_VET_AvianCase_VaccinationTableAdapter
//
this.sp_rep_VET_AvianCase_VaccinationTableAdapter.ClearBeforeFill = true;
//
// topMarginBand1
//
resources.ApplyResources(this.topMarginBand1, "topMarginBand1");
this.topMarginBand1.Name = "topMarginBand1";
//
// bottomMarginBand1
//
resources.ApplyResources(this.bottomMarginBand1, "bottomMarginBand1");
this.bottomMarginBand1.Name = "bottomMarginBand1";
//
// VaccinationReport
//
this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.Detail,
this.PageHeader,
this.PageFooter,
this.ReportHeader,
this.topMarginBand1,
this.bottomMarginBand1});
this.DataAdapter = this.sp_rep_VET_AvianCase_VaccinationTableAdapter;
this.DataMember = "spRepVetVaccination";
this.DataSource = this.vaccinationDataSet1;
resources.ApplyResources(this, "$this");
this.ExportOptions.Xls.SheetName = resources.GetString("VaccinationReport.ExportOptions.Xls.SheetName");
this.ExportOptions.Xlsx.SheetName = resources.GetString("VaccinationReport.ExportOptions.Xlsx.SheetName");
this.Version = "14.1";
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTableHeader)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.vaccinationDataSet1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
}
#endregion
private DevExpress.XtraReports.UI.DetailBand Detail;
private DevExpress.XtraReports.UI.PageHeaderBand PageHeader;
private DevExpress.XtraReports.UI.PageFooterBand PageFooter;
private DevExpress.XtraReports.UI.ReportHeaderBand ReportHeader;
private DevExpress.XtraReports.UI.XRTable xrTableHeader;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell4;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell2;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell3;
private DevExpress.XtraReports.UI.XRTable xrTable1;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow2;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell5;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell6;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell7;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell8;
private VaccinationDataSet vaccinationDataSet1;
private EIDSS.Reports.Document.Veterinary.LivestockInvestigation.VaccinationDataSetTableAdapters.sp_rep_VET_AvianCase_VaccinationTableAdapter sp_rep_VET_AvianCase_VaccinationTableAdapter;
private DevExpress.XtraReports.UI.XRLabel xrLabel1;
private DevExpress.XtraReports.UI.TopMarginBand topMarginBand1;
private DevExpress.XtraReports.UI.BottomMarginBand bottomMarginBand1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell10;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell12;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell17;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell18;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell15;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell9;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell11;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell14;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell16;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell13;
}
}
| |
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2017 FUJIWARA, Yusuke
//
// 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 -- License Terms --
using System;
using System.Globalization;
#if ( NET35 || SILVERLIGHT ) && !WINDOWS_UWP
using System.Threading;
#endif // ( NET35 || SILVERLIGHT ) && !WINDOWS_UWP
#if !MSTEST
using NUnit.Framework;
#else
using TestFixtureAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using TestAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
using TimeoutAttribute = NUnit.Framework.TimeoutAttribute;
using Assert = NUnit.Framework.Assert;
using Is = NUnit.Framework.Is;
#endif
namespace MsgPack
{
partial class TimestampTest
{
[Test]
public void TestToStringCore_Zero_LowerO()
{
var value =
new Timestamp.Value(
0,
1,
1,
0,
0,
0,
0
);
Assert.That(
TimestampStringConverter.ToString(
"o",
CultureInfo.InvariantCulture,
ref value
),
Is.EqualTo( "0000-01-01T00:00:00.000000000Z" )
);
}
[Test]
public void TestToStringCore_Zero_UpperO()
{
var value =
new Timestamp.Value(
0,
1,
1,
0,
0,
0,
0
);
Assert.That(
TimestampStringConverter.ToString(
"O",
CultureInfo.InvariantCulture,
ref value
),
Is.EqualTo( "0000-01-01T00:00:00.000000000Z" )
);
}
[Test]
public void TestToStringCore_Zero_LowerS()
{
var value =
new Timestamp.Value(
0,
1,
1,
0,
0,
0,
0
);
Assert.That(
TimestampStringConverter.ToString(
"s",
CultureInfo.InvariantCulture,
ref value
),
Is.EqualTo( "0000-01-01T00:00:00Z" )
);
}
[Test]
public void TestToStringCore_FullDigits_LowerO()
{
var value =
new Timestamp.Value(
1000,
10,
10,
10,
10,
10,
123456789
);
Assert.That(
TimestampStringConverter.ToString(
"o",
CultureInfo.InvariantCulture,
ref value
),
Is.EqualTo( "1000-10-10T10:10:10.123456789Z" )
);
}
[Test]
public void TestToStringCore_FullDigits_UpperO()
{
var value =
new Timestamp.Value(
1000,
10,
10,
10,
10,
10,
123456789
);
Assert.That(
TimestampStringConverter.ToString(
"O",
CultureInfo.InvariantCulture,
ref value
),
Is.EqualTo( "1000-10-10T10:10:10.123456789Z" )
);
}
[Test]
public void TestToStringCore_FullDigits_LowerS()
{
var value =
new Timestamp.Value(
1000,
10,
10,
10,
10,
10,
123456789
);
Assert.That(
TimestampStringConverter.ToString(
"s",
CultureInfo.InvariantCulture,
ref value
),
Is.EqualTo( "1000-10-10T10:10:10Z" )
);
}
[Test]
public void TestToStringCore_YearMinus1_LowerO()
{
var value =
new Timestamp.Value(
-1,
1,
1,
0,
0,
0,
0
);
Assert.That(
TimestampStringConverter.ToString(
"o",
CultureInfo.InvariantCulture,
ref value
),
Is.EqualTo( "-0001-01-01T00:00:00.000000000Z" )
);
}
[Test]
public void TestToStringCore_YearMinus1_UpperO()
{
var value =
new Timestamp.Value(
-1,
1,
1,
0,
0,
0,
0
);
Assert.That(
TimestampStringConverter.ToString(
"O",
CultureInfo.InvariantCulture,
ref value
),
Is.EqualTo( "-0001-01-01T00:00:00.000000000Z" )
);
}
[Test]
public void TestToStringCore_YearMinus1_LowerS()
{
var value =
new Timestamp.Value(
-1,
1,
1,
0,
0,
0,
0
);
Assert.That(
TimestampStringConverter.ToString(
"s",
CultureInfo.InvariantCulture,
ref value
),
Is.EqualTo( "-0001-01-01T00:00:00Z" )
);
}
[Test]
public void TestToStringCore_YearMinus1000_LowerO()
{
var value =
new Timestamp.Value(
-1000,
1,
1,
0,
0,
0,
0
);
Assert.That(
TimestampStringConverter.ToString(
"o",
CultureInfo.InvariantCulture,
ref value
),
Is.EqualTo( "-1000-01-01T00:00:00.000000000Z" )
);
}
[Test]
public void TestToStringCore_YearMinus1000_UpperO()
{
var value =
new Timestamp.Value(
-1000,
1,
1,
0,
0,
0,
0
);
Assert.That(
TimestampStringConverter.ToString(
"O",
CultureInfo.InvariantCulture,
ref value
),
Is.EqualTo( "-1000-01-01T00:00:00.000000000Z" )
);
}
[Test]
public void TestToStringCore_YearMinus1000_LowerS()
{
var value =
new Timestamp.Value(
-1000,
1,
1,
0,
0,
0,
0
);
Assert.That(
TimestampStringConverter.ToString(
"s",
CultureInfo.InvariantCulture,
ref value
),
Is.EqualTo( "-1000-01-01T00:00:00Z" )
);
}
[Test]
public void TestToStringCore_Year10000_LowerO()
{
var value =
new Timestamp.Value(
10000,
10,
10,
10,
10,
10,
123456789
);
Assert.That(
TimestampStringConverter.ToString(
"o",
CultureInfo.InvariantCulture,
ref value
),
Is.EqualTo( "10000-10-10T10:10:10.123456789Z" )
);
}
[Test]
public void TestToStringCore_Year10000_UpperO()
{
var value =
new Timestamp.Value(
10000,
10,
10,
10,
10,
10,
123456789
);
Assert.That(
TimestampStringConverter.ToString(
"O",
CultureInfo.InvariantCulture,
ref value
),
Is.EqualTo( "10000-10-10T10:10:10.123456789Z" )
);
}
[Test]
public void TestToStringCore_Year10000_LowerS()
{
var value =
new Timestamp.Value(
10000,
10,
10,
10,
10,
10,
123456789
);
Assert.That(
TimestampStringConverter.ToString(
"s",
CultureInfo.InvariantCulture,
ref value
),
Is.EqualTo( "10000-10-10T10:10:10Z" )
);
}
[Test]
public void TestToStringCore_YearMinus10000_LowerO()
{
var value =
new Timestamp.Value(
-10000,
10,
10,
10,
10,
10,
123456789
);
Assert.That(
TimestampStringConverter.ToString(
"o",
CultureInfo.InvariantCulture,
ref value
),
Is.EqualTo( "-10000-10-10T10:10:10.123456789Z" )
);
}
[Test]
public void TestToStringCore_YearMinus10000_UpperO()
{
var value =
new Timestamp.Value(
-10000,
10,
10,
10,
10,
10,
123456789
);
Assert.That(
TimestampStringConverter.ToString(
"O",
CultureInfo.InvariantCulture,
ref value
),
Is.EqualTo( "-10000-10-10T10:10:10.123456789Z" )
);
}
[Test]
public void TestToStringCore_YearMinus10000_LowerS()
{
var value =
new Timestamp.Value(
-10000,
10,
10,
10,
10,
10,
123456789
);
Assert.That(
TimestampStringConverter.ToString(
"s",
CultureInfo.InvariantCulture,
ref value
),
Is.EqualTo( "-10000-10-10T10:10:10Z" )
);
}
[Test]
public void TestToStringCore_TimestampMin_LowerO()
{
var value =
new Timestamp.Value(
-292277022657,
1,
27,
8,
29,
52,
0
);
Assert.That(
TimestampStringConverter.ToString(
"o",
CultureInfo.InvariantCulture,
ref value
),
Is.EqualTo( "-292277022657-01-27T08:29:52.000000000Z" )
);
}
[Test]
public void TestToStringCore_TimestampMin_UpperO()
{
var value =
new Timestamp.Value(
-292277022657,
1,
27,
8,
29,
52,
0
);
Assert.That(
TimestampStringConverter.ToString(
"O",
CultureInfo.InvariantCulture,
ref value
),
Is.EqualTo( "-292277022657-01-27T08:29:52.000000000Z" )
);
}
[Test]
public void TestToStringCore_TimestampMin_LowerS()
{
var value =
new Timestamp.Value(
-292277022657,
1,
27,
8,
29,
52,
0
);
Assert.That(
TimestampStringConverter.ToString(
"s",
CultureInfo.InvariantCulture,
ref value
),
Is.EqualTo( "-292277022657-01-27T08:29:52Z" )
);
}
[Test]
public void TestToStringCore_TimestampMax_LowerO()
{
var value =
new Timestamp.Value(
292277026596,
12,
4,
15,
30,
7,
999999999
);
Assert.That(
TimestampStringConverter.ToString(
"o",
CultureInfo.InvariantCulture,
ref value
),
Is.EqualTo( "292277026596-12-04T15:30:07.999999999Z" )
);
}
[Test]
public void TestToStringCore_TimestampMax_UpperO()
{
var value =
new Timestamp.Value(
292277026596,
12,
4,
15,
30,
7,
999999999
);
Assert.That(
TimestampStringConverter.ToString(
"O",
CultureInfo.InvariantCulture,
ref value
),
Is.EqualTo( "292277026596-12-04T15:30:07.999999999Z" )
);
}
[Test]
public void TestToStringCore_TimestampMax_LowerS()
{
var value =
new Timestamp.Value(
292277026596,
12,
4,
15,
30,
7,
999999999
);
Assert.That(
TimestampStringConverter.ToString(
"s",
CultureInfo.InvariantCulture,
ref value
),
Is.EqualTo( "292277026596-12-04T15:30:07Z" )
);
}
[Test]
public void TestToString_String_IFormatProvider_Distinguishable_o_InvariantCulture()
{
Assert.That(
new Timestamp(
-23215049511,
123456789
).ToString( "o", CultureInfo.InvariantCulture ),
Is.EqualTo( "1234-05-06T07:08:09.123456789Z" )
);
}
[Test]
public void TestToString_String_IFormatProvider_Distinguishable_s_InvariantCulture()
{
Assert.That(
new Timestamp(
-23215049511,
123456789
).ToString( "s", CultureInfo.InvariantCulture ),
Is.EqualTo( "1234-05-06T07:08:09Z" )
);
}
[Test]
public void TestToString_String_IFormatProvider_Distinguishable_null_InvariantCulture_FormatIsO()
{
Assert.That(
new Timestamp(
-23215049511,
123456789
).ToString( null, CultureInfo.InvariantCulture ),
Is.EqualTo( "1234-05-06T07:08:09.123456789Z" )
);
}
[Test]
public void TestToString_String_IFormatProvider_YearMinus1_o_InvariantCulture()
{
Assert.That(
new Timestamp(
-62193657600,
0
).ToString( "o", CultureInfo.InvariantCulture ),
Is.EqualTo( "-0001-03-01T00:00:00.000000000Z" )
);
}
[Test]
public void TestToString_String_IFormatProvider_YearMinus1_s_InvariantCulture()
{
Assert.That(
new Timestamp(
-62193657600,
0
).ToString( "s", CultureInfo.InvariantCulture ),
Is.EqualTo( "-0001-03-01T00:00:00Z" )
);
}
[Test]
public void TestToString_String_IFormatProvider_YearMinus1_null_InvariantCulture_FormatIsO()
{
Assert.That(
new Timestamp(
-62193657600,
0
).ToString( null, CultureInfo.InvariantCulture ),
Is.EqualTo( "-0001-03-01T00:00:00.000000000Z" )
);
}
[Test]
public void TestToString_String_IFormatProvider_Distinguishable_o_CustomCulture_UsedForNegativeSign()
{
Assert.That(
new Timestamp(
-23215049511,
123456789
).ToString( "o", new LegacyJapaneseCultureInfo() ),
Is.EqualTo( "1234-05-06T07:08:09.123456789Z" )
);
}
#if !WINDOWS_PHONE && !WINDOWS_PHONE_APP && !NETFX_CORE
[Test]
public void TestToString_String_IFormatProvider_Distinguishable_o_null_CurrentCultureIsUsed()
{
var originalCurrentCulture = CultureInfo.CurrentCulture;
try
{
#if ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
CultureInfo.CurrentCulture =
#else // ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
Thread.CurrentThread.CurrentCulture =
#endif // ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
new LegacyJapaneseCultureInfo();
if ( !( CultureInfo.CurrentCulture is LegacyJapaneseCultureInfo ) || CultureInfo.CurrentCulture.NumberFormat.NegativeSign != "\uFF0D" )
{
Assert.Ignore( "This platform does not support custom culture correctly." );
}
Assert.That(
new Timestamp(
-23215049511,
123456789
).ToString( "o", null ),
Is.EqualTo( "1234-05-06T07:08:09.123456789Z" )
);
}
finally
{
#if ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
CultureInfo.CurrentCulture =
#else // ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
Thread.CurrentThread.CurrentCulture =
#endif // ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
originalCurrentCulture;
}
}
#endif // !WINDOWS_PHONE && !WINDOWS_PHONE_APP && !NETFX_CORE
[Test]
public void TestToString_String_IFormatProvider_Distinguishable_s_CustomCulture_UsedForNegativeSign()
{
Assert.That(
new Timestamp(
-23215049511,
123456789
).ToString( "s", new LegacyJapaneseCultureInfo() ),
Is.EqualTo( "1234-05-06T07:08:09Z" )
);
}
#if !WINDOWS_PHONE && !WINDOWS_PHONE_APP && !NETFX_CORE
[Test]
public void TestToString_String_IFormatProvider_Distinguishable_s_null_CurrentCultureIsUsed()
{
var originalCurrentCulture = CultureInfo.CurrentCulture;
try
{
#if ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
CultureInfo.CurrentCulture =
#else // ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
Thread.CurrentThread.CurrentCulture =
#endif // ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
new LegacyJapaneseCultureInfo();
if ( !( CultureInfo.CurrentCulture is LegacyJapaneseCultureInfo ) || CultureInfo.CurrentCulture.NumberFormat.NegativeSign != "\uFF0D" )
{
Assert.Ignore( "This platform does not support custom culture correctly." );
}
Assert.That(
new Timestamp(
-23215049511,
123456789
).ToString( "s", null ),
Is.EqualTo( "1234-05-06T07:08:09Z" )
);
}
finally
{
#if ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
CultureInfo.CurrentCulture =
#else // ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
Thread.CurrentThread.CurrentCulture =
#endif // ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
originalCurrentCulture;
}
}
#endif // !WINDOWS_PHONE && !WINDOWS_PHONE_APP && !NETFX_CORE
[Test]
public void TestToString_String_IFormatProvider_YearMinus1_o_CustomCulture_UsedForNegativeSign()
{
Assert.That(
new Timestamp(
-62193657600,
0
).ToString( "o", new LegacyJapaneseCultureInfo() ),
Is.EqualTo( "\uFF0D0001-03-01T00:00:00.000000000Z" )
);
}
#if !WINDOWS_PHONE && !WINDOWS_PHONE_APP && !NETFX_CORE
[Test]
public void TestToString_String_IFormatProvider_YearMinus1_o_null_CurrentCultureIsUsed()
{
var originalCurrentCulture = CultureInfo.CurrentCulture;
try
{
#if ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
CultureInfo.CurrentCulture =
#else // ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
Thread.CurrentThread.CurrentCulture =
#endif // ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
new LegacyJapaneseCultureInfo();
if ( !( CultureInfo.CurrentCulture is LegacyJapaneseCultureInfo ) || CultureInfo.CurrentCulture.NumberFormat.NegativeSign != "\uFF0D" )
{
Assert.Ignore( "This platform does not support custom culture correctly." );
}
Assert.That(
new Timestamp(
-62193657600,
0
).ToString( "o", null ),
Is.EqualTo( "\uFF0D0001-03-01T00:00:00.000000000Z" )
);
}
finally
{
#if ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
CultureInfo.CurrentCulture =
#else // ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
Thread.CurrentThread.CurrentCulture =
#endif // ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
originalCurrentCulture;
}
}
#endif // !WINDOWS_PHONE && !WINDOWS_PHONE_APP && !NETFX_CORE
[Test]
public void TestToString_String_IFormatProvider_YearMinus1_s_CustomCulture_UsedForNegativeSign()
{
Assert.That(
new Timestamp(
-62193657600,
0
).ToString( "s", new LegacyJapaneseCultureInfo() ),
Is.EqualTo( "\uFF0D0001-03-01T00:00:00Z" )
);
}
#if !WINDOWS_PHONE && !WINDOWS_PHONE_APP && !NETFX_CORE
[Test]
public void TestToString_String_IFormatProvider_YearMinus1_s_null_CurrentCultureIsUsed()
{
var originalCurrentCulture = CultureInfo.CurrentCulture;
try
{
#if ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
CultureInfo.CurrentCulture =
#else // ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
Thread.CurrentThread.CurrentCulture =
#endif // ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
new LegacyJapaneseCultureInfo();
if ( !( CultureInfo.CurrentCulture is LegacyJapaneseCultureInfo ) || CultureInfo.CurrentCulture.NumberFormat.NegativeSign != "\uFF0D" )
{
Assert.Ignore( "This platform does not support custom culture correctly." );
}
Assert.That(
new Timestamp(
-62193657600,
0
).ToString( "s", null ),
Is.EqualTo( "\uFF0D0001-03-01T00:00:00Z" )
);
}
finally
{
#if ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
CultureInfo.CurrentCulture =
#else // ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
Thread.CurrentThread.CurrentCulture =
#endif // ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
originalCurrentCulture;
}
}
#endif // !WINDOWS_PHONE && !WINDOWS_PHONE_APP && !NETFX_CORE
[Test]
public void TestToString_String_IFormatProvider_DefaultIsOk()
{
Assert.That(
default( Timestamp ).ToString( null, null ),
Is.EqualTo( "1970-01-01T00:00:00.000000000Z" )
);
}
[Test]
public void TestToString_String_IFormatProvider_EmptyFormat()
{
Assert.Throws<ArgumentException>(
() => default( Timestamp ).ToString( String.Empty, null )
);
}
[Test]
public void TestToString_String_IFormatProvider_UnsupportedFormat()
{
Assert.Throws<ArgumentException>(
() => default( Timestamp ).ToString( "G", null )
);
}
#if !WINDOWS_PHONE && !WINDOWS_PHONE_APP && !NETFX_CORE
[Test]
public void TestToString_AsOFormatAndNullIFormatProvider()
{
var originalCurrentCulture = CultureInfo.CurrentCulture;
try
{
#if ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
CultureInfo.CurrentCulture =
#else // ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
Thread.CurrentThread.CurrentCulture =
#endif // ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
new LegacyJapaneseCultureInfo();
if ( !( CultureInfo.CurrentCulture is LegacyJapaneseCultureInfo ) || CultureInfo.CurrentCulture.NumberFormat.NegativeSign != "\uFF0D" )
{
Assert.Ignore( "This platform does not support custom culture correctly." );
}
Assert.That(
new Timestamp(
-62193657600,
0
).ToString(),
Is.EqualTo( "\uFF0D0001-03-01T00:00:00.000000000Z" )
);
}
finally
{
#if ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
CultureInfo.CurrentCulture =
#else // ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
Thread.CurrentThread.CurrentCulture =
#endif // ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
originalCurrentCulture;
}
}
#endif // !WINDOWS_PHONE && !WINDOWS_PHONE_APP && !NETFX_CORE
[Test]
public void TestToString_IFormatProvider_AsOFormat()
{
Assert.That(
new Timestamp(
-62193657600,
0
).ToString( new LegacyJapaneseCultureInfo() ),
Is.EqualTo( "\uFF0D0001-03-01T00:00:00.000000000Z" )
);
}
#if !WINDOWS_PHONE && !WINDOWS_PHONE_APP && !NETFX_CORE
[Test]
public void TestToString_String_AsNullIFormatProvider()
{
var originalCurrentCulture = CultureInfo.CurrentCulture;
try
{
#if ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
CultureInfo.CurrentCulture =
#else // ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
Thread.CurrentThread.CurrentCulture =
#endif // ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
new LegacyJapaneseCultureInfo();
if ( !( CultureInfo.CurrentCulture is LegacyJapaneseCultureInfo ) || CultureInfo.CurrentCulture.NumberFormat.NegativeSign != "\uFF0D" )
{
Assert.Ignore( "This platform does not support custom culture correctly." );
}
Assert.That(
new Timestamp(
-62193657600,
0
).ToString( "s" ),
Is.EqualTo( "\uFF0D0001-03-01T00:00:00Z" )
);
}
finally
{
#if ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
CultureInfo.CurrentCulture =
#else // ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
Thread.CurrentThread.CurrentCulture =
#endif // ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
originalCurrentCulture;
}
}
#endif // !WINDOWS_PHONE && !WINDOWS_PHONE_APP && !NETFX_CORE
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections.Generic;
using Avalonia.Collections;
namespace Avalonia.Controls
{
/// <summary>
/// Holds a collection of style classes for an <see cref="IStyledElement"/>.
/// </summary>
/// <remarks>
/// Similar to CSS, each control may have any number of styling classes applied.
/// </remarks>
public class Classes : AvaloniaList<string>, IPseudoClasses
{
/// <summary>
/// Initializes a new instance of the <see cref="Classes"/> class.
/// </summary>
public Classes()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Classes"/> class.
/// </summary>
/// <param name="items">The initial items.</param>
public Classes(IEnumerable<string> items)
: base(items)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Classes"/> class.
/// </summary>
/// <param name="items">The initial items.</param>
public Classes(params string[] items)
: base(items)
{
}
/// <summary>
/// Parses a classes string.
/// </summary>
/// <param name="s">The string.</param>
/// <returns>The <see cref="Classes"/>.</returns>
public static Classes Parse(string s) => new Classes(s.Split(' '));
/// <summary>
/// Adds a style class to the collection.
/// </summary>
/// <param name="name">The class name.</param>
/// <remarks>
/// Only standard classes may be added via this method. To add pseudoclasses (classes
/// beginning with a ':' character) use the protected <see cref="StyledElement.PseudoClasses"/>
/// property.
/// </remarks>
public override void Add(string name)
{
ThrowIfPseudoclass(name, "added");
if (!Contains(name))
{
base.Add(name);
}
}
/// <summary>
/// Adds a style classes to the collection.
/// </summary>
/// <param name="names">The class names.</param>
/// <remarks>
/// Only standard classes may be added via this method. To add pseudoclasses (classes
/// beginning with a ':' character) use the protected <see cref="StyledElement.PseudoClasses"/>
/// property.
/// </remarks>
public override void AddRange(IEnumerable<string> names)
{
var c = new List<string>();
foreach (var name in names)
{
ThrowIfPseudoclass(name, "added");
if (!Contains(name))
{
c.Add(name);
}
}
base.AddRange(c);
}
/// <summary>
/// Remvoes all non-pseudoclasses from the collection.
/// </summary>
public override void Clear()
{
for (var i = Count - 1; i >= 0; --i)
{
if (!this[i].StartsWith(":"))
{
RemoveAt(i);
}
}
}
/// <summary>
/// Inserts a style class into the collection.
/// </summary>
/// <param name="index">The index to insert the class at.</param>
/// <param name="name">The class name.</param>
/// <remarks>
/// Only standard classes may be added via this method. To add pseudoclasses (classes
/// beginning with a ':' character) use the protected <see cref="StyledElement.PseudoClasses"/>
/// property.
/// </remarks>
public override void Insert(int index, string name)
{
ThrowIfPseudoclass(name, "added");
if (!Contains(name))
{
base.Insert(index, name);
}
}
/// <summary>
/// Inserts style classes into the collection.
/// </summary>
/// <param name="index">The index to insert the class at.</param>
/// <param name="names">The class names.</param>
/// <remarks>
/// Only standard classes may be added via this method. To add pseudoclasses (classes
/// beginning with a ':' character) use the protected <see cref="StyledElement.PseudoClasses"/>
/// property.
/// </remarks>
public override void InsertRange(int index, IEnumerable<string> names)
{
var c = new List<string>();
foreach (var name in names)
{
ThrowIfPseudoclass(name, "added");
if (!Contains(name))
{
c.Add(name);
}
}
base.InsertRange(index, c);
}
/// <summary>
/// Removes a style class from the collection.
/// </summary>
/// <param name="name">The class name.</param>
/// <remarks>
/// Only standard classes may be removed via this method. To remove pseudoclasses (classes
/// beginning with a ':' character) use the protected <see cref="StyledElement.PseudoClasses"/>
/// property.
/// </remarks>
public override bool Remove(string name)
{
ThrowIfPseudoclass(name, "removed");
return base.Remove(name);
}
/// <summary>
/// Removes style classes from the collection.
/// </summary>
/// <param name="names">The class name.</param>
/// <remarks>
/// Only standard classes may be removed via this method. To remove pseudoclasses (classes
/// beginning with a ':' character) use the protected <see cref="StyledElement.PseudoClasses"/>
/// property.
/// </remarks>
public override void RemoveAll(IEnumerable<string> names)
{
var c = new List<string>();
foreach (var name in names)
{
ThrowIfPseudoclass(name, "removed");
if (Contains(name))
{
c.Add(name);
}
}
base.RemoveAll(c);
}
/// <summary>
/// Removes a style class from the collection.
/// </summary>
/// <param name="index">The index of the class in the collection.</param>
/// <remarks>
/// Only standard classes may be removed via this method. To remove pseudoclasses (classes
/// beginning with a ':' character) use the protected <see cref="StyledElement.PseudoClasses"/>
/// property.
/// </remarks>
public override void RemoveAt(int index)
{
var name = this[index];
ThrowIfPseudoclass(name, "removed");
base.RemoveAt(index);
}
/// <summary>
/// Removes style classes from the collection.
/// </summary>
/// <param name="index">The first index to remove.</param>
/// <param name="count">The number of items to remove.</param>
public override void RemoveRange(int index, int count)
{
base.RemoveRange(index, count);
}
/// <summary>
/// Removes all non-pseudoclasses in the collection and adds a new set.
/// </summary>
/// <param name="source">The new contents of the collection.</param>
public void Replace(IList<string> source)
{
var toRemove = new List<string>();
foreach (var name in source)
{
ThrowIfPseudoclass(name, "added");
}
foreach (var name in this)
{
if (!name.StartsWith(":"))
{
toRemove.Add(name);
}
}
base.RemoveAll(toRemove);
base.AddRange(source);
}
/// <inheritdoc/>
void IPseudoClasses.Add(string name)
{
if (!Contains(name))
{
base.Add(name);
}
}
/// <inheritdoc/>
bool IPseudoClasses.Remove(string name)
{
return base.Remove(name);
}
private void ThrowIfPseudoclass(string name, string operation)
{
if (name.StartsWith(":"))
{
throw new ArgumentException(
$"The pseudoclass '{name}' may only be {operation} by the control itself.");
}
}
}
}
| |
using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Xml;
using Rainbow.Framework;
using Rainbow.Framework.Settings;
using Rainbow.Framework.Content.Data;
using Rainbow.Framework.Data;
using Rainbow.Framework.DataTypes;
using Rainbow.Framework.Web.UI.WebControls;
using Path=System.IO.Path;
namespace Rainbow.Content.Web.Modules
{
/// <summary>
/// Books module
/// Load books from amazon
/// </summary>
public partial class AmazonBooks : PortalModuleControl
{
/// <summary>
/// Is module searchable
/// </summary>
public override bool Searchable
{
get { return false; }
}
/// <summary>
/// Books consturctor
/// </summary>
public AmazonBooks()
{
SettingItem Columns = new SettingItem(new IntegerDataType());
Columns.Required = true;
Columns.Value = "3";
Columns.MinValue = 1;
Columns.MaxValue = 10;
_baseSettings.Add("Columns", Columns);
SettingItem Width = new SettingItem(new IntegerDataType());
Width.Value = "110";
Width.MinValue = 50;
Width.MaxValue = 250;
_baseSettings.Add("Width", Width);
SettingItem PromoCode = new SettingItem(new StringDataType());
//jes1111
//if (ConfigurationSettings.AppSettings["AmazonPromoCode"] != null && ConfigurationSettings.AppSettings["AmazonPromoCode"].Length != 0)
// PromoCode.Value = ConfigurationSettings.AppSettings["AmazonPromoCode"].ToString();
//else
// PromoCode.Value = string.Empty;
PromoCode.Value = Config.AmazonPromoCode;
_baseSettings.Add("Promotion Code", PromoCode);
SettingItem ShowDetails = new SettingItem(new StringDataType());
ShowDetails.Value = "ProductName,OurPrice,Author";
_baseSettings.Add("Show Details", ShowDetails);
SettingItem AmazonDevToken = new SettingItem(new StringDataType());
//jes1111
//if (ConfigurationSettings.AppSettings["AmazonDevToken"] != null && ConfigurationSettings.AppSettings["AmazonDevToken"].Length != 0)
// AmazonDevToken.Value = ConfigurationSettings.AppSettings["AmazonDevToken"].ToString();
//else
// AmazonDevToken.Value = string.Empty;
AmazonDevToken.Value = Config.AmazonDevToken;
_baseSettings.Add("Amazon Dev Token", AmazonDevToken);
//Choose your editor here
SupportsWorkflow = false;
}
private void Page_Load(object sender, EventArgs e)
{
BooksDB books = new BooksDB();
myDataList.DataSource = books.Getrb_BookList(ModuleID);
myDataList.DataBind();
myDataList.RepeatColumns = Int32.Parse(Settings["Columns"].ToString());
}
/// <summary>
/// GetTdWidthPercentage
/// </summary>
/// <param name="Columns"></param>
/// <returns></returns>
public string GetTdWidthPercentage(string Columns)
{
//Trace.Write("AmazonFullCaption","GetTdWidthPercentage()");
int tdWidthPercent;
try
{
tdWidthPercent = 100/Int32.Parse(Columns);
return tdWidthPercent + "%";
}
catch (Exception)
{
return string.Empty;
}
}
/// <summary>
/// GetWebServiceDetails
/// </summary>
/// <param name="AmazonDevToken"></param>
/// <param name="isbn"></param>
/// <param name="ShowDetails"></param>
/// <param name="PromoCode"></param>
/// <returns></returns>
public string GetWebServiceDetails(string AmazonDevToken, string isbn, string ShowDetails, string PromoCode)
{
string BookDetails = string.Empty;
if (ShowDetails.Length > 0)
{
string strAmazonURL = "http://xml.amazon.com/onca/xml2?" +
"t=" + PromoCode +
"&dev-t=" + AmazonDevToken +
"&type=heavy&AsinSearch=" + isbn +
"&f=xml";
XmlTextReader xmlTr1;
xmlTr1 = XmlReaderCached_v2(strAmazonURL);
BookDetails = "<br>";
ShowDetails = "," + ShowDetails + ",";
try
{
//Trace.Write("AmazonFullCaption","GetTdWidthPercentage.If.Try()");
while (xmlTr1.Read())
{
//Trace.Write("AmazonFullCaption","GetTdWidthPercentage.If.Try.While()");
if (xmlTr1.NodeType.ToString() == "Element")
{
//Trace.Write("AmazonFullCaption","GetTdWidthPercentage.If.Try.While.If()");
string strName = xmlTr1.Name;
if ((ShowDetails.IndexOf("," + strName + ",") > -1) || (ShowDetails.ToLower() == ",all,"))
{
//Trace.Write("AmazonFullCaption","GetTdWidthPercentage.If.Try.While.If.If()");
xmlTr1.Read();
BookDetails += strName + " <b>" + xmlTr1.Value + "</b><br>";
} //END IF
} //END IF
} //END WHILE
}
catch
{
//Trace.Write("AmazonFullCaption","GetTdWidthPercentage.If.Try.Catch()");
}
} //END IF
//Trace.Write("AmazonFullCaption","GetWebServiceDetails.End()");
return BookDetails;
} //END FUNCTION
/// <summary>
/// ConvertStr2ByteArray
/// </summary>
/// <param name="strInput"></param>
/// <returns></returns>
public byte[] ConvertStr2ByteArray(string strInput)
{
//Trace.Write("AmazonFullCaption","ConvertStr2ByteArray.Begin()");
int intCounter = 0;
char[] arrChar;
arrChar = strInput.ToCharArray();
byte[] arrByte;
arrByte = new byte[arrChar.Length - 1];
for (intCounter = 0; intCounter <= arrByte.Length - 1; intCounter++)
{
arrByte[intCounter] = Convert.ToByte(arrChar[intCounter]);
}
//Trace.Write("AmazonFullCaption","ConvertStr2ByteArray.End()");
return arrByte;
}
private string MD5checksum(string strParm1)
{
//Trace.Write("AmazonFullCaption","MD5checksum.Begin()");
byte[] arrHashInput;
byte[] arrHashOutput;
MD5CryptoServiceProvider objMD5 = new MD5CryptoServiceProvider();
arrHashInput = ConvertStr2ByteArray(strParm1);
arrHashOutput = objMD5.ComputeHash(arrHashInput);
//Trace.Write("AmazonFullCaption","MD5checksum.End()");
return BitConverter.ToString(arrHashOutput);
}
// private XmlTextReader XmlReaderCached_v1(string strXML ){
//
// XmlTextReader xmlTrCached = new XmlTextReader(strXML);
// //Trace.Write("AmazonFullCaption","XmlReaderCached_v1()");
// return(xmlTrCached);
// }
private XmlTextReader XmlReaderCached_v2(string strXML)
{
//Trace.Write("AmazonFullCaption","XmlReaderCached_v2.Begin()");
XmlTextReader xmlTrCached;
string strChksum = MD5checksum(strXML);
string strInCache;
if (Cache[strChksum] == null)
{
strInCache = HttpGet(strXML);
if (strInCache != "error")
Cache.Insert(strChksum, strInCache, null, DateTime.Now.AddMinutes(60), System.Web.Caching.Cache.NoSlidingExpiration);
}
else
strInCache = Cache[strChksum].ToString();
StringReader strReader1 = new StringReader(strInCache);
xmlTrCached = new XmlTextReader(strReader1);
//Trace.Write("AmazonFullCaption","XmlReaderCached_v2.End()");
return (xmlTrCached);
}
private string HttpGet(string strURL)
{
//Response.Write("HttpGet(" + strURL + ")<BR>");
//Trace.Write("AmazonFullCaption","HttpGet.Begin()");
StreamReader sr1 = null;
string strTemp;
WebResponse webResponse1;
WebRequest webRequest1;
try
{
//Trace.Write("AmazonFullCaption","HttpGet.Try()");
webRequest1 = WebRequest.Create(strURL);
webResponse1 = webRequest1.GetResponse();
sr1 = new StreamReader(webResponse1.GetResponseStream());
strTemp = sr1.ReadToEnd();
}
catch
{
strTemp = "error";
//Trace.Write("AmazonFullCaption","HttpGet.Catch()");
}
finally
{
if (sr1 != null)
sr1.Close();
//Trace.Write("AmazonFullCaption","HttpGet.Finally()");
}
//Trace.Write("AmazonFullCaption","HttpGet.End()");
return (strTemp);
}
/// <summary>
/// General Module DEf GUID
/// </summary>
public override Guid GuidID
{
get { return new Guid("{5A2E8E9C-B9C7-439a-BFF9-54CA78762818}"); }
}
/// <summary>
///
/// </summary>
/// <param name="stateSaver"></param>
public override void Install(IDictionary stateSaver)
{
string currentScriptName = Path.Combine(Server.MapPath(TemplateSourceDirectory), "install.sql");
ArrayList errors = DBHelper.ExecuteScript(currentScriptName, true);
if (errors.Count > 0)
{
throw new Exception("Error occurred:" + errors[0].ToString());
}
}
/// <summary>
///
/// </summary>
/// <param name="stateSaver"></param>
public override void Uninstall(IDictionary stateSaver)
{
string currentScriptName = Path.Combine(Server.MapPath(TemplateSourceDirectory), "uninstall.sql");
ArrayList errors = DBHelper.ExecuteScript(currentScriptName, true);
if (errors.Count > 0)
{
throw new Exception("Error occurred:" + errors[0].ToString());
}
}
#region Web Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
protected override void OnInit(EventArgs e)
{
InitializeComponent();
// Set here title properties
// Add support for the edit page
AddUrl = "~/DesktopModules/CommunityModules/AmazonFull/BooksEdit.aspx";
base.OnInit(e);
}
private void InitializeComponent()
{
this.Load += new EventHandler(this.Page_Load);
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="EntityCommandDefinition.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//------------------------------------------------------------------------------
namespace System.Data.EntityClient {
using System.Collections.Generic;
using System.Data.Common;
using System.Data.Common.CommandTrees;
using System.Data.Common.Utils;
using System.Data.Mapping;
using System.Data.Metadata.Edm;
using System.Data.Query.InternalTrees;
using System.Data.Query.PlanCompiler;
using System.Data.Query.ResultAssembly;
using System.Diagnostics;
using System.Linq;
using System.Text;
/// <summary>
/// An aggregate Command Definition used by the EntityClient layers. This is an aggregator
/// object that represent information from multiple underlying provider commands.
/// </summary>
sealed internal class EntityCommandDefinition : DbCommandDefinition {
#region internal state
/// <summary>
/// nested store command definitions
/// </summary>
private readonly List<DbCommandDefinition> _mappedCommandDefinitions;
/// <summary>
/// generates column map for the store result reader
/// </summary>
private readonly IColumnMapGenerator[] _columnMapGenerators;
/// <summary>
/// list of the parameters that the resulting command should have
/// </summary>
private readonly System.Collections.ObjectModel.ReadOnlyCollection<EntityParameter> _parameters;
/// <summary>
/// Set of entity sets exposed in the command.
/// </summary>
private readonly Set<EntitySet> _entitySets;
#endregion
#region constructors
/// <summary>
/// don't let this be constructed publicly;
/// </summary>
/// <exception cref="EntityCommandCompilationException">Cannot prepare the command definition for execution; consult the InnerException for more information.</exception>
/// <exception cref="NotSupportedException">The ADO.NET Data Provider you are using does not support CommandTrees.</exception>
internal EntityCommandDefinition(DbProviderFactory storeProviderFactory, DbCommandTree commandTree) {
EntityUtil.CheckArgumentNull(storeProviderFactory, "storeProviderFactory");
EntityUtil.CheckArgumentNull(commandTree, "commandTree");
DbProviderServices storeProviderServices = DbProviderServices.GetProviderServices(storeProviderFactory);
try {
if (DbCommandTreeKind.Query == commandTree.CommandTreeKind) {
// Next compile the plan for the command tree
List<ProviderCommandInfo> mappedCommandList = new List<ProviderCommandInfo>();
ColumnMap columnMap;
int columnCount;
PlanCompiler.Compile(commandTree, out mappedCommandList, out columnMap, out columnCount, out _entitySets);
_columnMapGenerators = new IColumnMapGenerator[] {new ConstantColumnMapGenerator(columnMap, columnCount)};
// Note: we presume that the first item in the ProviderCommandInfo is the root node;
Debug.Assert(mappedCommandList.Count > 0, "empty providerCommandInfo collection and no exception?"); // this shouldn't ever happen.
// Then, generate the store commands from the resulting command tree(s)
_mappedCommandDefinitions = new List<DbCommandDefinition>(mappedCommandList.Count);
foreach (ProviderCommandInfo providerCommandInfo in mappedCommandList) {
DbCommandDefinition providerCommandDefinition = storeProviderServices.CreateCommandDefinition(providerCommandInfo.CommandTree);
if (null == providerCommandDefinition) {
throw EntityUtil.ProviderIncompatible(System.Data.Entity.Strings.ProviderReturnedNullForCreateCommandDefinition);
}
_mappedCommandDefinitions.Add(providerCommandDefinition);
}
}
else {
Debug.Assert(DbCommandTreeKind.Function == commandTree.CommandTreeKind, "only query and function command trees are supported");
DbFunctionCommandTree entityCommandTree = (DbFunctionCommandTree)commandTree;
// Retrieve mapping and metadata information for the function import.
FunctionImportMappingNonComposable mapping = GetTargetFunctionMapping(entityCommandTree);
IList<FunctionParameter> returnParameters = entityCommandTree.EdmFunction.ReturnParameters;
int resultSetCount = returnParameters.Count > 1 ? returnParameters.Count : 1;
_columnMapGenerators = new IColumnMapGenerator[resultSetCount];
TypeUsage storeResultType = DetermineStoreResultType(entityCommandTree.MetadataWorkspace, mapping, 0, out _columnMapGenerators[0]);
for (int i = 1; i < resultSetCount; i++)
{
DetermineStoreResultType(entityCommandTree.MetadataWorkspace, mapping, i, out _columnMapGenerators[i]);
}
// Copy over parameters (this happens through a more indirect route in the plan compiler, but
// it happens nonetheless)
List<KeyValuePair<string, TypeUsage>> providerParameters = new List<KeyValuePair<string, TypeUsage>>();
foreach (KeyValuePair<string, TypeUsage> parameter in entityCommandTree.Parameters)
{
providerParameters.Add(parameter);
}
// Construct store command tree usage.
DbFunctionCommandTree providerCommandTree = new DbFunctionCommandTree(entityCommandTree.MetadataWorkspace, DataSpace.SSpace,
mapping.TargetFunction, storeResultType, providerParameters);
DbCommandDefinition storeCommandDefinition = storeProviderServices.CreateCommandDefinition(providerCommandTree);
_mappedCommandDefinitions = new List<DbCommandDefinition>(1) { storeCommandDefinition };
EntitySet firstResultEntitySet = mapping.FunctionImport.EntitySets.FirstOrDefault();
if (firstResultEntitySet != null)
{
_entitySets = new Set<EntitySet>();
_entitySets.Add(mapping.FunctionImport.EntitySets.FirstOrDefault());
_entitySets.MakeReadOnly();
}
}
// Finally, build a list of the parameters that the resulting command should have;
List<EntityParameter> parameterList = new List<EntityParameter>();
foreach (KeyValuePair<string, TypeUsage> queryParameter in commandTree.Parameters) {
EntityParameter parameter = CreateEntityParameterFromQueryParameter(queryParameter);
parameterList.Add(parameter);
}
_parameters = new System.Collections.ObjectModel.ReadOnlyCollection<EntityParameter>(parameterList);
}
catch (EntityCommandCompilationException) {
// No need to re-wrap EntityCommandCompilationException
throw;
}
catch (Exception e) {
// we should not be wrapping all exceptions
if (EntityUtil.IsCatchableExceptionType(e)) {
// we don't wan't folks to have to know all the various types of exceptions that can
// occur, so we just rethrow a CommandDefinitionException and make whatever we caught
// the inner exception of it.
throw EntityUtil.CommandCompilation(System.Data.Entity.Strings.EntityClient_CommandDefinitionPreparationFailed, e);
}
throw;
}
}
/// <summary>
/// Determines the store type for a function import.
/// </summary>
private TypeUsage DetermineStoreResultType(MetadataWorkspace workspace, FunctionImportMappingNonComposable mapping, int resultSetIndex, out IColumnMapGenerator columnMapGenerator) {
// Determine column maps and infer result types for the mapped function. There are four varieties:
// Collection(Entity)
// Collection(PrimitiveType)
// Collection(ComplexType)
// No result type
TypeUsage storeResultType;
{
StructuralType baseStructuralType;
EdmFunction functionImport = mapping.FunctionImport;
// Collection(Entity) or Collection(ComplexType)
if (MetadataHelper.TryGetFunctionImportReturnType<StructuralType>(functionImport, resultSetIndex, out baseStructuralType))
{
ValidateEdmResultType(baseStructuralType, functionImport);
//Note: Defensive check for historic reasons, we expect functionImport.EntitySets.Count > resultSetIndex
EntitySet entitySet = functionImport.EntitySets.Count > resultSetIndex ? functionImport.EntitySets[resultSetIndex] : null;
columnMapGenerator = new FunctionColumnMapGenerator(mapping, resultSetIndex, entitySet, baseStructuralType);
// We don't actually know the return type for the stored procedure, but we can infer
// one based on the mapping (i.e.: a column for every property of the mapped types
// and for all discriminator columns)
storeResultType = mapping.GetExpectedTargetResultType(workspace, resultSetIndex);
}
// Collection(PrimitiveType)
else
{
FunctionParameter returnParameter = MetadataHelper.GetReturnParameter(functionImport, resultSetIndex);
if (returnParameter != null && returnParameter.TypeUsage != null)
{
// Get metadata description of the return type
storeResultType = returnParameter.TypeUsage;
Debug.Assert(storeResultType.EdmType.BuiltInTypeKind == BuiltInTypeKind.CollectionType, "FunctionImport currently supports only collection result type");
TypeUsage elementType = ((CollectionType)storeResultType.EdmType).TypeUsage;
Debug.Assert(Helper.IsScalarType(elementType.EdmType)
, "FunctionImport supports only Collection(Entity), Collection(Enum) and Collection(Primitive)");
// Build collection column map where the first column of the store result is assumed
// to contain the primitive type values.
ScalarColumnMap scalarColumnMap = new ScalarColumnMap(elementType, string.Empty, 0, 0);
SimpleCollectionColumnMap collectionColumnMap = new SimpleCollectionColumnMap(storeResultType,
string.Empty, scalarColumnMap, null, null);
columnMapGenerator = new ConstantColumnMapGenerator(collectionColumnMap, 1);
}
// No result type
else
{
storeResultType = null;
columnMapGenerator = new ConstantColumnMapGenerator(null, 0);
}
}
}
return storeResultType;
}
/// <summary>
/// Handles the following negative scenarios
/// Nested ComplexType Property in ComplexType
/// </summary>
/// <param name="resultType"></param>
private void ValidateEdmResultType(EdmType resultType, EdmFunction functionImport)
{
if (Helper.IsComplexType(resultType))
{
ComplexType complexType = resultType as ComplexType;
Debug.Assert(null != complexType, "we should have a complex type here");
foreach (var property in complexType.Properties)
{
if (property.TypeUsage.EdmType.BuiltInTypeKind == BuiltInTypeKind.ComplexType)
{
throw new NotSupportedException(System.Data.Entity.Strings.ComplexTypeAsReturnTypeAndNestedComplexProperty(property.Name, complexType.Name, functionImport.FullName));
}
}
}
}
/// <summary>
/// Retrieves mapping for the given C-Space functionCommandTree
/// </summary>
private static FunctionImportMappingNonComposable GetTargetFunctionMapping(DbFunctionCommandTree functionCommandTree)
{
Debug.Assert(functionCommandTree.DataSpace == DataSpace.CSpace, "map from CSpace->SSpace function");
Debug.Assert(functionCommandTree != null, "null functionCommandTree");
Debug.Assert(!functionCommandTree.EdmFunction.IsComposableAttribute, "functionCommandTree.EdmFunction must be non-composable.");
// Find mapped store function.
FunctionImportMapping targetFunctionMapping;
if (!functionCommandTree.MetadataWorkspace.TryGetFunctionImportMapping(functionCommandTree.EdmFunction, out targetFunctionMapping))
{
throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.EntityClient_UnmappedFunctionImport(functionCommandTree.EdmFunction.FullName));
}
return (FunctionImportMappingNonComposable)targetFunctionMapping;
}
#endregion
#region public API
/// <summary>
/// Create a DbCommand object from the definition, that can be executed
/// </summary>
/// <returns></returns>
public override DbCommand CreateCommand() {
return new EntityCommand(this);
}
#endregion
#region internal methods
/// <summary>
/// Get a list of commands to be executed by the provider
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal IEnumerable<string> MappedCommands {
get {
// Build up the list of command texts, if we haven't done so yet
List<string> mappedCommandTexts = new List<string>();
foreach (DbCommandDefinition commandDefinition in _mappedCommandDefinitions) {
DbCommand mappedCommand = commandDefinition.CreateCommand();
mappedCommandTexts.Add(mappedCommand.CommandText);
}
return mappedCommandTexts;
}
}
/// <summary>
/// Creates ColumnMap for result assembly using the given reader.
/// </summary>
internal ColumnMap CreateColumnMap(DbDataReader storeDataReader)
{
return CreateColumnMap(storeDataReader, 0);
}
/// <summary>
/// Creates ColumnMap for result assembly using the given reader's resultSetIndexth result set.
/// </summary>
internal ColumnMap CreateColumnMap(DbDataReader storeDataReader, int resultSetIndex)
{
return _columnMapGenerators[resultSetIndex].CreateColumnMap(storeDataReader);
}
/// <summary>
/// Property to expose the known parameters for the query, so the Command objects
/// constructor can poplulate it's parameter collection from.
/// </summary>
internal IEnumerable<EntityParameter> Parameters {
get {
return _parameters;
}
}
/// <summary>
/// Set of entity sets exposed in the command.
/// </summary>
internal Set<EntitySet> EntitySets {
get {
return _entitySets;
}
}
/// <summary>
/// Constructs a EntityParameter from a CQT parameter.
/// </summary>
/// <param name="queryParameter"></param>
/// <returns></returns>
private static EntityParameter CreateEntityParameterFromQueryParameter(KeyValuePair<string, TypeUsage> queryParameter) {
// We really can't have a parameter here that isn't a scalar type...
Debug.Assert(TypeSemantics.IsScalarType(queryParameter.Value), "Non-scalar type used as query parameter type");
EntityParameter result = new EntityParameter();
result.ParameterName = queryParameter.Key;
EntityCommandDefinition.PopulateParameterFromTypeUsage(result, queryParameter.Value, isOutParam: false);
return result;
}
internal static void PopulateParameterFromTypeUsage(EntityParameter parameter, TypeUsage type, bool isOutParam)
{
// type can be null here if the type provided by the user is not a known model type
if (type != null)
{
PrimitiveTypeKind primitiveTypeKind;
if (Helper.IsEnumType(type.EdmType))
{
type = TypeUsage.Create(Helper.GetUnderlyingEdmTypeForEnumType(type.EdmType));
}
else if (Helper.IsSpatialType(type, out primitiveTypeKind))
{
parameter.EdmType = EdmProviderManifest.Instance.GetPrimitiveType(primitiveTypeKind);
}
}
DbCommandDefinition.PopulateParameterFromTypeUsage(parameter, type, isOutParam);
}
/// <summary>
/// Internal execute method -- copies command information from the map command
/// to the command objects, executes them, and builds the result assembly
/// structures needed to return the data reader
/// </summary>
/// <param name="entityCommand"></param>
/// <param name="behavior"></param>
/// <returns></returns>
/// <exception cref="InvalidOperationException">behavior must specify CommandBehavior.SequentialAccess</exception>
/// <exception cref="InvalidOperationException">input parameters in the entityCommand.Parameters collection must have non-null values.</exception>
internal DbDataReader Execute(EntityCommand entityCommand, CommandBehavior behavior) {
if (CommandBehavior.SequentialAccess != (behavior & CommandBehavior.SequentialAccess)) {
throw EntityUtil.MustUseSequentialAccess();
}
DbDataReader storeDataReader = ExecuteStoreCommands(entityCommand, behavior);
DbDataReader result = null;
// If we actually executed something, then go ahead and construct a bridge
// data reader for it.
if (null != storeDataReader) {
try {
ColumnMap columnMap = this.CreateColumnMap(storeDataReader, 0);
if (null == columnMap) {
// For a query with no result type (and therefore no column map), consume the reader.
// When the user requests Metadata for this reader, we return nothing.
CommandHelper.ConsumeReader(storeDataReader);
result = storeDataReader;
}
else {
result = BridgeDataReader.Create(storeDataReader, columnMap, entityCommand.Connection.GetMetadataWorkspace(), GetNextResultColumnMaps(storeDataReader));
}
}
catch {
// dispose of store reader if there is an error creating the BridgeDataReader
storeDataReader.Dispose();
throw;
}
}
return result;
}
private IEnumerable<ColumnMap> GetNextResultColumnMaps(DbDataReader storeDataReader)
{
for (int i = 1; i < _columnMapGenerators.Length; ++i)
{
yield return this.CreateColumnMap(storeDataReader, i);
}
}
/// <summary>
/// Execute the store commands, and return IteratorSources for each one
/// </summary>
/// <param name="entityCommand"></param>
/// <param name="behavior"></param>
internal DbDataReader ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
{
// SQLPT #120007433 is the work item to implement MARS support, which we
// need to do here, but since the PlanCompiler doesn't
// have it yet, neither do we...
if (1 != _mappedCommandDefinitions.Count) {
throw EntityUtil.NotSupported("MARS");
}
EntityTransaction entityTransaction = CommandHelper.GetEntityTransaction(entityCommand);
DbCommandDefinition definition = _mappedCommandDefinitions[0];
DbCommand storeProviderCommand = definition.CreateCommand();
CommandHelper.SetStoreProviderCommandState(entityCommand, entityTransaction, storeProviderCommand);
// Copy over the values from the map command to the store command; we
// assume that they were not renamed by either the plan compiler or SQL
// Generation.
//
// Note that this pretty much presumes that named parameters are supported
// by the store provider, but it might work if we don't reorder/reuse
// parameters.
//
// Note also that the store provider may choose to add parameters to thier
// command object for some things; we'll only copy over the values for
// parameters that we find in the EntityCommands parameters collection, so
// we won't damage anything the store provider did.
bool hasOutputParameters = false;
if (storeProviderCommand.Parameters != null) // SQLBUDT 519066
{
DbProviderServices storeProviderServices = DbProviderServices.GetProviderServices(entityCommand.Connection.StoreProviderFactory);
foreach (DbParameter storeParameter in storeProviderCommand.Parameters) {
// I could just use the string indexer, but then if I didn't find it the
// consumer would get some ParameterNotFound exeception message and that
// wouldn't be very meaningful. Instead, I use the IndexOf method and
// if I don't find it, it's not a big deal (The store provider must
// have added it).
int parameterOrdinal = entityCommand.Parameters.IndexOf(storeParameter.ParameterName);
if (-1 != parameterOrdinal) {
EntityParameter entityParameter = entityCommand.Parameters[parameterOrdinal];
SyncParameterProperties(entityParameter, storeParameter, storeProviderServices);
if (storeParameter.Direction != ParameterDirection.Input) {
hasOutputParameters = true;
}
}
}
}
// If the EntityCommand has output parameters, we must synchronize parameter values when
// the reader is closed. Tell the EntityCommand about the store command so that it knows
// where to pull those values from.
if (hasOutputParameters) {
entityCommand.SetStoreProviderCommand(storeProviderCommand);
}
DbDataReader reader = null;
try {
reader = storeProviderCommand.ExecuteReader(behavior & ~CommandBehavior.SequentialAccess);
}
catch (Exception e) {
// we should not be wrapping all exceptions
if (EntityUtil.IsCatchableExceptionType(e)) {
// we don't wan't folks to have to know all the various types of exceptions that can
// occur, so we just rethrow a CommandDefinitionException and make whatever we caught
// the inner exception of it.
throw EntityUtil.CommandExecution(System.Data.Entity.Strings.EntityClient_CommandDefinitionExecutionFailed, e);
}
throw;
}
return reader;
}
/// <summary>
/// Updates storeParameter size, precision and scale properties from user provided parameter properties.
/// </summary>
/// <param name="entityParameter"></param>
/// <param name="storeParameter"></param>
private static void SyncParameterProperties(EntityParameter entityParameter, DbParameter storeParameter, DbProviderServices storeProviderServices) {
IDbDataParameter dbDataParameter = (IDbDataParameter)storeParameter;
// DBType is not currently syncable; it's part of the cache key anyway; this is because we can't guarantee
// that the store provider will honor it -- (SqlClient doesn't...)
//if (entityParameter.IsDbTypeSpecified)
//{
// storeParameter.DbType = entityParameter.DbType;
//}
// Give the store provider the opportunity to set the value before any parameter state has been copied from
// the EntityParameter.
TypeUsage parameterTypeUsage = TypeHelpers.GetPrimitiveTypeUsageForScalar(entityParameter.GetTypeUsage());
storeProviderServices.SetParameterValue(storeParameter, parameterTypeUsage, entityParameter.Value);
// Override the store provider parameter state with any explicitly specified values from the EntityParameter.
if (entityParameter.IsDirectionSpecified)
{
storeParameter.Direction = entityParameter.Direction;
}
if (entityParameter.IsIsNullableSpecified)
{
storeParameter.IsNullable = entityParameter.IsNullable;
}
if (entityParameter.IsSizeSpecified)
{
storeParameter.Size = entityParameter.Size;
}
if (entityParameter.IsPrecisionSpecified)
{
dbDataParameter.Precision = entityParameter.Precision;
}
if (entityParameter.IsScaleSpecified)
{
dbDataParameter.Scale = entityParameter.Scale;
}
}
/// <summary>
/// Return the string used by EntityCommand and ObjectQuery<T> ToTraceString"/>
/// </summary>
/// <returns></returns>
internal string ToTraceString() {
if (_mappedCommandDefinitions != null) {
if (_mappedCommandDefinitions.Count == 1) {
// Gosh it sure would be nice if I could just get the inner commandText, but
// that would require more public surface area on DbCommandDefinition, or
// me to know about the inner object...
return _mappedCommandDefinitions[0].CreateCommand().CommandText;
}
else {
StringBuilder sb = new StringBuilder();
foreach (DbCommandDefinition commandDefinition in _mappedCommandDefinitions) {
DbCommand mappedCommand = commandDefinition.CreateCommand();
sb.Append(mappedCommand.CommandText);
}
return sb.ToString();
}
}
return string.Empty;
}
#endregion
#region nested types
/// <summary>
/// Generates a column map given a data reader.
/// </summary>
private interface IColumnMapGenerator {
/// <summary>
/// Given a data reader, returns column map.
/// </summary>
/// <param name="reader">Data reader.</param>
/// <returns>Column map.</returns>
ColumnMap CreateColumnMap(DbDataReader reader);
}
/// <summary>
/// IColumnMapGenerator wrapping a constant instance of a column map (invariant with respect
/// to the given DbDataReader)
/// </summary>
private sealed class ConstantColumnMapGenerator : IColumnMapGenerator {
private readonly ColumnMap _columnMap;
private readonly int _fieldsRequired;
internal ConstantColumnMapGenerator(ColumnMap columnMap, int fieldsRequired) {
_columnMap = columnMap;
_fieldsRequired = fieldsRequired;
}
ColumnMap IColumnMapGenerator.CreateColumnMap(DbDataReader reader) {
if (null != reader && reader.FieldCount < _fieldsRequired) {
throw EntityUtil.CommandExecution(System.Data.Entity.Strings.EntityClient_TooFewColumns);
}
return _columnMap;
}
}
/// <summary>
/// Generates column maps for a non-composable function mapping.
/// </summary>
private sealed class FunctionColumnMapGenerator : IColumnMapGenerator {
private readonly FunctionImportMappingNonComposable _mapping;
private readonly EntitySet _entitySet;
private readonly StructuralType _baseStructuralType;
private readonly int _resultSetIndex;
internal FunctionColumnMapGenerator(FunctionImportMappingNonComposable mapping, int resultSetIndex, EntitySet entitySet, StructuralType baseStructuralType)
{
_mapping = mapping;
_entitySet = entitySet;
_baseStructuralType = baseStructuralType;
_resultSetIndex = resultSetIndex;
}
ColumnMap IColumnMapGenerator.CreateColumnMap(DbDataReader reader)
{
return ColumnMapFactory.CreateFunctionImportStructuralTypeColumnMap(reader, _mapping, _resultSetIndex, _entitySet, _baseStructuralType);
}
}
#endregion
}
}
| |
// SF API version v50.0
// Custom fields included: False
// Relationship objects included: True
using System;
using NetCoreForce.Client.Models;
using NetCoreForce.Client.Attributes;
using Newtonsoft.Json;
namespace NetCoreForce.Models
{
///<summary>
/// Payment Authorization
///<para>SObject Name: PaymentAuthorization</para>
///<para>Custom Object: False</para>
///</summary>
public class SfPaymentAuthorization : SObject
{
[JsonIgnore]
public static string SObjectTypeName
{
get { return "PaymentAuthorization"; }
}
///<summary>
/// Payment Authorization ID
/// <para>Name: Id</para>
/// <para>SF Type: id</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "id")]
[Updateable(false), Createable(false)]
public string Id { get; set; }
///<summary>
/// Deleted
/// <para>Name: IsDeleted</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isDeleted")]
[Updateable(false), Createable(false)]
public bool? IsDeleted { get; set; }
///<summary>
/// Payment Authorization Number
/// <para>Name: PaymentAuthorizationNumber</para>
/// <para>SF Type: string</para>
/// <para>AutoNumber field</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "paymentAuthorizationNumber")]
[Updateable(false), Createable(false)]
public string PaymentAuthorizationNumber { get; set; }
///<summary>
/// Created Date
/// <para>Name: CreatedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? CreatedDate { get; set; }
///<summary>
/// Created By ID
/// <para>Name: CreatedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdById")]
[Updateable(false), Createable(false)]
public string CreatedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: CreatedBy</para>
///</summary>
[JsonProperty(PropertyName = "createdBy")]
[Updateable(false), Createable(false)]
public SfUser CreatedBy { get; set; }
///<summary>
/// Last Modified Date
/// <para>Name: LastModifiedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastModifiedDate { get; set; }
///<summary>
/// Last Modified By ID
/// <para>Name: LastModifiedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedById")]
[Updateable(false), Createable(false)]
public string LastModifiedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: LastModifiedBy</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedBy")]
[Updateable(false), Createable(false)]
public SfUser LastModifiedBy { get; set; }
///<summary>
/// System Modstamp
/// <para>Name: SystemModstamp</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "systemModstamp")]
[Updateable(false), Createable(false)]
public DateTimeOffset? SystemModstamp { get; set; }
///<summary>
/// Last Viewed Date
/// <para>Name: LastViewedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "lastViewedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastViewedDate { get; set; }
///<summary>
/// Last Referenced Date
/// <para>Name: LastReferencedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "lastReferencedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastReferencedDate { get; set; }
///<summary>
/// Payment Group ID
/// <para>Name: PaymentGroupId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "paymentGroupId")]
public string PaymentGroupId { get; set; }
///<summary>
/// ReferenceTo: PaymentGroup
/// <para>RelationshipName: PaymentGroup</para>
///</summary>
[JsonProperty(PropertyName = "paymentGroup")]
[Updateable(false), Createable(false)]
public SfPaymentGroup PaymentGroup { get; set; }
///<summary>
/// Account ID
/// <para>Name: AccountId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "accountId")]
public string AccountId { get; set; }
///<summary>
/// ReferenceTo: Account
/// <para>RelationshipName: Account</para>
///</summary>
[JsonProperty(PropertyName = "account")]
[Updateable(false), Createable(false)]
public SfAccount Account { get; set; }
///<summary>
/// Date
/// <para>Name: Date</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "date")]
public DateTimeOffset? Date { get; set; }
///<summary>
/// Gateway Date
/// <para>Name: GatewayDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "gatewayDate")]
public DateTimeOffset? GatewayDate { get; set; }
///<summary>
/// Expiration Date
/// <para>Name: ExpirationDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "expirationDate")]
public DateTimeOffset? ExpirationDate { get; set; }
///<summary>
/// Effective Date
/// <para>Name: EffectiveDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "effectiveDate")]
public DateTimeOffset? EffectiveDate { get; set; }
///<summary>
/// Amount
/// <para>Name: Amount</para>
/// <para>SF Type: currency</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "amount")]
public decimal? Amount { get; set; }
///<summary>
/// Status
/// <para>Name: Status</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "status")]
public string Status { get; set; }
///<summary>
/// Processing Mode
/// <para>Name: ProcessingMode</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "processingMode")]
[Updateable(false), Createable(true)]
public string ProcessingMode { get; set; }
///<summary>
/// Payment Method ID
/// <para>Name: PaymentMethodId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "paymentMethodId")]
public string PaymentMethodId { get; set; }
///<summary>
/// ReferenceTo: PaymentMethod
/// <para>RelationshipName: PaymentMethod</para>
///</summary>
[JsonProperty(PropertyName = "paymentMethod")]
[Updateable(false), Createable(false)]
public SfPaymentMethod PaymentMethod { get; set; }
///<summary>
/// Comments
/// <para>Name: Comments</para>
/// <para>SF Type: textarea</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "comments")]
public string Comments { get; set; }
///<summary>
/// Gateway Reference Details
/// <para>Name: GatewayRefDetails</para>
/// <para>SF Type: textarea</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "gatewayRefDetails")]
public string GatewayRefDetails { get; set; }
///<summary>
/// Gateway Reference Number
/// <para>Name: GatewayRefNumber</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "gatewayRefNumber")]
public string GatewayRefNumber { get; set; }
///<summary>
/// Gateway Result Code
/// <para>Name: GatewayResultCode</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "gatewayResultCode")]
public string GatewayResultCode { get; set; }
///<summary>
/// Salesforce Result Code
/// <para>Name: SfResultCode</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "sfResultCode")]
public string SfResultCode { get; set; }
///<summary>
/// Gateway Auth Code
/// <para>Name: GatewayAuthCode</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "gatewayAuthCode")]
public string GatewayAuthCode { get; set; }
///<summary>
/// Total Auth Reversal Amount
/// <para>Name: TotalAuthReversalAmount</para>
/// <para>SF Type: currency</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "totalAuthReversalAmount")]
[Updateable(false), Createable(false)]
public decimal? TotalAuthReversalAmount { get; set; }
///<summary>
/// Gateway Result Code Description
/// <para>Name: GatewayResultCodeDescription</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "gatewayResultCodeDescription")]
public string GatewayResultCodeDescription { get; set; }
///<summary>
/// Balance
/// <para>Name: Balance</para>
/// <para>SF Type: currency</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "balance")]
[Updateable(false), Createable(false)]
public decimal? Balance { get; set; }
///<summary>
/// Total Payment Capture Amount
/// <para>Name: TotalPaymentCaptureAmount</para>
/// <para>SF Type: currency</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "totalPaymentCaptureAmount")]
[Updateable(false), Createable(false)]
public decimal? TotalPaymentCaptureAmount { get; set; }
///<summary>
/// IP Address
/// <para>Name: IpAddress</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "ipAddress")]
public string IpAddress { get; set; }
///<summary>
/// MAC Address
/// <para>Name: MacAddress</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "macAddress")]
public string MacAddress { get; set; }
///<summary>
/// Phone
/// <para>Name: Phone</para>
/// <para>SF Type: phone</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "phone")]
public string Phone { get; set; }
///<summary>
/// Audit Email
/// <para>Name: Email</para>
/// <para>SF Type: email</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "email")]
public string Email { get; set; }
///<summary>
/// Payment Gateway ID
/// <para>Name: PaymentGatewayId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "paymentGatewayId")]
public string PaymentGatewayId { get; set; }
///<summary>
/// ReferenceTo: PaymentGateway
/// <para>RelationshipName: PaymentGateway</para>
///</summary>
[JsonProperty(PropertyName = "paymentGateway")]
[Updateable(false), Createable(false)]
public SfPaymentGateway PaymentGateway { get; 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.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.Security.Cryptography
{
public abstract partial class Aes : System.Security.Cryptography.SymmetricAlgorithm
{
protected Aes() { }
public static new System.Security.Cryptography.Aes Create() { throw null; }
public static new System.Security.Cryptography.Aes Create(string algorithmName) { throw null; }
}
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
public sealed partial class AesManaged : System.Security.Cryptography.Aes
{
public AesManaged() { }
public override int FeedbackSize { get { throw null; } set { } }
public override int BlockSize { get { throw null; } set { } }
public override byte[] IV { get { throw null; } set { } }
public override byte[] Key { get { throw null; } set { } }
public override int KeySize { get { throw null; } set { } }
public override System.Security.Cryptography.KeySizes[] LegalBlockSizes { get { throw null; } }
public override System.Security.Cryptography.KeySizes[] LegalKeySizes { get { throw null; } }
public override System.Security.Cryptography.CipherMode Mode { get { throw null; } set { } }
public override System.Security.Cryptography.PaddingMode Padding { get { throw null; } set { } }
public override System.Security.Cryptography.ICryptoTransform CreateDecryptor() { throw null; }
public override System.Security.Cryptography.ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV) { throw null; }
public override System.Security.Cryptography.ICryptoTransform CreateEncryptor() { throw null; }
public override System.Security.Cryptography.ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV) { throw null; }
protected override void Dispose(bool disposing) { }
public override void GenerateIV() { }
public override void GenerateKey() { }
}
public abstract partial class AsymmetricKeyExchangeDeformatter
{
protected AsymmetricKeyExchangeDeformatter() { }
public abstract string Parameters { get; set; }
public abstract byte[] DecryptKeyExchange(byte[] rgb);
public abstract void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key);
}
public abstract partial class AsymmetricKeyExchangeFormatter
{
protected AsymmetricKeyExchangeFormatter() { }
public abstract string Parameters { get; }
public abstract byte[] CreateKeyExchange(byte[] data);
public abstract byte[] CreateKeyExchange(byte[] data, System.Type symAlgType);
public abstract void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key);
}
public abstract partial class AsymmetricSignatureDeformatter
{
protected AsymmetricSignatureDeformatter() { }
public abstract void SetHashAlgorithm(string strName);
public abstract void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key);
public abstract bool VerifySignature(byte[] rgbHash, byte[] rgbSignature);
public virtual bool VerifySignature(System.Security.Cryptography.HashAlgorithm hash, byte[] rgbSignature) { throw null; }
}
public abstract partial class AsymmetricSignatureFormatter
{
protected AsymmetricSignatureFormatter() { }
public abstract byte[] CreateSignature(byte[] rgbHash);
public virtual byte[] CreateSignature(System.Security.Cryptography.HashAlgorithm hash) { throw null; }
public abstract void SetHashAlgorithm(string strName);
public abstract void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key);
}
public abstract partial class DeriveBytes : System.IDisposable
{
protected DeriveBytes() { }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public abstract byte[] GetBytes(int cb);
public abstract void Reset();
}
public partial class CryptoConfig
{
public CryptoConfig() { }
public static bool AllowOnlyFipsAlgorithms { get { throw null; } }
public static void AddAlgorithm(System.Type algorithm, params string[] names) { }
public static void AddOID(string oid, params string[] names) { }
public static object CreateFromName(string name) { throw null; }
public static object CreateFromName(string name, params object[] args) { throw null; }
public static byte[] EncodeOID(string str) { throw null; }
public static string MapNameToOID(string name) { throw null; }
}
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
public abstract partial class DES : System.Security.Cryptography.SymmetricAlgorithm
{
protected DES() { }
public override byte[] Key { get { throw null; } set { } }
public static new System.Security.Cryptography.DES Create() { throw null; }
public static new System.Security.Cryptography.DES Create(string algName) { throw null; }
public static bool IsSemiWeakKey(byte[] rgbKey) { throw null; }
public static bool IsWeakKey(byte[] rgbKey) { throw null; }
}
public abstract partial class DSA : System.Security.Cryptography.AsymmetricAlgorithm
{
protected DSA() { }
public static new System.Security.Cryptography.DSA Create() { throw null; }
public static new System.Security.Cryptography.DSA Create(string algName) { throw null; }
public abstract byte[] CreateSignature(byte[] rgbHash);
public abstract System.Security.Cryptography.DSAParameters ExportParameters(bool includePrivateParameters);
public override void FromXmlString(string xmlString) { }
protected virtual byte[] HashData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
protected virtual byte[] HashData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
public abstract void ImportParameters(System.Security.Cryptography.DSAParameters parameters);
public virtual byte[] SignData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
public byte[] SignData(byte[] data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
public virtual byte[] SignData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
public override string ToXmlString(bool includePrivateParameters) { throw null; }
public bool VerifyData(byte[] data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
public virtual bool VerifyData(byte[] data, int offset, int count, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
public virtual bool VerifyData(System.IO.Stream data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
public abstract bool VerifySignature(byte[] rgbHash, byte[] rgbSignature);
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct DSAParameters
{
public int Counter;
public byte[] G;
public byte[] J;
public byte[] P;
public byte[] Q;
public byte[] Seed;
public byte[] X;
public byte[] Y;
}
public partial class DSASignatureDeformatter : System.Security.Cryptography.AsymmetricSignatureDeformatter
{
public DSASignatureDeformatter() { }
public DSASignatureDeformatter(System.Security.Cryptography.AsymmetricAlgorithm key) { }
public override void SetHashAlgorithm(string strName) { }
public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { }
public override bool VerifySignature(byte[] rgbHash, byte[] rgbSignature) { throw null; }
}
public partial class DSASignatureFormatter : System.Security.Cryptography.AsymmetricSignatureFormatter
{
public DSASignatureFormatter() { }
public DSASignatureFormatter(System.Security.Cryptography.AsymmetricAlgorithm key) { }
public override byte[] CreateSignature(byte[] rgbHash) { throw null; }
public override void SetHashAlgorithm(string strName) { }
public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct ECCurve
{
public byte[] A;
public byte[] B;
public byte[] Cofactor;
public System.Security.Cryptography.ECCurve.ECCurveType CurveType;
public System.Security.Cryptography.ECPoint G;
public System.Nullable<System.Security.Cryptography.HashAlgorithmName> Hash;
public byte[] Order;
public byte[] Polynomial;
public byte[] Prime;
public byte[] Seed;
public bool IsCharacteristic2 { get { throw null; } }
public bool IsExplicit { get { throw null; } }
public bool IsNamed { get { throw null; } }
public bool IsPrime { get { throw null; } }
public System.Security.Cryptography.Oid Oid { get { throw null; } }
public static System.Security.Cryptography.ECCurve CreateFromFriendlyName(string oidFriendlyName) { throw null; }
public static System.Security.Cryptography.ECCurve CreateFromOid(System.Security.Cryptography.Oid curveOid) { throw null; }
public static System.Security.Cryptography.ECCurve CreateFromValue(string oidValue) { throw null; }
public void Validate() { }
public enum ECCurveType
{
Characteristic2 = 4,
Implicit = 0,
Named = 5,
PrimeMontgomery = 3,
PrimeShortWeierstrass = 1,
PrimeTwistedEdwards = 2,
}
public static partial class NamedCurves
{
public static System.Security.Cryptography.ECCurve brainpoolP160r1 { get { throw null; } }
public static System.Security.Cryptography.ECCurve brainpoolP160t1 { get { throw null; } }
public static System.Security.Cryptography.ECCurve brainpoolP192r1 { get { throw null; } }
public static System.Security.Cryptography.ECCurve brainpoolP192t1 { get { throw null; } }
public static System.Security.Cryptography.ECCurve brainpoolP224r1 { get { throw null; } }
public static System.Security.Cryptography.ECCurve brainpoolP224t1 { get { throw null; } }
public static System.Security.Cryptography.ECCurve brainpoolP256r1 { get { throw null; } }
public static System.Security.Cryptography.ECCurve brainpoolP256t1 { get { throw null; } }
public static System.Security.Cryptography.ECCurve brainpoolP320r1 { get { throw null; } }
public static System.Security.Cryptography.ECCurve brainpoolP320t1 { get { throw null; } }
public static System.Security.Cryptography.ECCurve brainpoolP384r1 { get { throw null; } }
public static System.Security.Cryptography.ECCurve brainpoolP384t1 { get { throw null; } }
public static System.Security.Cryptography.ECCurve brainpoolP512r1 { get { throw null; } }
public static System.Security.Cryptography.ECCurve brainpoolP512t1 { get { throw null; } }
public static System.Security.Cryptography.ECCurve nistP256 { get { throw null; } }
public static System.Security.Cryptography.ECCurve nistP384 { get { throw null; } }
public static System.Security.Cryptography.ECCurve nistP521 { get { throw null; } }
}
}
public abstract partial class ECDiffieHellmanPublicKey : System.IDisposable
{
protected ECDiffieHellmanPublicKey(byte[] keyBlob) { }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public virtual byte[] ToByteArray() { throw null; }
public virtual string ToXmlString() { throw null; }
}
public abstract partial class ECDsa : System.Security.Cryptography.AsymmetricAlgorithm
{
protected ECDsa() { }
public override string KeyExchangeAlgorithm { get { throw null; } }
public override string SignatureAlgorithm { get { throw null; } }
public static new System.Security.Cryptography.ECDsa Create() { throw null; }
public static System.Security.Cryptography.ECDsa Create(System.Security.Cryptography.ECCurve curve) { throw null; }
public static System.Security.Cryptography.ECDsa Create(System.Security.Cryptography.ECParameters parameters) { throw null; }
public static new System.Security.Cryptography.ECDsa Create(string algorithm) { throw null; }
public virtual System.Security.Cryptography.ECParameters ExportExplicitParameters(bool includePrivateParameters) { throw null; }
public virtual System.Security.Cryptography.ECParameters ExportParameters(bool includePrivateParameters) { throw null; }
public override void FromXmlString(string xmlString) { }
public virtual void GenerateKey(System.Security.Cryptography.ECCurve curve) { }
protected virtual byte[] HashData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
protected virtual byte[] HashData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
public virtual void ImportParameters(System.Security.Cryptography.ECParameters parameters) { }
public virtual byte[] SignData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
public virtual byte[] SignData(byte[] data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
public virtual byte[] SignData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
public abstract byte[] SignHash(byte[] hash);
public override string ToXmlString(bool includePrivateParameters) { throw null; }
public bool VerifyData(byte[] data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
public virtual bool VerifyData(byte[] data, int offset, int count, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
public bool VerifyData(System.IO.Stream data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
public abstract bool VerifyHash(byte[] hash, byte[] signature);
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct ECParameters
{
public System.Security.Cryptography.ECCurve Curve;
public byte[] D;
public System.Security.Cryptography.ECPoint Q;
public void Validate() { }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct ECPoint
{
public byte[] X;
public byte[] Y;
}
public partial class HMACMD5 : System.Security.Cryptography.HMAC
{
public HMACMD5() { }
public HMACMD5(byte[] key) { }
public override byte[] Key { get { throw null; } set { } }
protected override void Dispose(bool disposing) { }
protected override void HashCore(byte[] rgb, int ib, int cb) { }
protected override byte[] HashFinal() { throw null; }
public override void Initialize() { }
}
public partial class HMACSHA1 : System.Security.Cryptography.HMAC
{
public HMACSHA1() { }
public HMACSHA1(byte[] key) { }
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
public HMACSHA1(byte[] key, bool useManagedSha1) { }
public override byte[] Key { get { throw null; } set { } }
protected override void Dispose(bool disposing) { }
protected override void HashCore(byte[] rgb, int ib, int cb) { }
protected override byte[] HashFinal() { throw null; }
public override void Initialize() { }
}
public partial class HMACSHA256 : System.Security.Cryptography.HMAC
{
public HMACSHA256() { }
public HMACSHA256(byte[] key) { }
public override byte[] Key { get { throw null; } set { } }
protected override void Dispose(bool disposing) { }
protected override void HashCore(byte[] rgb, int ib, int cb) { }
protected override byte[] HashFinal() { throw null; }
public override void Initialize() { }
}
public partial class HMACSHA384 : System.Security.Cryptography.HMAC
{
public HMACSHA384() { }
public HMACSHA384(byte[] key) { }
public bool ProduceLegacyHmacValues { get; set; }
public override byte[] Key { get { throw null; } set { } }
protected override void Dispose(bool disposing) { }
protected override void HashCore(byte[] rgb, int ib, int cb) { }
protected override byte[] HashFinal() { throw null; }
public override void Initialize() { }
}
public partial class HMACSHA512 : System.Security.Cryptography.HMAC
{
public HMACSHA512() { }
public HMACSHA512(byte[] key) { }
public bool ProduceLegacyHmacValues { get; set; }
public override byte[] Key { get { throw null; } set { } }
protected override void Dispose(bool disposing) { }
protected override void HashCore(byte[] rgb, int ib, int cb) { }
protected override byte[] HashFinal() { throw null; }
public override void Initialize() { }
}
public sealed partial class IncrementalHash : System.IDisposable
{
internal IncrementalHash() { }
public System.Security.Cryptography.HashAlgorithmName AlgorithmName { get { throw null; } }
public void AppendData(byte[] data) { }
public void AppendData(byte[] data, int offset, int count) { }
public static System.Security.Cryptography.IncrementalHash CreateHash(System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
public static System.Security.Cryptography.IncrementalHash CreateHMAC(System.Security.Cryptography.HashAlgorithmName hashAlgorithm, byte[] key) { throw null; }
public void Dispose() { }
public byte[] GetHashAndReset() { throw null; }
}
public abstract partial class MD5 : System.Security.Cryptography.HashAlgorithm
{
protected MD5() { }
public static new System.Security.Cryptography.MD5 Create() { throw null; }
public static new System.Security.Cryptography.MD5 Create(string algName) { throw null; }
}
public abstract class MaskGenerationMethod
{
public abstract byte[] GenerateMask(byte[] rgbSeed, int cbReturn);
}
public class PKCS1MaskGenerationMethod : MaskGenerationMethod
{
public PKCS1MaskGenerationMethod() { }
public string HashName { get { throw null; } set { } }
public override byte[] GenerateMask(byte[] rgbSeed, int cbReturn) { throw null; }
}
public abstract partial class RandomNumberGenerator : System.IDisposable
{
protected RandomNumberGenerator() { }
public static System.Security.Cryptography.RandomNumberGenerator Create() { throw null; }
public static System.Security.Cryptography.RandomNumberGenerator Create(string rngName) { throw null; }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public abstract void GetBytes(byte[] data);
public virtual void GetBytes(byte[] data, int offset, int count) { }
public virtual void GetNonZeroBytes(byte[] data) { }
}
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
public abstract partial class RC2 : System.Security.Cryptography.SymmetricAlgorithm
{
protected int EffectiveKeySizeValue;
protected RC2() { }
public virtual int EffectiveKeySize { get { throw null; } set { } }
public override int KeySize { get { throw null; } set { } }
public static new System.Security.Cryptography.RC2 Create() { throw null; }
public static new System.Security.Cryptography.RC2 Create(string AlgName) { throw null; }
}
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
public abstract partial class Rijndael : System.Security.Cryptography.SymmetricAlgorithm
{
protected Rijndael() { }
public static new System.Security.Cryptography.Rijndael Create() { throw null; }
public static new System.Security.Cryptography.Rijndael Create(string algName) { throw null; }
}
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
public sealed partial class RijndaelManaged : System.Security.Cryptography.Rijndael
{
public RijndaelManaged() { }
public override int BlockSize { get { throw null; } set { } }
public override byte[] IV { get { throw null; } set { } }
public override byte[] Key { get { throw null; } set { } }
public override int KeySize { get { throw null; } set { } }
public override System.Security.Cryptography.KeySizes[] LegalKeySizes { get { throw null; } }
public override System.Security.Cryptography.CipherMode Mode { get { throw null; } set { } }
public override System.Security.Cryptography.PaddingMode Padding { get { throw null; } set { } }
public override System.Security.Cryptography.ICryptoTransform CreateDecryptor() { throw null; }
public override System.Security.Cryptography.ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV) { throw null; }
public override System.Security.Cryptography.ICryptoTransform CreateEncryptor() { throw null; }
public override System.Security.Cryptography.ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV) { throw null; }
protected override void Dispose(bool disposing) { }
public override void GenerateIV() { }
public override void GenerateKey() { }
}
public partial class Rfc2898DeriveBytes : System.Security.Cryptography.DeriveBytes
{
public Rfc2898DeriveBytes(byte[] password, byte[] salt, int iterations) { }
public Rfc2898DeriveBytes(byte[] password, byte[] salt, int iterations, HashAlgorithmName hashAlgorithm) { }
public Rfc2898DeriveBytes(string password, byte[] salt) { }
public Rfc2898DeriveBytes(string password, byte[] salt, int iterations) { }
public Rfc2898DeriveBytes(string password, byte[] salt, int iterations, HashAlgorithmName hashAlgorithm) { }
public Rfc2898DeriveBytes(string password, int saltSize) { }
public Rfc2898DeriveBytes(string password, int saltSize, int iterations) { }
public Rfc2898DeriveBytes(string password, int saltSize, int iterations, HashAlgorithmName hashAlgorithm) { }
public HashAlgorithmName HashAlgorithm { get { throw null; } }
public int IterationCount { get { throw null; } set { } }
public byte[] Salt { get { throw null; } set { } }
public byte[] CryptDeriveKey(string algname, string alghashname, int keySize, byte[] rgbIV) { throw null; }
protected override void Dispose(bool disposing) { }
public override byte[] GetBytes(int cb) { throw null; }
public override void Reset() { }
}
public abstract partial class RSA : System.Security.Cryptography.AsymmetricAlgorithm
{
protected RSA() { }
public override string KeyExchangeAlgorithm { get { throw null; } }
public override string SignatureAlgorithm { get { throw null; } }
public static new System.Security.Cryptography.RSA Create() { throw null; }
public static new System.Security.Cryptography.RSA Create(string algName) { throw null; }
public virtual byte[] Decrypt(byte[] data, System.Security.Cryptography.RSAEncryptionPadding padding) { throw null; }
public virtual byte[] DecryptValue(byte[] rgb) { throw null; }
public virtual byte[] Encrypt(byte[] data, System.Security.Cryptography.RSAEncryptionPadding padding) { throw null; }
public virtual byte[] EncryptValue(byte[] rgb) { throw null; }
public abstract System.Security.Cryptography.RSAParameters ExportParameters(bool includePrivateParameters);
protected virtual byte[] HashData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
protected virtual byte[] HashData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
public override void FromXmlString(string xmlString) { }
public abstract void ImportParameters(System.Security.Cryptography.RSAParameters parameters);
public virtual byte[] SignData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; }
public byte[] SignData(byte[] data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; }
public virtual byte[] SignData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; }
public virtual byte[] SignHash(byte[] hash, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; }
public override string ToXmlString(bool includePrivateParameters) { throw null; }
public bool VerifyData(byte[] data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; }
public virtual bool VerifyData(byte[] data, int offset, int count, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; }
public bool VerifyData(System.IO.Stream data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; }
public virtual bool VerifyHash(byte[] hash, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; }
}
public sealed partial class RSAEncryptionPadding : System.IEquatable<System.Security.Cryptography.RSAEncryptionPadding>
{
internal RSAEncryptionPadding() { }
public System.Security.Cryptography.RSAEncryptionPaddingMode Mode { get { throw null; } }
public System.Security.Cryptography.HashAlgorithmName OaepHashAlgorithm { get { throw null; } }
public static System.Security.Cryptography.RSAEncryptionPadding OaepSHA1 { get { throw null; } }
public static System.Security.Cryptography.RSAEncryptionPadding OaepSHA256 { get { throw null; } }
public static System.Security.Cryptography.RSAEncryptionPadding OaepSHA384 { get { throw null; } }
public static System.Security.Cryptography.RSAEncryptionPadding OaepSHA512 { get { throw null; } }
public static System.Security.Cryptography.RSAEncryptionPadding Pkcs1 { get { throw null; } }
public static System.Security.Cryptography.RSAEncryptionPadding CreateOaep(System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
public override bool Equals(object obj) { throw null; }
public bool Equals(System.Security.Cryptography.RSAEncryptionPadding other) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(System.Security.Cryptography.RSAEncryptionPadding left, System.Security.Cryptography.RSAEncryptionPadding right) { throw null; }
public static bool operator !=(System.Security.Cryptography.RSAEncryptionPadding left, System.Security.Cryptography.RSAEncryptionPadding right) { throw null; }
public override string ToString() { throw null; }
}
public enum RSAEncryptionPaddingMode
{
Oaep = 1,
Pkcs1 = 0,
}
public partial class RSAOAEPKeyExchangeDeformatter : System.Security.Cryptography.AsymmetricKeyExchangeDeformatter
{
public RSAOAEPKeyExchangeDeformatter() { }
public RSAOAEPKeyExchangeDeformatter(System.Security.Cryptography.AsymmetricAlgorithm key) { }
public override string Parameters { get { throw null; } set { } }
public override byte[] DecryptKeyExchange(byte[] rgbData) { throw null; }
public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { }
}
public partial class RSAOAEPKeyExchangeFormatter : System.Security.Cryptography.AsymmetricKeyExchangeFormatter
{
public RSAOAEPKeyExchangeFormatter() { }
public RSAOAEPKeyExchangeFormatter(System.Security.Cryptography.AsymmetricAlgorithm key) { }
public byte[] Parameter { get { throw null; } set { } }
public override string Parameters { get { throw null; } }
public RandomNumberGenerator Rng { get { throw null; } set { } }
public override byte[] CreateKeyExchange(byte[] rgbData) { throw null; }
public override byte[] CreateKeyExchange(byte[] rgbData, System.Type symAlgType) { throw null; }
public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct RSAParameters
{
public byte[] D;
public byte[] DP;
public byte[] DQ;
public byte[] Exponent;
public byte[] InverseQ;
public byte[] Modulus;
public byte[] P;
public byte[] Q;
}
public partial class RSAPKCS1KeyExchangeDeformatter : System.Security.Cryptography.AsymmetricKeyExchangeDeformatter
{
public RSAPKCS1KeyExchangeDeformatter() { }
public RSAPKCS1KeyExchangeDeformatter(System.Security.Cryptography.AsymmetricAlgorithm key) { }
public RandomNumberGenerator RNG { get { throw null; } set { } }
public override string Parameters { get { throw null; } set { } }
public override byte[] DecryptKeyExchange(byte[] rgbIn) { throw null; }
public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { }
}
public partial class RSAPKCS1KeyExchangeFormatter : System.Security.Cryptography.AsymmetricKeyExchangeFormatter
{
public RSAPKCS1KeyExchangeFormatter() { }
public RSAPKCS1KeyExchangeFormatter(System.Security.Cryptography.AsymmetricAlgorithm key) { }
public override string Parameters { get { throw null; } }
public RandomNumberGenerator Rng { get { throw null; } set { } }
public override byte[] CreateKeyExchange(byte[] rgbData) { throw null; }
public override byte[] CreateKeyExchange(byte[] rgbData, System.Type symAlgType) { throw null; }
public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { }
}
public partial class RSAPKCS1SignatureDeformatter : System.Security.Cryptography.AsymmetricSignatureDeformatter
{
public RSAPKCS1SignatureDeformatter() { }
public RSAPKCS1SignatureDeformatter(System.Security.Cryptography.AsymmetricAlgorithm key) { }
public override void SetHashAlgorithm(string strName) { }
public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { }
public override bool VerifySignature(byte[] rgbHash, byte[] rgbSignature) { throw null; }
}
public partial class RSAPKCS1SignatureFormatter : System.Security.Cryptography.AsymmetricSignatureFormatter
{
public RSAPKCS1SignatureFormatter() { }
public RSAPKCS1SignatureFormatter(System.Security.Cryptography.AsymmetricAlgorithm key) { }
public override byte[] CreateSignature(byte[] rgbHash) { throw null; }
public override void SetHashAlgorithm(string strName) { }
public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { }
}
public sealed partial class RSASignaturePadding : System.IEquatable<System.Security.Cryptography.RSASignaturePadding>
{
internal RSASignaturePadding() { }
public System.Security.Cryptography.RSASignaturePaddingMode Mode { get { throw null; } }
public static System.Security.Cryptography.RSASignaturePadding Pkcs1 { get { throw null; } }
public static System.Security.Cryptography.RSASignaturePadding Pss { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public bool Equals(System.Security.Cryptography.RSASignaturePadding other) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(System.Security.Cryptography.RSASignaturePadding left, System.Security.Cryptography.RSASignaturePadding right) { throw null; }
public static bool operator !=(System.Security.Cryptography.RSASignaturePadding left, System.Security.Cryptography.RSASignaturePadding right) { throw null; }
public override string ToString() { throw null; }
}
public enum RSASignaturePaddingMode
{
Pkcs1 = 0,
Pss = 1,
}
public abstract partial class SHA1 : System.Security.Cryptography.HashAlgorithm
{
protected SHA1() { }
public static new System.Security.Cryptography.SHA1 Create() { throw null; }
public static new System.Security.Cryptography.SHA1 Create(string hashName) { throw null; }
}
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
public sealed partial class SHA1Managed : System.Security.Cryptography.SHA1
{
public SHA1Managed() { }
protected sealed override void Dispose(bool disposing) { }
protected sealed override void HashCore(byte[] array, int ibStart, int cbSize) { }
protected sealed override byte[] HashFinal() { throw null; }
public sealed override void Initialize() { }
}
public abstract partial class SHA256 : System.Security.Cryptography.HashAlgorithm
{
protected SHA256() { }
public static new System.Security.Cryptography.SHA256 Create() { throw null; }
public static new System.Security.Cryptography.SHA256 Create(string hashName) { throw null; }
}
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
public sealed partial class SHA256Managed : System.Security.Cryptography.SHA256
{
public SHA256Managed() { }
protected sealed override void Dispose(bool disposing) { }
protected sealed override void HashCore(byte[] array, int ibStart, int cbSize) { }
protected sealed override byte[] HashFinal() { throw null; }
public sealed override void Initialize() { }
}
public abstract partial class SHA384 : System.Security.Cryptography.HashAlgorithm
{
protected SHA384() { }
public static new System.Security.Cryptography.SHA384 Create() { throw null; }
public static new System.Security.Cryptography.SHA384 Create(string hashName) { throw null; }
}
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
public sealed partial class SHA384Managed : System.Security.Cryptography.SHA384
{
public SHA384Managed() { }
protected sealed override void Dispose(bool disposing) { }
protected sealed override void HashCore(byte[] array, int ibStart, int cbSize) { }
protected sealed override byte[] HashFinal() { throw null; }
public sealed override void Initialize() { }
}
public abstract partial class SHA512 : System.Security.Cryptography.HashAlgorithm
{
protected SHA512() { }
public static new System.Security.Cryptography.SHA512 Create() { throw null; }
public static new System.Security.Cryptography.SHA512 Create(string hashName) { throw null; }
}
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
public sealed partial class SHA512Managed : System.Security.Cryptography.SHA512
{
public SHA512Managed() { }
protected sealed override void Dispose(bool disposing) { }
protected sealed override void HashCore(byte[] array, int ibStart, int cbSize) { }
protected sealed override byte[] HashFinal() { throw null; }
public sealed override void Initialize() { }
}
public partial class SignatureDescription {
public SignatureDescription() { }
public SignatureDescription(System.Security.SecurityElement el) { }
public string DeformatterAlgorithm { get { throw null; } set { } }
public string DigestAlgorithm { get { throw null;} set { } }
public string FormatterAlgorithm { get { throw null;} set { } }
public string KeyAlgorithm { get { throw null;} set { } }
public virtual System.Security.Cryptography.AsymmetricSignatureDeformatter CreateDeformatter(System.Security.Cryptography.AsymmetricAlgorithm key) { throw null; }
public virtual System.Security.Cryptography.HashAlgorithm CreateDigest() { throw null; }
public virtual System.Security.Cryptography.AsymmetricSignatureFormatter CreateFormatter(System.Security.Cryptography.AsymmetricAlgorithm key) { throw null; }
}
public abstract partial class TripleDES : System.Security.Cryptography.SymmetricAlgorithm
{
protected TripleDES() { }
public override byte[] Key { get { throw null; } set { } }
public override System.Security.Cryptography.KeySizes[] LegalBlockSizes { get { throw null; } }
public override System.Security.Cryptography.KeySizes[] LegalKeySizes { get { throw null; } }
public static new System.Security.Cryptography.TripleDES Create() { throw null; }
public static new System.Security.Cryptography.TripleDES Create(string str) { throw null; }
public static bool IsWeakKey(byte[] rgbKey) { throw null; }
}
}
| |
/* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.IO;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using XenAdmin.Actions;
using XenAdmin.Controls;
using XenAdmin.Controls.Common;
using XenAdmin.Core;
using XenAdmin.Dialogs;
using Registry = XenAdmin.Core.Registry;
namespace XenAdmin.Wizards.BugToolWizardFiles
{
public partial class BugToolPageDestination : XenTabPage
{
private bool m_buttonNextEnabled;
private const int TokenExpiration = 86400; // 24 hours
public BugToolPageDestination()
{
InitializeComponent();
m_textBoxName.Text = string.Format("{0}{1}.zip", Messages.BUGTOOL_FILE_PREFIX, HelpersGUI.DateTimeToString(DateTime.Now, "yyyy-MM-dd-HH-mm-ss", false));
try
{
string initialDirectory = Path.GetDirectoryName(Properties.Settings.Default.ServerStatusPath);
if (!string.IsNullOrEmpty(initialDirectory) && Directory.Exists(initialDirectory))
m_textBoxLocation.Text = initialDirectory;
}
catch (ArgumentException)
{
//this is normal; ignore
}
usernameTextBox.Visible = usernameLabel.Visible = passwordLabel.Visible = passwordTextBox.Visible =
caseNumberLabel.Visible = caseNumberTextBox.Visible = optionalLabel.Visible =
enterCredentialsLinkLabel.Visible = uploadCheckBox.Visible = !HiddenFeatures.UploadOptionHidden;
string enterCredentialsMessage = string.Format(Messages.STATUS_REPORT_ENTER_CREDENTIALS_MESSAGE, Messages.MY_CITRIX_CREDENTIALS_URL);
enterCredentialsLinkLabel.Text = (enterCredentialsMessage);
enterCredentialsLinkLabel.LinkArea = new System.Windows.Forms.LinkArea(enterCredentialsMessage.IndexOf(Messages.MY_CITRIX_CREDENTIALS_URL), Messages.MY_CITRIX_CREDENTIALS_URL.Length);
}
public override string Text { get { return Messages.BUGTOOL_PAGE_DESTINATION_TEXT; } }
public override string PageTitle { get { return Messages.BUGTOOL_PAGE_DESTINATION_PAGETITLE; } }
public override string HelpID { get { return "ReportDestination"; } }
public override bool EnableNext()
{
return m_buttonNextEnabled;
}
public override void PageLoaded(PageLoadedDirection direction)
{
base.PageLoaded(direction);
PerformCheck(CheckPathValid, CheckCredentialsEntered);
}
public override void PageLeave(PageLoadedDirection direction, ref bool cancel)
{
if (direction == PageLoadedDirection.Forward)
cancel = !PerformCheck(CheckPathValid, CheckCredentialsEntered, CheckUploadAuthentication);
base.PageLeave(direction, ref cancel);
}
public override void SelectDefaultControl()
{
if (string.IsNullOrEmpty(m_textBoxLocation.Text))
m_textBoxLocation.Select();
}
public string OutputFile
{
get
{
var name = m_textBoxName.Text.Trim();
var folder = m_textBoxLocation.Text.Trim();
if (!name.EndsWith(".zip"))
name = string.Concat(name, ".zip");
return string.Format(@"{0}\{1}", folder, name);
}
}
public bool Upload
{
get
{
return uploadCheckBox.Checked;
}
}
public string UploadToken { get; private set; }
public string CaseNumber
{
get
{
return caseNumberTextBox.Text.Trim();
}
}
private bool PerformCheck(params CheckDelegate[] checks)
{
bool success = m_ctrlError.PerformCheck(checks);
m_buttonNextEnabled = success;
OnPageUpdated();
return success;
}
private bool CheckPathValid(out string error)
{
error = string.Empty;
var name = m_textBoxName.Text.Trim();
var folder = m_textBoxLocation.Text.Trim();
if (String.IsNullOrEmpty(name))
return false;
if (!PathValidator.IsFileNameValid(name))
{
error = Messages.BUGTOOL_PAGE_DESTINATION_INVALID_NAME;
return false;
}
if (String.IsNullOrEmpty(folder))
return false;
string path = String.Format("{0}\\{1}", folder, name);
if (!PathValidator.IsPathValid(path))
{
error = Messages.BUGTOOL_PAGE_DESTINATION_INVALID_FOLDER;
return false;
}
return true;
}
private bool CheckCredentialsEntered(out string error)
{
error = string.Empty;
if (!uploadCheckBox.Checked)
return true;
if (string.IsNullOrEmpty(usernameTextBox.Text.Trim()) || string.IsNullOrEmpty(passwordTextBox.Text))
return false;
return true;
}
private bool CheckUploadAuthentication(out string error)
{
error = string.Empty;
if (!uploadCheckBox.Checked)
return true;
if (string.IsNullOrEmpty(usernameTextBox.Text.Trim()) || string.IsNullOrEmpty(passwordTextBox.Text))
return false;
var action = new HealthCheckAuthenticationAction(usernameTextBox.Text.Trim(), passwordTextBox.Text.Trim(),
Registry.HealthCheckIdentityTokenDomainName, Registry.HealthCheckUploadGrantTokenDomainName,
Registry.HealthCheckUploadTokenDomainName, Registry.HealthCheckDiagnosticDomainName, Registry.HealthCheckProductKey,
TokenExpiration, false);
using (var dlg = new ActionProgressDialog(action, ProgressBarStyle.Blocks))
dlg.ShowDialog(Parent);
if (!action.Succeeded)
{
error = action.Exception != null ? action.Exception.Message : Messages.ERROR_UNKNOWN;
UploadToken = null;
return false;
}
UploadToken = action.UploadToken; // curent upload token
return !string.IsNullOrEmpty(UploadToken);
}
private bool CheckCaseNumberValid(out string error)
{
error = string.Empty;
if (!uploadCheckBox.Checked || string.IsNullOrEmpty(caseNumberTextBox.Text.Trim()))
return true;
ulong val;
if (ulong.TryParse(caseNumberTextBox.Text.Trim(), out val) && val > 0 && val < 1000000000)
return true;
error = Messages.BUGTOOL_PAGE_DESTINATION_INVALID_CASE_NO;
return false;
}
#region Control event handlers
private void m_textBoxName_TextChanged(object sender, EventArgs e)
{
PerformCheck(CheckPathValid, CheckCaseNumberValid, CheckCredentialsEntered);
}
private void m_textBoxLocation_TextChanged(object sender, EventArgs e)
{
PerformCheck(CheckPathValid, CheckCaseNumberValid, CheckCredentialsEntered);
}
private void BrowseButton_Click(object sender, EventArgs e)
{
using (FolderBrowserDialog dlog = new FolderBrowserDialog {SelectedPath = m_textBoxLocation.Text, Description = Messages.FOLDER_BROWSER_BUG_TOOL})
{
if (dlog.ShowDialog() == DialogResult.OK)
m_textBoxLocation.Text = dlog.SelectedPath;
}
}
private void uploadCheckBox_CheckedChanged(object sender, EventArgs e)
{
PerformCheck(CheckPathValid, CheckCaseNumberValid, CheckCredentialsEntered);
}
private void credentials_TextChanged(object sender, EventArgs e)
{
uploadCheckBox.Checked = true;
PerformCheck(CheckPathValid, CheckCaseNumberValid, CheckCredentialsEntered);
}
private void caseNumberLabelTextBox_TextChanged(object sender, EventArgs e)
{
uploadCheckBox.Checked = true;
PerformCheck(CheckPathValid, CheckCaseNumberValid, CheckCredentialsEntered);
}
#endregion
private void enterCredentialsLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
this.enterCredentialsLinkLabel.LinkVisited = true;
Program.OpenURL(Messages.MY_CITRIX_CREDENTIALS_URL);
}
}
}
| |
namespace Microsoft.Protocols.TestSuites.Common
{
using System;
using System.Text;
/// <summary>
/// Refers to an attachment Id
/// </summary>
public struct AttachmentId
{
/// <summary>
/// The attachment Id bytes length
/// </summary>
public short AttachmentIdLength;
/// <summary>
/// Attachment Id bytes
/// </summary>
public byte[] Id;
}
/// <summary>
/// A parsed itemid's id
/// </summary>
public class ItemIdId
{
/// <summary>
/// Indicates whether Run Length Encoding (RLE) is used
/// </summary>
private byte compressionByte = 0;
/// <summary>
/// Indicates the type of the Id
/// </summary>
private IdStorageType storageType;
/// <summary>
/// Moniker Length
/// </summary>
private short? monikerLength;
/// <summary>
/// Moniker Bytes
/// </summary>
private byte[] monikerBytes;
/// <summary>
/// Indicates any special processing to perform on an Id when deserializing it
/// </summary>
private IdProcessingInstructionType? processingInstruction;
/// <summary>
/// Store Id Bytes Length
/// </summary>
private short storeIdLength = 0;
/// <summary>
/// Store Id Bytes
/// </summary>
private byte[] storeId;
/// <summary>
/// Folder Id Bytes Length
/// </summary>
private short? folderIdLength;
/// <summary>
/// Folder Id Bytes
/// </summary>
private byte[] folderId;
/// <summary>
/// Indicates how many attachments are in the hierarchy.
/// </summary>
private byte? attachmentIdCount;
/// <summary>
/// Attachment Ids
/// </summary>
private AttachmentId[] attachmentIds;
/// <summary>
/// Gets or sets the byte which indicates whether Run Length Encoding (RLE) is used
/// </summary>
public byte CompressionByte
{
get { return this.compressionByte; }
set { this.compressionByte = value; }
}
/// <summary>
/// Gets or sets the type of the Id
/// </summary>
public IdStorageType StorageType
{
get { return this.storageType; }
set { this.storageType = value; }
}
/// <summary>
/// Gets or sets the moniker length
/// </summary>
public short? MonikerLength
{
get { return this.monikerLength; }
set { this.monikerLength = value; }
}
/// <summary>
/// Gets or sets the moniker bytes
/// </summary>
public byte[] MonikerBytes
{
get { return this.monikerBytes; }
set { this.monikerBytes = value; }
}
/// <summary>
/// Gets the moniker string for MailboxItemSmtpAddressBased
/// </summary>
public string MonikerString
{
get
{
if (this.storageType == IdStorageType.MailboxItemSmtpAddressBased)
{
return Encoding.UTF8.GetString(this.monikerBytes, 0, this.monikerBytes.Length);
}
else
{
return null;
}
}
}
/// <summary>
/// Gets the moniker Guid for ConversationIdMailboxGuidBased or MailboxItemMailboxGuidBased
/// </summary>
public Guid? MonikerGuid
{
get
{
if (this.storageType == IdStorageType.ConversationIdMailboxGuidBased || this.storageType == IdStorageType.MailboxItemMailboxGuidBased)
{
return new Guid(Encoding.UTF8.GetString(this.monikerBytes, 0, this.monikerBytes.Length));
}
else
{
return null;
}
}
}
/// <summary>
/// Gets or sets the processing type to perform on an Id when deserializing it
/// </summary>
public IdProcessingInstructionType? IdProcessingInstruction
{
get { return this.processingInstruction; }
set { this.processingInstruction = value; }
}
/// <summary>
/// Gets or sets the store Id length
/// </summary>
public short StoreIdLength
{
get { return this.storeIdLength; }
set { this.storeIdLength = value; }
}
/// <summary>
/// Gets or sets the store Id bytes
/// </summary>
public byte[] StoreId
{
get { return this.storeId; }
set { this.storeId = value; }
}
/// <summary>
/// Gets or sets the folder Id length
/// </summary>
public short? FolderIdLength
{
get { return this.folderIdLength; }
set { this.folderIdLength = value; }
}
/// <summary>
/// Gets or sets the folder Id bytes
/// </summary>
public byte[] FolderId
{
get { return this.folderId; }
set { this.folderId = value; }
}
/// <summary>
/// Gets or sets the count of attachments.
/// </summary>
public byte? AttachmentIdCount
{
get { return this.attachmentIdCount; }
set { this.attachmentIdCount = value; }
}
/// <summary>
/// Gets or sets the attachment Id array
/// </summary>
public AttachmentId[] AttachmentIds
{
get { return this.attachmentIds; }
set { this.attachmentIds = value; }
}
}
}
| |
// Copyright 2011 Microsoft 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.
namespace Microsoft.Data.OData.Query
{
#region Namespaces
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using Microsoft.Data.Edm;
#endregion
/// <summary>Use this class to perform late-bound operations on data service entity sets.</summary>
/// <remarks>This class was copied from the product.</remarks>
#if INTERNAL_DROP
internal static class DataServiceProviderMethods
#else
public static class DataServiceProviderMethods
#endif
{
#region Internal MethodInfos
/// <summary>MethodInfo for object DataServiceProviderMethods.GetValue(this object value, string propertyName).</summary>
internal static readonly MethodInfo GetValueMethodInfo = typeof(DataServiceProviderMethods).GetMethod(
"GetValue",
BindingFlags.Static | BindingFlags.Public,
null,
new Type[] { typeof(object), typeof(IEdmProperty) },
null);
/// <summary>MethodInfo for IEnumerable<T> DataServiceProviderMethods.GetSequenceValue(this object value, string propertyName).</summary>
internal static readonly MethodInfo GetSequenceValueMethodInfo = typeof(DataServiceProviderMethods).GetMethod(
"GetSequenceValue",
BindingFlags.Static | BindingFlags.Public,
null,
new Type[] { typeof(object), typeof(IEdmProperty) },
null);
/// <summary>MethodInfo for Convert.</summary>
internal static readonly MethodInfo ConvertMethodInfo = typeof(DataServiceProviderMethods).GetMethod(
"Convert",
BindingFlags.Static | BindingFlags.Public);
/// <summary>MethodInfo for TypeIs.</summary>
internal static readonly MethodInfo TypeIsMethodInfo = typeof(DataServiceProviderMethods).GetMethod(
"TypeIs",
BindingFlags.Static | BindingFlags.Public);
/// <summary>Method info for string comparison</summary>
internal static readonly MethodInfo StringCompareMethodInfo = typeof(DataServiceProviderMethods)
.GetMethods(BindingFlags.Public | BindingFlags.Static)
.Single(m => m.Name == "Compare" && m.GetParameters()[0].ParameterType == typeof(string));
/// <summary>Method info for Bool comparison</summary>
internal static readonly MethodInfo BoolCompareMethodInfo = typeof(DataServiceProviderMethods)
.GetMethods(BindingFlags.Public | BindingFlags.Static)
.Single(m => m.Name == "Compare" && m.GetParameters()[0].ParameterType == typeof(bool));
/// <summary>Method info for Bool? comparison</summary>
internal static readonly MethodInfo BoolCompareMethodInfoNullable = typeof(DataServiceProviderMethods)
.GetMethods(BindingFlags.Public | BindingFlags.Static)
.Single(m => m.Name == "Compare" && m.GetParameters()[0].ParameterType == typeof(bool?));
/// <summary>Method info for Guid comparison</summary>
internal static readonly MethodInfo GuidCompareMethodInfo = typeof(DataServiceProviderMethods)
.GetMethods(BindingFlags.Public | BindingFlags.Static)
.Single(m => m.Name == "Compare" && m.GetParameters()[0].ParameterType == typeof(Guid));
/// <summary>Method info for Guid? comparison</summary>
internal static readonly MethodInfo GuidCompareMethodInfoNullable = typeof(DataServiceProviderMethods)
.GetMethods(BindingFlags.Public | BindingFlags.Static)
.Single(m => m.Name == "Compare" && m.GetParameters()[0].ParameterType == typeof(Guid?));
/// <summary>Method info for byte array comparison.</summary>
internal static readonly MethodInfo AreByteArraysEqualMethodInfo = typeof(DataServiceProviderMethods)
.GetMethod("AreByteArraysEqual", BindingFlags.Public | BindingFlags.Static);
/// <summary>Method info for byte array comparison.</summary>
internal static readonly MethodInfo AreByteArraysNotEqualMethodInfo = typeof(DataServiceProviderMethods)
.GetMethod("AreByteArraysNotEqual", BindingFlags.Public | BindingFlags.Static);
#endregion
#region GetValue, GetSequenceValue
/// <summary>Gets a named value from the specified object.</summary>
/// <param name='value'>Object to get value from.</param>
/// <param name='property'><see cref="IEdmProperty"/> describing the property whose value needs to be fetched.</param>
/// <returns>The requested value.</returns>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", Justification = "Parameters will be used in the actual impl")]
public static object GetValue(object value, IEdmProperty property)
{
throw new NotImplementedException();
}
/// <summary>Gets a named value from the specified object as a sequence.</summary>
/// <param name='value'>Object to get value from.</param>
/// <param name='property'><see cref="IEdmProperty"/> describing the property whose value needs to be fetched.</param>
/// <typeparam name="T">expected result type</typeparam>
/// <returns>The requested value as a sequence; null if not found.</returns>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", Justification = "Parameters will be used in the actual impl")]
[SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "need T for proper binding to collections")]
public static IEnumerable<T> GetSequenceValue<T>(object value, IEdmProperty property)
{
throw new NotImplementedException();
}
#endregion
#region Type Conversions
/// <summary>Performs an type cast on the specified value.</summary>
/// <param name='value'>Value.</param>
/// <param name='typeReference'>Type reference to check for.</param>
/// <returns>Casted value.</returns>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", Justification = "Parameters will be used in the actual impl")]
public static object Convert(object value, IEdmTypeReference typeReference)
{
throw new NotImplementedException();
}
/// <summary>Performs an type check on the specified value.</summary>
/// <param name='value'>Value.</param>
/// <param name='typeReference'>Type reference type to check for.</param>
/// <returns>True if value is-a type; false otherwise.</returns>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", Justification = "Parameters will be used in the actual impl")]
public static bool TypeIs(object value, IEdmTypeReference typeReference)
{
throw new NotImplementedException();
}
#endregion
#region Type Comparers
/// <summary>
/// Compares 2 strings by ordinal, used to obtain MethodInfo for comparison operator expression parameter
/// </summary>
/// <param name="left">Left Parameter</param>
/// <param name="right">Right Parameter</param>
/// <returns>0 for equality, -1 for left less than right, 1 for left greater than right</returns>
/// <remarks>
/// Do not change the name of this function because LINQ to SQL is sensitive about the
/// method name, so is EF probably.
/// </remarks>
public static int Compare(String left, String right)
{
return Comparer<string>.Default.Compare(left, right);
}
/// <summary>
/// Compares 2 booleans with true greater than false, used to obtain MethodInfo for comparison operator expression parameter
/// </summary>
/// <param name="left">Left Parameter</param>
/// <param name="right">Right Parameter</param>
/// <returns>0 for equality, -1 for left less than right, 1 for left greater than right</returns>
/// <remarks>
/// Do not change the name of this function because LINQ to SQL is sensitive about the
/// method name, so is EF probably.
/// </remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA908:AvoidTypesThatRequireJitCompilationInPrecompiledAssemblies", Justification = "Need implementation")]
public static int Compare(bool left, bool right)
{
return Comparer<bool>.Default.Compare(left, right);
}
/// <summary>
/// Compares 2 nullable booleans with true greater than false, used to obtain MethodInfo for comparison operator expression parameter
/// </summary>
/// <param name="left">Left Parameter</param>
/// <param name="right">Right Parameter</param>
/// <returns>0 for equality, -1 for left less than right, 1 for left greater than right</returns>
/// <remarks>
/// Do not change the name of this function because LINQ to SQL is sensitive about the
/// method name, so is EF probably.
/// </remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA908:AvoidTypesThatRequireJitCompilationInPrecompiledAssemblies", Justification = "Need implementation")]
public static int Compare(bool? left, bool? right)
{
return Comparer<bool?>.Default.Compare(left, right);
}
/// <summary>
/// Compares 2 guids by byte order, used to obtain MethodInfo for comparison operator expression parameter
/// </summary>
/// <param name="left">Left Parameter</param>
/// <param name="right">Right Parameter</param>
/// <returns>0 for equality, -1 for left less than right, 1 for left greater than right</returns>
/// <remarks>
/// Do not change the name of this function because LINQ to SQL is sensitive about the
/// method name, so is EF probably.
/// </remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA908:AvoidTypesThatRequireJitCompilationInPrecompiledAssemblies", Justification = "Need implementation")]
public static int Compare(Guid left, Guid right)
{
return Comparer<Guid>.Default.Compare(left, right);
}
/// <summary>
/// Compares 2 nullable guids by byte order, used to obtain MethodInfo for comparison operator expression parameter
/// </summary>
/// <param name="left">Left Parameter</param>
/// <param name="right">Right Parameter</param>
/// <returns>0 for equality, -1 for left less than right, 1 for left greater than right</returns>
/// <remarks>
/// Do not change the name of this function because LINQ to SQL is sensitive about the
/// method name, so is EF probably.
/// </remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA908:AvoidTypesThatRequireJitCompilationInPrecompiledAssemblies", Justification = "Need implementation")]
public static int Compare(Guid? left, Guid? right)
{
return Comparer<Guid?>.Default.Compare(left, right);
}
/// <summary>Compares two byte arrays for equality.</summary>
/// <param name="left">First byte array.</param>
/// <param name="right">Second byte array.</param>
/// <returns>true if the arrays are equal; false otherwise.</returns>
public static bool AreByteArraysEqual(byte[] left, byte[] right)
{
if (left == right)
{
return true;
}
if (left == null || right == null)
{
return false;
}
if (left.Length != right.Length)
{
return false;
}
for (int i = 0; i < left.Length; i++)
{
if (left[i] != right[i])
{
return false;
}
}
return true;
}
/// <summary>Compares two byte arrays for equality.</summary>
/// <param name="left">First byte array.</param>
/// <param name="right">Second byte array.</param>
/// <returns>true if the arrays are not equal; false otherwise.</returns>
public static bool AreByteArraysNotEqual(byte[] left, byte[] right)
{
return !AreByteArraysEqual(left, right);
}
#endregion
}
}
| |
// 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!
namespace Google.Apis.HomeGraphService.v1
{
/// <summary>The HomeGraphService Service.</summary>
public class HomeGraphServiceService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public HomeGraphServiceService() : this(new Google.Apis.Services.BaseClientService.Initializer())
{
}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public HomeGraphServiceService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer)
{
AgentUsers = new AgentUsersResource(this);
Devices = new DevicesResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features => new string[0];
/// <summary>Gets the service name.</summary>
public override string Name => "homegraph";
/// <summary>Gets the service base URI.</summary>
public override string BaseUri =>
#if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45
BaseUriOverride ?? "https://homegraph.googleapis.com/";
#else
"https://homegraph.googleapis.com/";
#endif
/// <summary>Gets the service base path.</summary>
public override string BasePath => "";
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri => "https://homegraph.googleapis.com/batch";
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath => "batch";
#endif
/// <summary>Available OAuth 2.0 scopes for use with the HomeGraph API.</summary>
public class Scope
{
/// <summary>Private Service: https://www.googleapis.com/auth/homegraph</summary>
public static string Homegraph = "https://www.googleapis.com/auth/homegraph";
}
/// <summary>Available OAuth 2.0 scope constants for use with the HomeGraph API.</summary>
public static class ScopeConstants
{
/// <summary>Private Service: https://www.googleapis.com/auth/homegraph</summary>
public const string Homegraph = "https://www.googleapis.com/auth/homegraph";
}
/// <summary>Gets the AgentUsers resource.</summary>
public virtual AgentUsersResource AgentUsers { get; }
/// <summary>Gets the Devices resource.</summary>
public virtual DevicesResource Devices { get; }
}
/// <summary>A base abstract class for HomeGraphService requests.</summary>
public abstract class HomeGraphServiceBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
/// <summary>Constructs a new HomeGraphServiceBaseServiceRequest instance.</summary>
protected HomeGraphServiceBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service)
{
}
/// <summary>V1 error format.</summary>
[Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<XgafvEnum> Xgafv { get; set; }
/// <summary>V1 error format.</summary>
public enum XgafvEnum
{
/// <summary>v1 error format</summary>
[Google.Apis.Util.StringValueAttribute("1")]
Value1 = 0,
/// <summary>v2 error format</summary>
[Google.Apis.Util.StringValueAttribute("2")]
Value2 = 1,
}
/// <summary>OAuth access token.</summary>
[Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string AccessToken { get; set; }
/// <summary>Data format for response.</summary>
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json = 0,
/// <summary>Media download with context-dependent Content-Type</summary>
[Google.Apis.Util.StringValueAttribute("media")]
Media = 1,
/// <summary>Responses with Content-Type of application/x-protobuf</summary>
[Google.Apis.Util.StringValueAttribute("proto")]
Proto = 2,
}
/// <summary>JSONP</summary>
[Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Callback { get; set; }
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>
/// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required
/// unless you provide an OAuth 2.0 token.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>
/// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a
/// user, but should not exceed 40 characters.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadType { get; set; }
/// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadProtocol { get; set; }
/// <summary>Initializes HomeGraphService parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("$.xgafv", new Google.Apis.Discovery.Parameter
{
Name = "$.xgafv",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter
{
Name = "access_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add("callback", new Google.Apis.Discovery.Parameter
{
Name = "callback",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("uploadType", new Google.Apis.Discovery.Parameter
{
Name = "uploadType",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("upload_protocol", new Google.Apis.Discovery.Parameter
{
Name = "upload_protocol",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "agentUsers" collection of methods.</summary>
public class AgentUsersResource
{
private const string Resource = "agentUsers";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public AgentUsersResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>
/// Unlinks the given third-party user from your smart home Action. All data related to this user will be
/// deleted. For more details on how users link their accounts, see [fulfillment and
/// authentication](https://developers.google.com/assistant/smarthome/concepts/fulfillment-authentication). The
/// third-party user's identity is passed in via the `agent_user_id` (see DeleteAgentUserRequest). This request
/// must be authorized using service account credentials from your Actions console project.
/// </summary>
/// <param name="agentUserId">Required. Third-party user ID.</param>
public virtual DeleteRequest Delete(string agentUserId)
{
return new DeleteRequest(service, agentUserId);
}
/// <summary>
/// Unlinks the given third-party user from your smart home Action. All data related to this user will be
/// deleted. For more details on how users link their accounts, see [fulfillment and
/// authentication](https://developers.google.com/assistant/smarthome/concepts/fulfillment-authentication). The
/// third-party user's identity is passed in via the `agent_user_id` (see DeleteAgentUserRequest). This request
/// must be authorized using service account credentials from your Actions console project.
/// </summary>
public class DeleteRequest : HomeGraphServiceBaseServiceRequest<Google.Apis.HomeGraphService.v1.Data.Empty>
{
/// <summary>Constructs a new Delete request.</summary>
public DeleteRequest(Google.Apis.Services.IClientService service, string agentUserId) : base(service)
{
AgentUserId = agentUserId;
InitParameters();
}
/// <summary>Required. Third-party user ID.</summary>
[Google.Apis.Util.RequestParameterAttribute("agentUserId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string AgentUserId { get; private set; }
/// <summary>Request ID used for debugging.</summary>
[Google.Apis.Util.RequestParameterAttribute("requestId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string RequestId { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "delete";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "DELETE";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+agentUserId}";
/// <summary>Initializes Delete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("agentUserId", new Google.Apis.Discovery.Parameter
{
Name = "agentUserId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^agentUsers/.*$",
});
RequestParameters.Add("requestId", new Google.Apis.Discovery.Parameter
{
Name = "requestId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
/// <summary>The "devices" collection of methods.</summary>
public class DevicesResource
{
private const string Resource = "devices";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public DevicesResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>
/// Gets the current states in Home Graph for the given set of the third-party user's devices. The third-party
/// user's identity is passed in via the `agent_user_id` (see QueryRequest). This request must be authorized
/// using service account credentials from your Actions console project.
/// </summary>
/// <param name="body">The body of the request.</param>
public virtual QueryRequest Query(Google.Apis.HomeGraphService.v1.Data.QueryRequest body)
{
return new QueryRequest(service, body);
}
/// <summary>
/// Gets the current states in Home Graph for the given set of the third-party user's devices. The third-party
/// user's identity is passed in via the `agent_user_id` (see QueryRequest). This request must be authorized
/// using service account credentials from your Actions console project.
/// </summary>
public class QueryRequest : HomeGraphServiceBaseServiceRequest<Google.Apis.HomeGraphService.v1.Data.QueryResponse>
{
/// <summary>Constructs a new Query request.</summary>
public QueryRequest(Google.Apis.Services.IClientService service, Google.Apis.HomeGraphService.v1.Data.QueryRequest body) : base(service)
{
Body = body;
InitParameters();
}
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.HomeGraphService.v1.Data.QueryRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "query";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/devices:query";
/// <summary>Initializes Query parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
}
}
/// <summary>
/// Reports device state and optionally sends device notifications. Called by your smart home Action when the
/// state of a third-party device changes or you need to send a notification about the device. See [Implement
/// Report State](https://developers.google.com/assistant/smarthome/develop/report-state) for more information.
/// This method updates the device state according to its declared
/// [traits](https://developers.google.com/assistant/smarthome/concepts/devices-traits). Publishing a new state
/// value outside of these traits will result in an `INVALID_ARGUMENT` error response. The third-party user's
/// identity is passed in via the `agent_user_id` (see ReportStateAndNotificationRequest). This request must be
/// authorized using service account credentials from your Actions console project.
/// </summary>
/// <param name="body">The body of the request.</param>
public virtual ReportStateAndNotificationRequest ReportStateAndNotification(Google.Apis.HomeGraphService.v1.Data.ReportStateAndNotificationRequest body)
{
return new ReportStateAndNotificationRequest(service, body);
}
/// <summary>
/// Reports device state and optionally sends device notifications. Called by your smart home Action when the
/// state of a third-party device changes or you need to send a notification about the device. See [Implement
/// Report State](https://developers.google.com/assistant/smarthome/develop/report-state) for more information.
/// This method updates the device state according to its declared
/// [traits](https://developers.google.com/assistant/smarthome/concepts/devices-traits). Publishing a new state
/// value outside of these traits will result in an `INVALID_ARGUMENT` error response. The third-party user's
/// identity is passed in via the `agent_user_id` (see ReportStateAndNotificationRequest). This request must be
/// authorized using service account credentials from your Actions console project.
/// </summary>
public class ReportStateAndNotificationRequest : HomeGraphServiceBaseServiceRequest<Google.Apis.HomeGraphService.v1.Data.ReportStateAndNotificationResponse>
{
/// <summary>Constructs a new ReportStateAndNotification request.</summary>
public ReportStateAndNotificationRequest(Google.Apis.Services.IClientService service, Google.Apis.HomeGraphService.v1.Data.ReportStateAndNotificationRequest body) : base(service)
{
Body = body;
InitParameters();
}
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.HomeGraphService.v1.Data.ReportStateAndNotificationRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "reportStateAndNotification";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/devices:reportStateAndNotification";
/// <summary>Initializes ReportStateAndNotification parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
}
}
/// <summary>
/// Requests Google to send an `action.devices.SYNC`
/// [intent](https://developers.google.com/assistant/smarthome/reference/intent/sync) to your smart home Action
/// to update device metadata for the given user. The third-party user's identity is passed via the
/// `agent_user_id` (see RequestSyncDevicesRequest). This request must be authorized using service account
/// credentials from your Actions console project.
/// </summary>
/// <param name="body">The body of the request.</param>
public virtual RequestSyncRequest RequestSync(Google.Apis.HomeGraphService.v1.Data.RequestSyncDevicesRequest body)
{
return new RequestSyncRequest(service, body);
}
/// <summary>
/// Requests Google to send an `action.devices.SYNC`
/// [intent](https://developers.google.com/assistant/smarthome/reference/intent/sync) to your smart home Action
/// to update device metadata for the given user. The third-party user's identity is passed via the
/// `agent_user_id` (see RequestSyncDevicesRequest). This request must be authorized using service account
/// credentials from your Actions console project.
/// </summary>
public class RequestSyncRequest : HomeGraphServiceBaseServiceRequest<Google.Apis.HomeGraphService.v1.Data.RequestSyncDevicesResponse>
{
/// <summary>Constructs a new RequestSync request.</summary>
public RequestSyncRequest(Google.Apis.Services.IClientService service, Google.Apis.HomeGraphService.v1.Data.RequestSyncDevicesRequest body) : base(service)
{
Body = body;
InitParameters();
}
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.HomeGraphService.v1.Data.RequestSyncDevicesRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "requestSync";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/devices:requestSync";
/// <summary>Initializes RequestSync parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
}
}
/// <summary>
/// Gets all the devices associated with the given third-party user. The third-party user's identity is passed
/// in via the `agent_user_id` (see SyncRequest). This request must be authorized using service account
/// credentials from your Actions console project.
/// </summary>
/// <param name="body">The body of the request.</param>
public virtual SyncRequest Sync(Google.Apis.HomeGraphService.v1.Data.SyncRequest body)
{
return new SyncRequest(service, body);
}
/// <summary>
/// Gets all the devices associated with the given third-party user. The third-party user's identity is passed
/// in via the `agent_user_id` (see SyncRequest). This request must be authorized using service account
/// credentials from your Actions console project.
/// </summary>
public class SyncRequest : HomeGraphServiceBaseServiceRequest<Google.Apis.HomeGraphService.v1.Data.SyncResponse>
{
/// <summary>Constructs a new Sync request.</summary>
public SyncRequest(Google.Apis.Services.IClientService service, Google.Apis.HomeGraphService.v1.Data.SyncRequest body) : base(service)
{
Body = body;
InitParameters();
}
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.HomeGraphService.v1.Data.SyncRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "sync";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/devices:sync";
/// <summary>Initializes Sync parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
}
}
}
}
namespace Google.Apis.HomeGraphService.v1.Data
{
/// <summary>Third-party device ID for one device.</summary>
public class AgentDeviceId : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Third-party device ID.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("id")]
public virtual string Id { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Alternate third-party device ID.</summary>
public class AgentOtherDeviceId : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Project ID for your smart home Action.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("agentId")]
public virtual string AgentId { get; set; }
/// <summary>Unique third-party device ID.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("deviceId")]
public virtual string DeviceId { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Third-party device definition. Next ID = 14</summary>
public class Device : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Attributes for the traits supported by the device.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("attributes")]
public virtual System.Collections.Generic.IDictionary<string, object> Attributes { get; set; }
/// <summary>
/// Custom device attributes stored in Home Graph and provided to your smart home Action in each
/// [QUERY](https://developers.google.com/assistant/smarthome/reference/intent/query) and
/// [EXECUTE](https://developers.google.com/assistant/smarthome/reference/intent/execute) intent. Data in this
/// object has a few constraints: No sensitive information, including but not limited to Personally Identifiable
/// Information.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("customData")]
public virtual System.Collections.Generic.IDictionary<string, object> CustomData { get; set; }
/// <summary>Device manufacturer, model, hardware version, and software version.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("deviceInfo")]
public virtual DeviceInfo DeviceInfo { get; set; }
/// <summary>Third-party device ID.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("id")]
public virtual string Id { get; set; }
/// <summary>Names given to this device by your smart home Action.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual DeviceNames Name { get; set; }
/// <summary>
/// Indicates whether your smart home Action will report notifications to Google for this device via
/// ReportStateAndNotification. If your smart home Action enables users to control device notifications, you
/// should update this field and call RequestSyncDevices.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("notificationSupportedByAgent")]
public virtual System.Nullable<bool> NotificationSupportedByAgent { get; set; }
/// <summary>
/// Alternate IDs associated with this device. This is used to identify cloud synced devices enabled for [local
/// fulfillment](https://developers.google.com/assistant/smarthome/concepts/local).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("otherDeviceIds")]
public virtual System.Collections.Generic.IList<AgentOtherDeviceId> OtherDeviceIds { get; set; }
/// <summary>
/// Suggested name for the room where this device is installed. Google attempts to use this value during user
/// setup.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("roomHint")]
public virtual string RoomHint { get; set; }
/// <summary>
/// Suggested name for the structure where this device is installed. Google attempts to use this value during
/// user setup.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("structureHint")]
public virtual string StructureHint { get; set; }
/// <summary>
/// Traits supported by the device. See [device
/// traits](https://developers.google.com/assistant/smarthome/traits).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("traits")]
public virtual System.Collections.Generic.IList<string> Traits { get; set; }
/// <summary>
/// Hardware type of the device. See [device types](https://developers.google.com/assistant/smarthome/guides).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("type")]
public virtual string Type { get; set; }
/// <summary>
/// Indicates whether your smart home Action will report state of this device to Google via
/// ReportStateAndNotification.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("willReportState")]
public virtual System.Nullable<bool> WillReportState { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Device information.</summary>
public class DeviceInfo : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Device hardware version.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("hwVersion")]
public virtual string HwVersion { get; set; }
/// <summary>Device manufacturer.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("manufacturer")]
public virtual string Manufacturer { get; set; }
/// <summary>Device model.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("model")]
public virtual string Model { get; set; }
/// <summary>Device software version.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("swVersion")]
public virtual string SwVersion { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Identifiers used to describe the device.</summary>
public class DeviceNames : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// List of names provided by the manufacturer rather than the user, such as serial numbers, SKUs, etc.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("defaultNames")]
public virtual System.Collections.Generic.IList<string> DefaultNames { get; set; }
/// <summary>Primary name of the device, generally provided by the user.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>Additional names provided by the user for the device.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nicknames")]
public virtual System.Collections.Generic.IList<string> Nicknames { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical
/// example is to use it as the request or the response type of an API method. For instance: service Foo { rpc
/// Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The JSON representation for `Empty` is empty JSON
/// object `{}`.
/// </summary>
public class Empty : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Request type for the [`Query`](#google.home.graph.v1.HomeGraphApiService.Query) call.</summary>
public class QueryRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. Third-party user ID.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("agentUserId")]
public virtual string AgentUserId { get; set; }
/// <summary>Required. Inputs containing third-party device IDs for which to get the device states.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("inputs")]
public virtual System.Collections.Generic.IList<QueryRequestInput> Inputs { get; set; }
/// <summary>Request ID used for debugging.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("requestId")]
public virtual string RequestId { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Device ID inputs to QueryRequest.</summary>
public class QueryRequestInput : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Payload containing third-party device IDs.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("payload")]
public virtual QueryRequestPayload Payload { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Payload containing device IDs.</summary>
public class QueryRequestPayload : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Third-party device IDs for which to get the device states.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("devices")]
public virtual System.Collections.Generic.IList<AgentDeviceId> Devices { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// Response type for the [`Query`](#google.home.graph.v1.HomeGraphApiService.Query) call. This should follow the
/// same format as the Google smart home `action.devices.QUERY`
/// [response](https://developers.google.com/assistant/smarthome/reference/intent/query). # Example ```json {
/// "requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf", "payload": { "devices": { "123": { "on": true, "online":
/// true }, "456": { "on": true, "online": true, "brightness": 80, "color": { "name": "cerulean", "spectrumRGB":
/// 31655 } } } } } ```
/// </summary>
public class QueryResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Device states for the devices given in the request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("payload")]
public virtual QueryResponsePayload Payload { get; set; }
/// <summary>Request ID used for debugging. Copied from the request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("requestId")]
public virtual string RequestId { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Payload containing device states information.</summary>
public class QueryResponsePayload : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>States of the devices. Map of third-party device ID to struct of device states.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("devices")]
public virtual System.Collections.Generic.IDictionary<string, System.Collections.Generic.IDictionary<string, object>> Devices { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The states and notifications specific to a device.</summary>
public class ReportStateAndNotificationDevice : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Notifications metadata for devices. See the **Device NOTIFICATIONS** section of the individual trait
/// [reference guides](https://developers.google.com/assistant/smarthome/traits).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("notifications")]
public virtual System.Collections.Generic.IDictionary<string, object> Notifications { get; set; }
/// <summary>
/// States of devices to update. See the **Device STATES** section of the individual trait [reference
/// guides](https://developers.google.com/assistant/smarthome/traits).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("states")]
public virtual System.Collections.Generic.IDictionary<string, object> States { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// Request type for the
/// [`ReportStateAndNotification`](#google.home.graph.v1.HomeGraphApiService.ReportStateAndNotification) call. It
/// may include states, notifications, or both. States and notifications are defined per `device_id` (for example,
/// "123" and "456" in the following example). # Example ```json { "requestId":
/// "ff36a3cc-ec34-11e6-b1a0-64510650abcf", "agentUserId": "1234", "payload": { "devices": { "states": { "123": {
/// "on": true }, "456": { "on": true, "brightness": 10 } }, } } } ```
/// </summary>
public class ReportStateAndNotificationRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. Third-party user ID.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("agentUserId")]
public virtual string AgentUserId { get; set; }
/// <summary>Unique identifier per event (for example, a doorbell press).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("eventId")]
public virtual string EventId { get; set; }
/// <summary>Deprecated.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("followUpToken")]
public virtual string FollowUpToken { get; set; }
/// <summary>Required. State of devices to update and notification metadata for devices.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("payload")]
public virtual StateAndNotificationPayload Payload { get; set; }
/// <summary>Request ID used for debugging.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("requestId")]
public virtual string RequestId { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// Response type for the
/// [`ReportStateAndNotification`](#google.home.graph.v1.HomeGraphApiService.ReportStateAndNotification) call.
/// </summary>
public class ReportStateAndNotificationResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Request ID copied from ReportStateAndNotificationRequest.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("requestId")]
public virtual string RequestId { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// Request type for the [`RequestSyncDevices`](#google.home.graph.v1.HomeGraphApiService.RequestSyncDevices) call.
/// </summary>
public class RequestSyncDevicesRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. Third-party user ID.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("agentUserId")]
public virtual string AgentUserId { get; set; }
/// <summary>
/// Optional. If set, the request will be added to a queue and a response will be returned immediately. This
/// enables concurrent requests for the given `agent_user_id`, but the caller will not receive any error
/// responses.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("async")]
public virtual System.Nullable<bool> Async__ { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// Response type for the [`RequestSyncDevices`](#google.home.graph.v1.HomeGraphApiService.RequestSyncDevices) call.
/// Intentionally empty upon success. An HTTP response code is returned with more details upon failure.
/// </summary>
public class RequestSyncDevicesResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Payload containing the state and notification information for devices.</summary>
public class StateAndNotificationPayload : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The devices for updating state and sending notifications.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("devices")]
public virtual ReportStateAndNotificationDevice Devices { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Request type for the [`Sync`](#google.home.graph.v1.HomeGraphApiService.Sync) call.</summary>
public class SyncRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. Third-party user ID.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("agentUserId")]
public virtual string AgentUserId { get; set; }
/// <summary>Request ID used for debugging.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("requestId")]
public virtual string RequestId { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// Response type for the [`Sync`](#google.home.graph.v1.HomeGraphApiService.Sync) call. This should follow the same
/// format as the Google smart home `action.devices.SYNC`
/// [response](https://developers.google.com/assistant/smarthome/reference/intent/sync). # Example ```json {
/// "requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf", "payload": { "agentUserId": "1836.15267389", "devices": [{
/// "id": "123", "type": "action.devices.types.OUTLET", "traits": [ "action.devices.traits.OnOff" ], "name": {
/// "defaultNames": ["My Outlet 1234"], "name": "Night light", "nicknames": ["wall plug"] }, "willReportState":
/// false, "deviceInfo": { "manufacturer": "lights-out-inc", "model": "hs1234", "hwVersion": "3.2", "swVersion":
/// "11.4" }, "customData": { "fooValue": 74, "barValue": true, "bazValue": "foo" } }] } } ```
/// </summary>
public class SyncResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Devices associated with the third-party user.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("payload")]
public virtual SyncResponsePayload Payload { get; set; }
/// <summary>Request ID used for debugging. Copied from the request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("requestId")]
public virtual string RequestId { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Payload containing device information.</summary>
public class SyncResponsePayload : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Third-party user ID</summary>
[Newtonsoft.Json.JsonPropertyAttribute("agentUserId")]
public virtual string AgentUserId { get; set; }
/// <summary>Devices associated with the third-party user.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("devices")]
public virtual System.Collections.Generic.IList<Device> Devices { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| |
using System;
/// <summary>
/// System.Decimal.ctor(Int32,Int32,Int32,Boolean,Byte)
/// </summary>
public class DecimalCtor3
{
public static int Main()
{
DecimalCtor3 dCtor3 = new DecimalCtor3();
TestLibrary.TestFramework.BeginTestCase("for Constructor:System.Decimal.Ctor(Int32,Int32,Int32,Boolean,Byte)");
if (dCtor3.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
return retVal;
}
#region PositiveTesting
public bool PosTest1()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest1:Verify the isNagetive is true... ";
const string c_TEST_ID = "P001";
int low = TestLibrary.Generator.GetInt32(-55);
int mid = TestLibrary.Generator.GetInt32(-55);
int hi = TestLibrary.Generator.GetInt32(-55);
bool isNagetive = true;
Byte scale = TestLibrary.Generator.GetByte(-55);
while (scale > 28)
{
scale = TestLibrary.Generator.GetByte(-55);
}
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
Decimal decimalValue = new Decimal(low, mid, hi, isNagetive, scale);
int[] arrInt = Decimal.GetBits(decimalValue);
if (arrInt[0] != low)
{
string errorDesc = "lo Value is not " +low.ToString() +" as expected: param is " + arrInt[0].ToString();
TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
if (arrInt[1] != mid)
{
string errorDesc = "mid Value is not " + mid.ToString() + " as expected: param is " + arrInt[1].ToString();
TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
if (arrInt[2] != hi)
{
string errorDesc = "hi Value is not " + hi.ToString() + " as expected: param is " + arrInt[2].ToString();
TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
if (isNagetive)
{
if (decimalValue > 0m)
{
string errorDesc = "created decimal object should is less than 0 ";
TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
else
{
if (decimalValue < 0m)
{
string errorDesc = "created decimal object should is larger than 0 ";
TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
string subLast;
int resScale;
int index = decimalValue.ToString().IndexOf(System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
if (index != -1)
{
subLast = decimalValue.ToString().Substring(index);
resScale = subLast.Length - 1;
}
else
{
resScale = 0;
}
if (Convert.ToInt64(scale) != resScale)
{
string errorDesc = "scale Value is not " + scale.ToString() + " as expected: actual<" + resScale.ToString() + ">";
TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID + " TestId-" + c_TEST_ID, "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest2:Verify the isNagetive is false... ";
const string c_TEST_ID = "P002";
int low = TestLibrary.Generator.GetInt32(-55);
int mid = TestLibrary.Generator.GetInt32(-55);
int hi = TestLibrary.Generator.GetInt32(-55);
bool isNagetive = false;
Byte scale = TestLibrary.Generator.GetByte(-55);
while (scale > 28)
{
scale = TestLibrary.Generator.GetByte(-55);
}
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
Decimal decimalValue = new Decimal(low, mid, hi, isNagetive, scale);
int[] arrInt = Decimal.GetBits(decimalValue);
if (arrInt[0] != low)
{
string errorDesc = "lo Value is not " + low.ToString() + " as expected: param is " + arrInt[0].ToString();
TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
if (arrInt[1] != mid)
{
string errorDesc = "mid Value is not " + mid.ToString() + " as expected: param is " + arrInt[1].ToString();
TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
if (arrInt[2] != hi)
{
string errorDesc = "hi Value is not " + hi.ToString() + " as expected: param is " + arrInt[2].ToString();
TestLibrary.TestFramework.LogError("010" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
if (isNagetive)
{
if (decimalValue > 0m)
{
string errorDesc = "created decimal object should is less than 0 ";
TestLibrary.TestFramework.LogError("011" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
else
{
if (decimalValue < 0m)
{
string errorDesc = "created decimal object should is larger than 0 ";
TestLibrary.TestFramework.LogError("012" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
string subLast;
int resScale;
int index = decimalValue.ToString().IndexOf(System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
if (index != -1)
{
subLast = decimalValue.ToString().Substring(index);
resScale = subLast.Length - 1;
}
else
{
resScale=0;
}
if (Convert.ToInt64(scale) != resScale)
{
string errorDesc = "scale Value is not " + scale.ToString() + " as expected: actual<" + resScale.ToString() + ">";
TestLibrary.TestFramework.LogError("013" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("014" + " TestId-" + c_TEST_ID + " TestId-" + c_TEST_ID, "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Testing
public bool NegTest1()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest1:Verify the scale is larger than 28";
const string c_TEST_ID = "N001";
int low = TestLibrary.Generator.GetInt32(-55);
int mid = TestLibrary.Generator.GetInt32(-55);
int hi = TestLibrary.Generator.GetInt32(-55);
bool isNagetive = false;
Byte scale = TestLibrary.Generator.GetByte(-55);
while (scale < 28)
{
scale = TestLibrary.Generator.GetByte(-55);
}
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
Decimal decimalValue = new Decimal(low,mid,hi,isNagetive,scale);
TestLibrary.TestFramework.LogError("015" + " TestId-" + c_TEST_ID, "ArgumentOutOfRangeException is not thrown as expected ." + "\n scale value is " + scale.ToString());
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("016" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
}
| |
// Copyright 2018, Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using FirebaseAdmin.Util;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Http;
using Google.Apis.Json;
using Google.Apis.Requests;
using Google.Apis.Services;
using Google.Apis.Util;
namespace FirebaseAdmin.Messaging
{
/// <summary>
/// A client for making authorized HTTP calls to the FCM backend service. Handles request
/// serialization, response parsing, and HTTP error handling.
/// </summary>
internal sealed class FirebaseMessagingClient : IDisposable
{
private const string FcmBaseUrl = "https://fcm.googleapis.com";
private const string FcmSendUrl = FcmBaseUrl + "/v1/projects/{0}/messages:send";
private const string FcmBatchUrl = FcmBaseUrl + "/batch";
private readonly ErrorHandlingHttpClient<FirebaseMessagingException> httpClient;
private readonly string sendUrl;
private readonly string restPath;
private readonly FCMClientService fcmClientService;
internal FirebaseMessagingClient(Args args)
{
if (string.IsNullOrEmpty(args.ProjectId))
{
throw new ArgumentException(
"Project ID is required to access messaging service. Use a service account "
+ "credential or set the project ID explicitly via AppOptions. Alternatively "
+ "you can set the project ID via the GOOGLE_CLOUD_PROJECT environment "
+ "variable.");
}
this.httpClient = new ErrorHandlingHttpClient<FirebaseMessagingException>(
new ErrorHandlingHttpClientArgs<FirebaseMessagingException>()
{
HttpClientFactory = args.ClientFactory.ThrowIfNull(nameof(args.ClientFactory)),
Credential = args.Credential.ThrowIfNull(nameof(args.Credential)),
RequestExceptionHandler = MessagingErrorHandler.Instance,
ErrorResponseHandler = MessagingErrorHandler.Instance,
DeserializeExceptionHandler = MessagingErrorHandler.Instance,
RetryOptions = args.RetryOptions,
});
this.fcmClientService = new FCMClientService(new BaseClientService.Initializer()
{
HttpClientFactory = args.ClientFactory,
HttpClientInitializer = args.Credential,
ApplicationName = ClientVersion,
});
this.sendUrl = string.Format(FcmSendUrl, args.ProjectId);
this.restPath = this.sendUrl.Substring(FcmBaseUrl.Length);
}
internal static string ClientVersion
{
get
{
return $"fire-admin-dotnet/{FirebaseApp.GetSdkVersion()}";
}
}
/// <summary>
/// Sends a message to the FCM service for delivery. The message gets validated both by
/// the Admin SDK, and the remote FCM service. A successful return value indicates
/// that the message has been successfully sent to FCM, where it has been accepted by the
/// FCM service.
/// </summary>
/// <returns>A task that completes with a message ID string, which represents
/// successful handoff to FCM.</returns>
/// <exception cref="ArgumentNullException">If the message argument is null.</exception>
/// <exception cref="ArgumentException">If the message contains any invalid
/// fields.</exception>
/// <exception cref="FirebaseMessagingException">If an error occurs while sending the
/// message.</exception>
/// <param name="message">The message to be sent. Must not be null.</param>
/// <param name="dryRun">A boolean indicating whether to perform a dry run (validation
/// only) of the send. If set to true, the message will be sent to the FCM backend service,
/// but it will not be delivered to any actual recipients.</param>
/// <param name="cancellationToken">A cancellation token to monitor the asynchronous
/// operation.</param>
public async Task<string> SendAsync(
Message message,
bool dryRun = false,
CancellationToken cancellationToken = default(CancellationToken))
{
var body = new SendRequest()
{
Message = message.ThrowIfNull(nameof(message)).CopyAndValidate(),
ValidateOnly = dryRun,
};
var request = new HttpRequestMessage()
{
Method = HttpMethod.Post,
RequestUri = new Uri(this.sendUrl),
Content = NewtonsoftJsonSerializer.Instance.CreateJsonHttpContent(body),
};
AddCommonHeaders(request);
var response = await this.httpClient
.SendAndDeserializeAsync<SingleMessageResponse>(request, cancellationToken)
.ConfigureAwait(false);
return response.Result.Name;
}
/// <summary>
/// Sends all messages in a single batch.
/// </summary>
/// <param name="messages">The messages to be sent. Must not be null.</param>
/// <param name="dryRun">A boolean indicating whether to perform a dry run (validation
/// only) of the send. If set to true, the messages will be sent to the FCM backend service,
/// but it will not be delivered to any actual recipients.</param>
/// <param name="cancellationToken">A cancellation token to monitor the asynchronous
/// operation.</param>
/// <returns>A task that completes with a <see cref="BatchResponse"/>, giving details about
/// the batch operation.</returns>
public async Task<BatchResponse> SendAllAsync(
IEnumerable<Message> messages,
bool dryRun = false,
CancellationToken cancellationToken = default(CancellationToken))
{
var copyOfMessages = messages.ThrowIfNull(nameof(messages))
.Select((message) => message.CopyAndValidate())
.ToList();
if (copyOfMessages.Count < 1)
{
throw new ArgumentException("At least one message is required.");
}
if (copyOfMessages.Count > 500)
{
throw new ArgumentException("At most 500 messages are allowed.");
}
try
{
return await this.SendBatchRequestAsync(copyOfMessages, dryRun, cancellationToken)
.ConfigureAwait(false);
}
catch (HttpRequestException e)
{
throw MessagingErrorHandler.Instance.HandleHttpRequestException(e);
}
}
public void Dispose()
{
this.httpClient.Dispose();
this.fcmClientService.Dispose();
}
internal static FirebaseMessagingClient Create(FirebaseApp app)
{
var args = new Args
{
ClientFactory = app.Options.HttpClientFactory,
Credential = app.Options.Credential,
ProjectId = app.GetProjectId(),
RetryOptions = RetryOptions.Default,
};
return new FirebaseMessagingClient(args);
}
private static void AddCommonHeaders(HttpRequestMessage request)
{
request.Headers.Add("X-Firebase-Client", ClientVersion);
request.Headers.Add("X-GOOG-API-FORMAT-VERSION", "2");
}
private async Task<BatchResponse> SendBatchRequestAsync(
IEnumerable<Message> messages,
bool dryRun,
CancellationToken cancellationToken)
{
var responses = new List<SendResponse>();
var batch = this.CreateBatchRequest(
messages,
dryRun,
(content, error, index, message) =>
{
SendResponse sendResponse;
if (error != null)
{
var json = (error as ContentRetainingRequestError).Content;
var exception = MessagingErrorHandler.Instance.HandleHttpErrorResponse(
message, json);
sendResponse = SendResponse.FromException(exception);
}
else if (content != null)
{
sendResponse = SendResponse.FromMessageId(content.Name);
}
else
{
var exception = new FirebaseMessagingException(
ErrorCode.Unknown,
$"Unexpected batch response. Response status code: {message.StatusCode}.");
sendResponse = SendResponse.FromException(exception);
}
responses.Add(sendResponse);
});
await batch.ExecuteAsync(cancellationToken).ConfigureAwait(false);
return new BatchResponse(responses);
}
private BatchRequest CreateBatchRequest(
IEnumerable<Message> messages,
bool dryRun,
BatchRequest.OnResponse<SingleMessageResponse> callback)
{
var batch = new BatchRequest(this.fcmClientService, FcmBatchUrl);
foreach (var message in messages)
{
var body = new SendRequest()
{
Message = message,
ValidateOnly = dryRun,
};
batch.Queue(new FCMClientServiceRequest(this.fcmClientService, this.restPath, body), callback);
}
return batch;
}
/// <summary>
/// Represents the envelope message accepted by the FCM backend service, including the message
/// payload and other options like <c>validate_only</c>.
/// </summary>
internal class SendRequest
{
[Newtonsoft.Json.JsonProperty("message")]
public Message Message { get; set; }
[Newtonsoft.Json.JsonProperty("validate_only")]
public bool ValidateOnly { get; set; }
}
/// <summary>
/// Represents the response messages sent by the FCM backend service when sending a single
/// message. Primarily consists of the message ID (Name) that indicates success handoff to FCM.
/// </summary>
internal class SingleMessageResponse
{
[Newtonsoft.Json.JsonProperty("name")]
public string Name { get; set; }
}
internal sealed class Args
{
internal HttpClientFactory ClientFactory { get; set; }
internal GoogleCredential Credential { get; set; }
internal string ProjectId { get; set; }
internal RetryOptions RetryOptions { get; set; }
}
private sealed class FCMClientService : BaseClientService
{
public FCMClientService(Initializer initializer)
: base(initializer) { }
public override string Name => "FCM";
public override string BaseUri => FcmBaseUrl;
public override string BasePath => null;
public override IList<string> Features => null;
public override async Task<RequestError> DeserializeError(HttpResponseMessage response)
{
var error = await base.DeserializeError(response).ConfigureAwait(false);
// Read the full response text here and add it to the RequestError so it can be
// used in the batch request callback.
// See https://github.com/googleapis/google-api-dotnet-client/issues/1632.
var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
return new ContentRetainingRequestError(error, content);
}
}
private sealed class ContentRetainingRequestError : RequestError
{
internal ContentRetainingRequestError(RequestError error, string content)
{
this.Code = error.Code;
this.Message = error.Message;
this.Errors = error.Errors;
this.Content = content;
}
internal string Content { get; }
}
private sealed class FCMClientServiceRequest : ClientServiceRequest<string>
{
private readonly string restPath;
private readonly SendRequest body;
public FCMClientServiceRequest(FCMClientService clientService, string restPath, SendRequest body)
: base(clientService)
{
this.restPath = restPath;
this.body = body;
this.ModifyRequest = (request) =>
{
AddCommonHeaders(request);
};
this.InitParameters();
}
public override string HttpMethod => "POST";
public override string RestPath => this.restPath;
public override string MethodName => throw new NotImplementedException();
protected override object GetBody()
{
return this.body;
}
}
}
}
| |
/////////////////////////////////////////////////////////////////////////////////
// Paint.NET //
// Copyright (C) Rick Brewster, Tom Jackson, and past contributors. //
// Portions Copyright (C) Microsoft Corporation. All Rights Reserved. //
// See license-pdn.txt for full licensing and attribution details. //
/////////////////////////////////////////////////////////////////////////////////
using System;
namespace Pinta.Core
{
/// <summary>
/// Provides a set of standard UnaryPixelOps.
/// </summary>
public sealed class UnaryPixelOps
{
private UnaryPixelOps()
{
}
/// <summary>
/// Passes through the given color value.
/// result(color) = color
/// </summary>
[Serializable]
public class Identity
: UnaryPixelOp
{
public override ColorBgra Apply(ColorBgra color)
{
return color;
}
public unsafe override void Apply(ColorBgra *dst, ColorBgra *src, int length)
{
for (int i = 0; i < length; i++) {
*dst = *src;
dst++;
src++;
}
}
public unsafe override void Apply(ColorBgra* ptr, int length)
{
return;
}
}
/// <summary>
/// Always returns a constant color.
/// </summary>
[Serializable]
public class Constant
: UnaryPixelOp
{
private ColorBgra setColor;
public override ColorBgra Apply(ColorBgra color)
{
return setColor;
}
public unsafe override void Apply(ColorBgra* dst, ColorBgra* src, int length)
{
while (length > 0)
{
*dst = setColor;
++dst;
--length;
}
}
public unsafe override void Apply(ColorBgra* ptr, int length)
{
while (length > 0)
{
*ptr = setColor;
++ptr;
--length;
}
}
public Constant(ColorBgra setColor)
{
this.setColor = setColor;
}
}
/// <summary>
/// Blends pixels with the specified constant color.
/// </summary>
[Serializable]
public class BlendConstant
: UnaryPixelOp
{
private ColorBgra blendColor;
public override ColorBgra Apply(ColorBgra color)
{
int a = blendColor.A;
int invA = 255 - a;
int r = ((color.R * invA) + (blendColor.R * a)) / 256;
int g = ((color.G * invA) + (blendColor.G * a)) / 256;
int b = ((color.B * invA) + (blendColor.B * a)) / 256;
byte a2 = ComputeAlpha(color.A, blendColor.A);
return ColorBgra.FromBgra((byte)b, (byte)g, (byte)r, a2);
}
public BlendConstant(ColorBgra blendColor)
{
this.blendColor = blendColor;
}
}
/// <summary>
/// Used to set a given channel of a pixel to a given, predefined color.
/// Useful if you want to set only the alpha value of a given region.
/// </summary>
[Serializable]
public class SetChannel
: UnaryPixelOp
{
private int channel;
private byte setValue;
public override ColorBgra Apply(ColorBgra color)
{
color[channel] = setValue;
return color;
}
public override unsafe void Apply(ColorBgra* dst, ColorBgra* src, int length)
{
while (length > 0)
{
*dst = *src;
(*dst)[channel] = setValue;
++dst;
++src;
--length;
}
}
public override unsafe void Apply(ColorBgra* ptr, int length)
{
while (length > 0)
{
(*ptr)[channel] = setValue;
++ptr;
--length;
}
}
public SetChannel(int channel, byte setValue)
{
this.channel = channel;
this.setValue = setValue;
}
}
/// <summary>
/// Specialization of SetChannel that sets the alpha channel.
/// </summary>
/// <remarks>This class depends on the system being litte-endian with the alpha channel
/// occupying the 8 most-significant-bits of a ColorBgra instance.
/// By the way, we use addition instead of bitwise-OR because an addition can be
/// perform very fast (0.5 cycles) on a Pentium 4.</remarks>
[Serializable]
public class SetAlphaChannel
: UnaryPixelOp
{
private UInt32 addValue;
public override ColorBgra Apply(ColorBgra color)
{
return ColorBgra.FromUInt32((color.Bgra & 0x00ffffff) + addValue);
}
public override unsafe void Apply(ColorBgra* dst, ColorBgra* src, int length)
{
while (length > 0)
{
dst->Bgra = (src->Bgra & 0x00ffffff) + addValue;
++dst;
++src;
--length;
}
}
public override unsafe void Apply(ColorBgra* ptr, int length)
{
while (length > 0)
{
ptr->Bgra = (ptr->Bgra & 0x00ffffff) + addValue;
++ptr;
--length;
}
}
public SetAlphaChannel(byte alphaValue)
{
addValue = (uint)alphaValue << 24;
}
}
/// <summary>
/// Specialization of SetAlphaChannel that always sets alpha to 255.
/// </summary>
[Serializable]
public class SetAlphaChannelTo255
: UnaryPixelOp
{
public override ColorBgra Apply(ColorBgra color)
{
return ColorBgra.FromUInt32(color.Bgra | 0xff000000);
}
public override unsafe void Apply(ColorBgra* dst, ColorBgra* src, int length)
{
while (length > 0)
{
dst->Bgra = src->Bgra | 0xff000000;
++dst;
++src;
--length;
}
}
public override unsafe void Apply(ColorBgra* ptr, int length)
{
while (length > 0)
{
ptr->Bgra |= 0xff000000;
++ptr;
--length;
}
}
}
/// <summary>
/// Inverts a pixel's color, and passes through the alpha component.
/// </summary>
[Serializable]
public class Invert
: UnaryPixelOp
{
public override ColorBgra Apply(ColorBgra color)
{
return ColorBgra.FromBgra((byte)(255 - color.B), (byte)(255 - color.G), (byte)(255 - color.R), color.A);
}
}
/// <summary>
/// If the color is within the red tolerance, remove it
/// </summary>
[Serializable]
public class RedEyeRemove
: UnaryPixelOp
{
private int tolerence;
private double setSaturation;
public RedEyeRemove(int tol, int sat)
{
tolerence = tol;
setSaturation = (double)sat / 100;
}
public override ColorBgra Apply(ColorBgra color)
{
// The higher the saturation, the more red it is
int saturation = GetSaturation(color);
// The higher the difference between the other colors, the more red it is
int difference = color.R - Math.Max(color.B,color.G);
// If it is within tolerence, and the saturation is high
if ((difference > tolerence) && (saturation > 100))
{
double i = 255.0 * color.GetIntensity();
byte ib = (byte)(i * setSaturation); // adjust the red color for user inputted saturation
return ColorBgra.FromBgra((byte)color.B,(byte)color.G, ib, color.A);
}
else
{
return color;
}
}
//Saturation formula from RgbColor.cs, public HsvColor ToHsv()
private int GetSaturation(ColorBgra color)
{
double min;
double max;
double delta;
double r = (double) color.R / 255;
double g = (double) color.G / 255;
double b = (double) color.B / 255;
double s;
min = Math.Min(Math.Min(r, g), b);
max = Math.Max(Math.Max(r, g), b);
delta = max - min;
if (max == 0 || delta == 0)
{
// R, G, and B must be 0, or all the same.
// In this case, S is 0, and H is undefined.
// Using H = 0 is as good as any...
s = 0;
}
else
{
s = delta / max;
}
return (int)(s * 255);
}
}
/// <summary>
/// Inverts a pixel's color and its alpha component.
/// </summary>
[Serializable]
public class InvertWithAlpha
: UnaryPixelOp
{
public override ColorBgra Apply(ColorBgra color)
{
return ColorBgra.FromBgra((byte)(255 - color.B), (byte)(255 - color.G), (byte)(255 - color.R), (byte)(255 - color.A));
}
}
/// <summary>
/// Averages the input color's red, green, and blue channels. The alpha component
/// is unaffected.
/// </summary>
[Serializable]
public class AverageChannels
: UnaryPixelOp
{
public override ColorBgra Apply(ColorBgra color)
{
byte average = (byte)(((int)color.R + (int)color.G + (int)color.B) / 3);
return ColorBgra.FromBgra(average, average, average, color.A);
}
}
[Serializable]
public class Desaturate
: UnaryPixelOp
{
public override ColorBgra Apply(ColorBgra color)
{
byte i = color.GetIntensityByte();
return ColorBgra.FromBgra(i, i, i, color.A);
}
public unsafe override void Apply(ColorBgra* ptr, int length)
{
while (length > 0)
{
byte i = ptr->GetIntensityByte();
ptr->R = i;
ptr->G = i;
ptr->B = i;
++ptr;
--length;
}
}
public unsafe override void Apply(ColorBgra* dst, ColorBgra* src, int length)
{
while (length > 0)
{
byte i = src->GetIntensityByte();
dst->B = i;
dst->G = i;
dst->R = i;
dst->A = src->A;
++dst;
++src;
--length;
}
}
}
[Serializable]
public class LuminosityCurve
: UnaryPixelOp
{
public byte[] Curve = new byte[256];
public LuminosityCurve()
{
for (int i = 0; i < 256; ++i)
{
Curve[i] = (byte)i;
}
}
public override ColorBgra Apply(ColorBgra color)
{
byte lumi = color.GetIntensityByte();
int diff = Curve[lumi] - lumi;
return ColorBgra.FromBgraClamped(
color.B + diff,
color.G + diff,
color.R + diff,
color.A);
}
}
[Serializable]
public class ChannelCurve
: UnaryPixelOp
{
public byte[] CurveB = new byte[256];
public byte[] CurveG = new byte[256];
public byte[] CurveR = new byte[256];
public ChannelCurve()
{
for (int i = 0; i < 256; ++i)
{
CurveB[i] = (byte)i;
CurveG[i] = (byte)i;
CurveR[i] = (byte)i;
}
}
public override unsafe void Apply(ColorBgra* dst, ColorBgra* src, int length)
{
while (--length >= 0)
{
dst->B = CurveB[src->B];
dst->G = CurveG[src->G];
dst->R = CurveR[src->R];
dst->A = src->A;
++dst;
++src;
}
}
public override unsafe void Apply(ColorBgra* ptr, int length)
{
while (--length >= 0)
{
ptr->B = CurveB[ptr->B];
ptr->G = CurveG[ptr->G];
ptr->R = CurveR[ptr->R];
++ptr;
}
}
public override ColorBgra Apply(ColorBgra color)
{
return ColorBgra.FromBgra(CurveB[color.B], CurveG[color.G], CurveR[color.R], color.A);
}
// public override void Apply(Surface dst, Point dstOffset, Surface src, Point srcOffset, int scanLength)
// {
// base.Apply (dst, dstOffset, src, srcOffset, scanLength);
// }
}
[Serializable]
public class Level
: ChannelCurve,
ICloneable
{
private ColorBgra colorInLow;
public ColorBgra ColorInLow
{
get
{
return colorInLow;
}
set
{
if (value.R == 255)
{
value.R = 254;
}
if (value.G == 255)
{
value.G = 254;
}
if (value.B == 255)
{
value.B = 254;
}
if (colorInHigh.R < value.R + 1)
{
colorInHigh.R = (byte)(value.R + 1);
}
if (colorInHigh.G < value.G + 1)
{
colorInHigh.G = (byte)(value.R + 1);
}
if (colorInHigh.B < value.B + 1)
{
colorInHigh.B = (byte)(value.R + 1);
}
colorInLow = value;
UpdateLookupTable();
}
}
private ColorBgra colorInHigh;
public ColorBgra ColorInHigh
{
get
{
return colorInHigh;
}
set
{
if (value.R == 0)
{
value.R = 1;
}
if (value.G == 0)
{
value.G = 1;
}
if (value.B == 0)
{
value.B = 1;
}
if (colorInLow.R > value.R - 1)
{
colorInLow.R = (byte)(value.R - 1);
}
if (colorInLow.G > value.G - 1)
{
colorInLow.G = (byte)(value.R - 1);
}
if (colorInLow.B > value.B - 1)
{
colorInLow.B = (byte)(value.R - 1);
}
colorInHigh = value;
UpdateLookupTable();
}
}
private ColorBgra colorOutLow;
public ColorBgra ColorOutLow
{
get
{
return colorOutLow;
}
set
{
if (value.R == 255)
{
value.R = 254;
}
if (value.G == 255)
{
value.G = 254;
}
if (value.B == 255)
{
value.B = 254;
}
if (colorOutHigh.R < value.R + 1)
{
colorOutHigh.R = (byte)(value.R + 1);
}
if (colorOutHigh.G < value.G + 1)
{
colorOutHigh.G = (byte)(value.G + 1);
}
if (colorOutHigh.B < value.B + 1)
{
colorOutHigh.B = (byte)(value.B + 1);
}
colorOutLow = value;
UpdateLookupTable();
}
}
private ColorBgra colorOutHigh;
public ColorBgra ColorOutHigh
{
get
{
return colorOutHigh;
}
set
{
if (value.R == 0)
{
value.R = 1;
}
if (value.G == 0)
{
value.G = 1;
}
if (value.B == 0)
{
value.B = 1;
}
if (colorOutLow.R > value.R - 1)
{
colorOutLow.R = (byte)(value.R - 1);
}
if (colorOutLow.G > value.G - 1)
{
colorOutLow.G = (byte)(value.G - 1);
}
if (colorOutLow.B > value.B - 1)
{
colorOutLow.B = (byte)(value.B - 1);
}
colorOutHigh = value;
UpdateLookupTable();
}
}
private float[] gamma = new float[3];
public float GetGamma(int index)
{
if (index < 0 || index >= 3)
{
throw new ArgumentOutOfRangeException("index", index, "Index must be between 0 and 2");
}
return gamma[index];
}
public void SetGamma(int index, float val)
{
if (index < 0 || index >= 3)
{
throw new ArgumentOutOfRangeException("index", index, "Index must be between 0 and 2");
}
gamma[index] = Utility.Clamp(val, 0.1f, 10.0f);
UpdateLookupTable();
}
public bool isValid = true;
public static Level AutoFromLoMdHi(ColorBgra lo, ColorBgra md, ColorBgra hi)
{
float[] gamma = new float[3];
for (int i = 0; i < 3; i++)
{
if (lo[i] < md[i] && md[i] < hi[i])
{
gamma[i] = (float)Utility.Clamp(Math.Log(0.5, (float)(md[i] - lo[i]) / (float)(hi[i] - lo[i])), 0.1, 10.0);
}
else
{
gamma[i] = 1.0f;
}
}
return new Level(lo, hi, gamma, ColorBgra.Black, ColorBgra.White);
}
private void UpdateLookupTable()
{
for (int i = 0; i < 3; i++)
{
if (colorOutHigh[i] < colorOutLow[i] ||
colorInHigh[i] <= colorInLow[i] ||
gamma[i] < 0)
{
isValid = false;
return;
}
for (int j = 0; j < 256; j++)
{
ColorBgra col = Apply(j, j, j);
CurveB[j] = col.B;
CurveG[j] = col.G;
CurveR[j] = col.R;
}
}
}
public Level()
: this(ColorBgra.Black,
ColorBgra.White,
new float[] { 1, 1, 1 },
ColorBgra.Black,
ColorBgra.White)
{
}
public Level(ColorBgra in_lo, ColorBgra in_hi, float[] gamma, ColorBgra out_lo, ColorBgra out_hi)
{
colorInLow = in_lo;
colorInHigh = in_hi;
colorOutLow = out_lo;
colorOutHigh = out_hi;
if (gamma.Length != 3)
{
throw new ArgumentException("gamma", "gamma must be a float[3]");
}
this.gamma = gamma;
UpdateLookupTable();
}
public ColorBgra Apply(float r, float g, float b)
{
ColorBgra ret = new ColorBgra();
float[] input = new float[] { b, g, r };
for (int i = 0; i < 3; i++)
{
float v = (input[i] - colorInLow[i]);
if (v < 0)
{
ret[i] = colorOutLow[i];
}
else if (v + colorInLow[i] >= colorInHigh[i])
{
ret[i] = colorOutHigh[i];
}
else
{
ret[i] = (byte)Utility.Clamp(
colorOutLow[i] + (colorOutHigh[i] - colorOutLow[i]) * Math.Pow(v / (colorInHigh[i] - colorInLow[i]), gamma[i]),
0.0f,
255.0f);
}
}
return ret;
}
public void UnApply(ColorBgra after, float[] beforeOut, float[] slopesOut)
{
if (beforeOut.Length != 3)
{
throw new ArgumentException("before must be a float[3]", "before");
}
if (slopesOut.Length != 3)
{
throw new ArgumentException("slopes must be a float[3]", "slopes");
}
for (int i = 0; i < 3; i++)
{
beforeOut[i] = colorInLow[i] + (colorInHigh[i] - colorInLow[i]) *
(float)Math.Pow((float)(after[i] - colorOutLow[i]) / (colorOutHigh[i] - colorOutLow[i]), 1 / gamma[i]);
slopesOut[i] = (float)(colorInHigh[i] - colorInLow[i]) / ((colorOutHigh[i] - colorOutLow[i]) * gamma[i]) *
(float)Math.Pow((float)(after[i] - colorOutLow[i]) / (colorOutHigh[i] - colorOutLow[i]), 1 / gamma[i] - 1);
if (float.IsInfinity(slopesOut[i]) || float.IsNaN(slopesOut[i]))
{
slopesOut[i] = 0;
}
}
}
public object Clone()
{
Level copy = new Level(colorInLow, colorInHigh, (float[])gamma.Clone(), colorOutLow, colorOutHigh);
copy.CurveB = (byte[])this.CurveB.Clone();
copy.CurveG = (byte[])this.CurveG.Clone();
copy.CurveR = (byte[])this.CurveR.Clone();
return copy;
}
}
[Serializable]
public class HueSaturationLightness
: UnaryPixelOp
{
private int hueDelta;
private int satFactor;
private UnaryPixelOp blendOp;
public HueSaturationLightness(int hueDelta, int satDelta, int lightness)
{
this.hueDelta = hueDelta;
this.satFactor = (satDelta * 1024) / 100;
if (lightness == 0)
{
blendOp = new UnaryPixelOps.Identity();
}
else if (lightness > 0)
{
blendOp = new UnaryPixelOps.BlendConstant(ColorBgra.FromBgra(255, 255, 255, (byte)((lightness * 255) / 100)));
}
else // if (lightness < 0)
{
blendOp = new UnaryPixelOps.BlendConstant(ColorBgra.FromBgra(0, 0, 0, (byte)((-lightness * 255) / 100)));
}
}
public override ColorBgra Apply (ColorBgra color)
{
//adjust saturation
byte intensity = color.GetIntensityByte();
color.R = Utility.ClampToByte((intensity * 1024 + (color.R - intensity) * satFactor) >> 10);
color.G = Utility.ClampToByte((intensity * 1024 + (color.G - intensity) * satFactor) >> 10);
color.B = Utility.ClampToByte((intensity * 1024 + (color.B - intensity) * satFactor) >> 10);
HsvColor hsvColor = (new RgbColor(color.R, color.G, color.B)).ToHsv();
int hue = hsvColor.Hue;
hue += hueDelta;
while (hue < 0)
{
hue += 360;
}
while (hue > 360)
{
hue -= 360;
}
hsvColor.Hue = hue;
RgbColor rgbColor=hsvColor.ToRgb();
ColorBgra newColor = ColorBgra.FromBgr((byte)rgbColor.Blue, (byte)rgbColor.Green, (byte)rgbColor.Red);
newColor = blendOp.Apply(newColor);
newColor.A = color.A;
return newColor;
}
}
[Serializable]
public class PosterizePixel
: UnaryPixelOp
{
private byte[] redLevels;
private byte[] greenLevels;
private byte[] blueLevels;
public PosterizePixel(int red, int green, int blue)
{
this.redLevels = CalcLevels(red);
this.greenLevels = CalcLevels(green);
this.blueLevels = CalcLevels(blue);
}
private static byte[] CalcLevels(int levelCount)
{
byte[] t1 = new byte[levelCount];
for (int i = 1; i < levelCount; i++)
{
t1[i] = (byte)((255 * i) / (levelCount - 1));
}
byte[] levels = new byte[256];
int j = 0;
int k = 0;
for (int i = 0; i < 256; i++)
{
levels[i] = t1[j];
k += levelCount;
if (k > 255)
{
k -= 255;
j++;
}
}
return levels;
}
public override ColorBgra Apply(ColorBgra color)
{
return ColorBgra.FromBgra(blueLevels[color.B], greenLevels[color.G], redLevels[color.R], color.A);
}
public unsafe override void Apply(ColorBgra* ptr, int length)
{
while (length > 0)
{
ptr->B = this.blueLevels[ptr->B];
ptr->G = this.greenLevels[ptr->G];
ptr->R = this.redLevels[ptr->R];
++ptr;
--length;
}
}
public unsafe override void Apply(ColorBgra* dst, ColorBgra* src, int length)
{
while (length > 0)
{
dst->B = this.blueLevels[src->B];
dst->G = this.greenLevels[src->G];
dst->R = this.redLevels[src->R];
dst->A = src->A;
++dst;
++src;
--length;
}
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Chess
{
[TestClass]
public class EngineTests
{
[TestInitialize]
public void Setup() {
Game = new Game();
Game.New();
Game.SetInitials();
}
private Game Game { get; set; }
[TestMethod]
public void TestBestMoveStart() {
var engine = new Engine();
var move = engine.BestMoveAtDepth(Game, 4);
Console.WriteLine(move);
}
[TestMethod]
public void TestBestMoveQueenCaptureAlphaBeta() {
var engine = new Engine();
Assert.IsTrue(Game.TryPossibleMoveCommand(new MoveCommand(File.D, Rank._2, File.D, Rank._3)));
Assert.IsTrue(Game.TryPossibleMoveCommand(new MoveCommand(File.E, Rank._7, File.E, Rank._6)));
Assert.IsTrue(Game.TryPossibleMoveCommand(new MoveCommand(File.B, Rank._1, File.C, Rank._3)));
Assert.IsTrue(Game.TryPossibleMoveCommand(new MoveCommand(File.D, Rank._8, File.G, Rank._5)));
var move = engine.BestMoveAtDepth(Game, 2);
Console.WriteLine(move);
Assert.AreEqual("Bxg5", move.Move.ToString());
}
[TestMethod]
public void TestBestMoveBlackToPlay() {
var engine = new Engine();
Assert.IsTrue(Game.TryPossibleMoveCommand(new MoveCommand(File.B, Rank._1, File.C, Rank._3)));
Assert.IsTrue(Game.TryPossibleMoveCommand(new MoveCommand(File.C, Rank._7, File.C, Rank._6)));
Assert.IsTrue(Game.TryPossibleMoveCommand(new MoveCommand(File.C, Rank._3, File.D, Rank._5)));
var move = engine.BestMoveAtDepth(Game, 3);
Console.WriteLine(move);
Assert.AreEqual("cxd5", move.Move.ToString());
}
[TestMethod]
public void TestAttackBlackQueen() {
var engine = new Engine();
Assert.IsTrue(Game.TryPossibleMoveCommand(new MoveCommand(File.E, Rank._2, File.E, Rank._4)));
Assert.IsTrue(Game.TryPossibleMoveCommand(new MoveCommand(File.D, Rank._7, File.D, Rank._5)));
Assert.IsTrue(Game.TryPossibleMoveCommand(new MoveCommand(File.E, Rank._4, File.D, Rank._5)));
Assert.IsTrue(Game.TryPossibleMoveCommand(new MoveCommand(File.D, Rank._8, File.D, Rank._5)));
Assert.IsTrue(Game.TryPossibleMoveCommand(new MoveCommand(File.B, Rank._1, File.C, Rank._3)));
var evaluation = engine.BestMoveAtDepth(Game, 2);
Console.WriteLine(evaluation);
Assert.AreNotEqual("Qxg2", evaluation.Move.ToString());
Assert.AreNotEqual("Qxa2", evaluation.Move.ToString());
}
[TestMethod]
public void TestMiniGameWhite() {
Game.Reset();
Game.AddPiece(File.H, Rank._1, new King(Color.White));
Game.AddPiece(File.H, Rank._8, new King(Color.Black));
Game.AddPiece(File.A, Rank._1, new Knight(Color.White));
Game.AddPiece(File.B, Rank._3, new Pawn(Color.Black));
Game.AddPiece(File.D, Rank._5, new Pawn(Color.Black));
Game.WhitePlayer.CanCastleKingSide = false;
Game.BlackPlayer.CanCastleKingSide = false;
Game.SetInitials();
var ngine = new Engine();
var evaluation = ngine.BestMoveAtDepth(Game, 3);
Console.WriteLine(evaluation);
Assert.AreEqual("Nxb3", evaluation.Move.ToString());
}
[TestMethod]
public void TestMiniGameBlack() {
Game.Reset();
Game.AddPiece(File.H, Rank._1, new King(Color.White));
Game.AddPiece(File.H, Rank._8, new King(Color.Black));
Game.AddPiece(File.A, Rank._8, new Knight(Color.Black));
Game.AddPiece(File.B, Rank._6, new Pawn(Color.White));
Game.AddPiece(File.D, Rank._3, new Pawn(Color.White));
Game.CurrentPlayer = Game.BlackPlayer;
Game.WhitePlayer.CanCastleKingSide = false;
Game.BlackPlayer.CanCastleKingSide = false;
Game.SetInitials();
var ngine = new Engine();
var evaluation = ngine.BestMoveAtDepth(Game, 4);
Console.WriteLine(evaluation);
Assert.AreEqual("Nxb6", evaluation.Move.ToString());
}
[TestMethod]
public void TestBlackToPlay_WhiteMatesInOne() {
LoadFile("TestGames\\mated.txt");
var engine = new Engine();
var evaluation = engine.BestMoveAtDepth(Game, 3);
Console.WriteLine(evaluation);
Assert.IsNotNull(evaluation);
}
[TestMethod]
public void TestBlackToPlay_MatesInOne() {
LoadFile("TestGames\\white_mated.txt");
var engine = new Engine();
var bestMove = engine.BestMoveAtDepth(Game, 2);
Assert.IsNotNull(bestMove);
Assert.AreEqual("Qh4#", bestMove.Move.ToString());
}
private void LoadFile(string fileName) {
var gameFile = GameFile.Load(fileName);
foreach (var moveCommand in gameFile.MoveCommands)
Assert.IsTrue(Game.TryPossibleMoveCommand(moveCommand));
}
[TestMethod]
public void WhiteToPlay_MatesInTwo() {
var game = new Game();
game.New();
game.Reset();
game
.AddPiece("a8bR").AddPiece("b8bN").AddPiece("c8bB").AddPiece("d8bQ").AddPiece("e8bK").AddPiece("f8bB").AddPiece("g8bN")
.AddPiece("a7bP").AddPiece("b7bP").AddPiece("c7bP").AddPiece("d7bP").AddPiece("e7bP").AddPiece("h7bP")
.AddPiece("g6pP")
.AddPiece("g5bP").AddPiece("h5bR")
.AddPiece("d4wP").AddPiece("e4wQ").AddPiece("f4bP")
.AddPiece("d3wB").AddPiece("e3wP").AddPiece("g3wB")
.AddPiece("a2wP").AddPiece("b2wP").AddPiece("c2wP").AddPiece("f2wP").AddPiece("g2wP").AddPiece("h2wP")
.AddPiece("a1wR").AddPiece("b1wN").AddPiece("e1wK").AddPiece("g1wN").AddPiece("h1wR");
game.WhitePlayer.CanCastleKingSide = false;
game.BlackPlayer.CanCastleKingSide = false;
game.CurrentPlayer = game.WhitePlayer;
game.SetInitials();
var engine = new Engine();
var evaluation = engine.BestMoveAtDepth(game, 3);
Console.WriteLine(evaluation);
Assert.AreEqual("Qxg6+", evaluation.Move.ToString());
}
[TestMethod]
public void BlackToPlay_MateInTwo() {
var game = new Game();
game.New();
game.Reset();
game
.AddPiece("a8bR").AddPiece("e8bK").AddPiece("f8bB")
.AddPiece("c7bP").AddPiece("d7bP").AddPiece("f7bP")
.AddPiece("a6bP").AddPiece("g6bQ")
.AddPiece("b5bP").AddPiece("e5wP")
.AddPiece("h4wQ")
.AddPiece("b3wP").AddPiece("e3wB").AddPiece("f3bB").AddPiece("h3wP")
.AddPiece("b2wP").AddPiece("c2wP").AddPiece("e2wN").AddPiece("f2wP").AddPiece("g2bR")
.AddPiece("a1wR").AddPiece("e1wR").AddPiece("f1wK");
game.CurrentPlayer = game.BlackPlayer;
DisableCastling(game);
game.SetInitials();
var engine = new Engine();
var timer = Stopwatch.StartNew();
var evaluation = engine.BestMoveAtDepth(game, 3);
timer.Stop();
#if DEBUG
var timeLimit = 12000;
#else
var timeLimit = 12000;
#endif
Console.WriteLine(evaluation.ToString());
Assert.AreEqual("Rg1+", evaluation.Move.ToString());
Assert.IsTrue(timer.ElapsedMilliseconds < timeLimit, "timer.ElapsedMilliseconds < timeLimit");
}
internal static void DisableCastling(Game game)
{
game.WhitePlayer.CanCastleKingSide = false;
game.BlackPlayer.CanCastleKingSide = false;
game.WhitePlayer.CanCastleQueenSide = false;
game.BlackPlayer.CanCastleQueenSide = false;
}
[TestMethod]
public void MateInThreeWhiteToPlay() {
var game = new Game();
game.New();
game.Reset();
game
.AddPiece("g8bK")
.AddPiece("a7wR").AddPiece("b7wR").AddPiece("c7bP")
.AddPiece("f6wK").AddPiece("g6wN")
.AddPiece("f5wP")
.AddPiece("b2bP").AddPiece("c3bR").AddPiece("e3bR").AddPiece("f3bN");
DisableCastling(game);
game.SetInitials();
var engine = new Engine();
var move = engine.BestMoveAtDepth(game, 5);
Console.WriteLine(move);
var expects = new[] { "Rb8+", "Ra8+" };
Assert.IsTrue(expects.Contains(move.Move.ToString()));
}
[TestMethod]
public void MateInThreeBlackToPlay() {
var game = new Game();
game.New();
game.Reset();
game
.AddPiece("b8bK")
.AddPiece("a7bP").AddPiece("g7bP").AddPiece("h7bP")
.AddPiece("b6bP").AddPiece("d6bQ").AddPiece("f6bP")
.AddPiece("c5bP")
.AddPiece("d4wP").AddPiece("f4bN").AddPiece("g4wP").AddPiece("h4wP")
.AddPiece("a3wQ").AddPiece("c3wP").AddPiece("f3wP").AddPiece("g3wK")
.AddPiece("a2wP").AddPiece("e2bR")
.AddPiece("g1wR").AddPiece("h1wR");
game.WhitePlayer.CanCastleKingSide = false;
game.BlackPlayer.CanCastleQueenSide = false;
game.CurrentPlayer = game.BlackPlayer;
game.SetInitials();
var engine = new Engine();
var move = engine.BestMoveAtDepth(game, 5);
Console.WriteLine(move.ToString());
Assert.AreEqual("Nh5+", move.Move.ToString());
}
[TestMethod]
public void TestGamePerformance() {
#if DEBUG
Assert.Fail("Run this test in release configuration");
#endif
var gameFile = GameFile.Load("TestGames\\performance1.txt");
Game.Load(gameFile);
var engine = new Engine();
var evaluation = engine.BestMoveDeepeningSearch(Game, TimeSpan.FromSeconds(10));
Console.WriteLine(evaluation);
}
[TestMethod]
public void RookKingEndgame()
{
Game.New();
Game.Reset();
Game.AddPiece("e5bK").AddPiece("c3bR").AddPiece("g5wK");
Game.CurrentPlayer = Game.BlackPlayer;
Game.SetInitials();
Game.BlackPlayer.CanCastleKingSide = true;
Game.WhitePlayer.CanCastleKingSide = true;
var engine = new Engine();
var move = engine.BestMoveAtDepth(Game, 3);
Console.WriteLine(move.ToString());
Assert.AreEqual("Rg3+", move.Move.ToString());
}
[TestMethod]
public void Perft()
{
Game.New();
var engine = new Engine();
var nodes = engine.Perft(Game, 5);
Console.WriteLine(nodes);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Dynamic;
using System.Linq;
using SqlKata.Compilers;
using SqlKata.Tests.Infrastructure;
using Xunit;
namespace SqlKata.Tests
{
public class InsertTests : TestSupport
{
private class Account
{
public Account(string name, string currency = null, string created_at = null, string color = null)
{
this.name = name ?? throw new ArgumentNullException(nameof(name));
this.Currency = currency;
this.color = color;
}
public string name { get; set; }
[Column("currency_id")]
public string Currency { get; set; }
[Ignore]
public string color { get; set; }
}
[Fact]
public void InsertObject()
{
var query = new Query("Table")
.AsInsert(
new
{
Name = "The User",
Age = new DateTime(2018, 1, 1, 0, 0, 0, DateTimeKind.Utc),
});
var c = Compile(query);
Assert.Equal(
"INSERT INTO [Table] ([Name], [Age]) VALUES ('The User', '2018-01-01')",
c[EngineCodes.SqlServer]);
Assert.Equal(
"INSERT INTO \"TABLE\" (\"NAME\", \"AGE\") VALUES ('The User', '2018-01-01')",
c[EngineCodes.Firebird]);
}
[Fact]
public void InsertFromSubQueryWithCte()
{
var query = new Query("expensive_cars")
.With("old_cards", new Query("all_cars").Where("year", "<", 2000))
.AsInsert(
new[] { "name", "model", "year" },
new Query("old_cars").Where("price", ">", 100).ForPage(2, 10));
var c = Compile(query);
Assert.Equal(
"WITH [old_cards] AS (SELECT * FROM [all_cars] WHERE [year] < 2000)\nINSERT INTO [expensive_cars] ([name], [model], [year]) SELECT * FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY (SELECT 0)) AS [row_num] FROM [old_cars] WHERE [price] > 100) AS [results_wrapper] WHERE [row_num] BETWEEN 11 AND 20",
c[EngineCodes.SqlServer]);
Assert.Equal(
"WITH `old_cards` AS (SELECT * FROM `all_cars` WHERE `year` < 2000)\nINSERT INTO `expensive_cars` (`name`, `model`, `year`) SELECT * FROM `old_cars` WHERE `price` > 100 LIMIT 10 OFFSET 10",
c[EngineCodes.MySql]);
Assert.Equal(
"WITH \"old_cards\" AS (SELECT * FROM \"all_cars\" WHERE \"year\" < 2000)\nINSERT INTO \"expensive_cars\" (\"name\", \"model\", \"year\") SELECT * FROM \"old_cars\" WHERE \"price\" > 100 LIMIT 10 OFFSET 10",
c[EngineCodes.PostgreSql]);
}
[Fact]
public void InsertMultiRecords()
{
var query = new Query("expensive_cars")
.AsInsert(
new[] { "name", "brand", "year" },
new[]
{
new object[] { "Chiron", "Bugatti", null },
new object[] { "Huayra", "Pagani", 2012 },
new object[] { "Reventon roadster", "Lamborghini", 2009 }
});
var c = Compile(query);
Assert.Equal(
"INSERT INTO [expensive_cars] ([name], [brand], [year]) VALUES ('Chiron', 'Bugatti', NULL), ('Huayra', 'Pagani', 2012), ('Reventon roadster', 'Lamborghini', 2009)",
c[EngineCodes.SqlServer]);
Assert.Equal(
"INSERT INTO \"EXPENSIVE_CARS\" (\"NAME\", \"BRAND\", \"YEAR\") SELECT 'Chiron', 'Bugatti', NULL FROM RDB$DATABASE UNION ALL SELECT 'Huayra', 'Pagani', 2012 FROM RDB$DATABASE UNION ALL SELECT 'Reventon roadster', 'Lamborghini', 2009 FROM RDB$DATABASE",
c[EngineCodes.Firebird]);
}
[Fact]
public void InsertWithNullValues()
{
var query = new Query("Books")
.AsInsert(
new[] { "Id", "Author", "ISBN", "Date" },
new object[] { 1, "Author 1", "123456", null });
var c = Compile(query);
Assert.Equal("INSERT INTO [Books] ([Id], [Author], [ISBN], [Date]) VALUES (1, 'Author 1', '123456', NULL)",
c[EngineCodes.SqlServer]);
Assert.Equal(
"INSERT INTO \"BOOKS\" (\"ID\", \"AUTHOR\", \"ISBN\", \"DATE\") VALUES (1, 'Author 1', '123456', NULL)",
c[EngineCodes.Firebird]);
}
[Fact]
public void InsertWithEmptyString()
{
var query = new Query("Books")
.AsInsert(
new[] { "Id", "Author", "ISBN", "Description" },
new object[] { 1, "Author 1", "123456", "" });
var c = Compile(query);
Assert.Equal(
"INSERT INTO [Books] ([Id], [Author], [ISBN], [Description]) VALUES (1, 'Author 1', '123456', '')",
c[EngineCodes.SqlServer]);
Assert.Equal(
"INSERT INTO \"BOOKS\" (\"ID\", \"AUTHOR\", \"ISBN\", \"DESCRIPTION\") VALUES (1, 'Author 1', '123456', '')",
c[EngineCodes.Firebird]);
}
[Fact]
public void InsertWithByteArray()
{
var fauxImagebytes = new byte[] { 0x1, 0x3, 0x3, 0x7 };
var query = new Query("Books")
.AsInsert(
new[] { "Id", "CoverImageBytes" },
new object[]
{
1,
fauxImagebytes
});
var c = Compilers.Compile(query);
Assert.All(c.Values, a => Assert.Equal(2, a.NamedBindings.Count));
var exemplar = c[EngineCodes.SqlServer];
Assert.Equal("INSERT INTO [Books] ([Id], [CoverImageBytes]) VALUES (?, ?)", exemplar.RawSql);
Assert.Equal("INSERT INTO [Books] ([Id], [CoverImageBytes]) VALUES (@p0, @p1)", exemplar.Sql);
}
[Fact]
public void InsertWithIgnoreAndColumnProperties()
{
var account = new Account(name: $"popular", color: $"blue", currency: "US");
var query = new Query("Account").AsInsert(account);
var c = Compile(query);
Assert.Equal(
"INSERT INTO [Account] ([name], [currency_id]) VALUES ('popular', 'US')",
c[EngineCodes.SqlServer]);
Assert.Equal(
"INSERT INTO \"ACCOUNT\" (\"NAME\", \"CURRENCY_ID\") VALUES ('popular', 'US')",
c[EngineCodes.Firebird]);
}
[Fact]
public void InsertFromRaw()
{
var query = new Query()
.FromRaw("Table.With.Dots")
.AsInsert(
new
{
Name = "The User",
Age = new DateTime(2018, 1, 1, 0, 0, 0, DateTimeKind.Utc),
});
var c = Compile(query);
Assert.Equal(
"INSERT INTO Table.With.Dots ([Name], [Age]) VALUES ('The User', '2018-01-01')",
c[EngineCodes.SqlServer]);
}
[Fact]
public void InsertFromQueryShouldFail()
{
var query = new Query()
.From(new Query("InnerTable"))
.AsInsert(
new
{
Name = "The User",
Age = new DateTime(2018, 1, 1, 0, 0, 0, DateTimeKind.Utc),
});
Assert.Throws<InvalidOperationException>(() =>
{
Compile(query);
});
}
[Fact]
public void InsertKeyValuePairs()
{
var dictionaryUser = new Dictionary<string, object>
{
{ "Name", "The User" },
{ "Age", new DateTime(2018, 1, 1, 0, 0, 0, DateTimeKind.Utc) },
}
.ToArray();
var query = new Query("Table")
.AsInsert(dictionaryUser);
var c = Compile(query);
Assert.Equal(
"INSERT INTO [Table] ([Name], [Age]) VALUES ('The User', '2018-01-01')",
c[EngineCodes.SqlServer]);
Assert.Equal(
"INSERT INTO \"TABLE\" (\"NAME\", \"AGE\") VALUES ('The User', '2018-01-01')",
c[EngineCodes.Firebird]);
}
[Fact]
public void InsertDictionary()
{
var dictionaryUser = new Dictionary<string, object> {
{ "Name", "The User" },
{ "Age", new DateTime(2018, 1, 1, 0, 0, 0, DateTimeKind.Utc) },
};
var query = new Query("Table")
.AsInsert(dictionaryUser);
var c = Compile(query);
Assert.Equal(
"INSERT INTO [Table] ([Name], [Age]) VALUES ('The User', '2018-01-01')",
c[EngineCodes.SqlServer]);
Assert.Equal(
"INSERT INTO \"TABLE\" (\"NAME\", \"AGE\") VALUES ('The User', '2018-01-01')",
c[EngineCodes.Firebird]);
}
[Fact]
public void InsertReadOnlyDictionary()
{
var dictionaryUser = new ReadOnlyDictionary<string, object>(
new Dictionary<string, object>
{
{ "Name", "The User" },
{ "Age", new DateTime(2018, 1, 1, 0, 0, 0, DateTimeKind.Utc) },
});
var query = new Query("Table")
.AsInsert(dictionaryUser);
var c = Compile(query);
Assert.Equal(
"INSERT INTO [Table] ([Name], [Age]) VALUES ('The User', '2018-01-01')",
c[EngineCodes.SqlServer]);
Assert.Equal(
"INSERT INTO \"TABLE\" (\"NAME\", \"AGE\") VALUES ('The User', '2018-01-01')",
c[EngineCodes.Firebird]);
}
[Fact]
public void InsertExpandoObject()
{
dynamic expandoUser = new ExpandoObject();
expandoUser.Name = "The User";
expandoUser.Age = new DateTime(2018, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var query = new Query("Table")
.AsInsert(expandoUser);
var c = Compile(query);
Assert.Equal(
"INSERT INTO [Table] ([Name], [Age]) VALUES ('The User', '2018-01-01')",
c[EngineCodes.SqlServer]);
Assert.Equal(
"INSERT INTO \"TABLE\" (\"NAME\", \"AGE\") VALUES ('The User', '2018-01-01')",
c[EngineCodes.Firebird]);
}
}
}
| |
using System.Diagnostics.CodeAnalysis;
using Robust.Client.Graphics;
using Robust.Client.Input;
using Robust.Client.UserInterface.Controls;
using Robust.Shared.Input;
using Robust.Shared.Localization;
using Robust.Shared.Maths;
using Robust.Shared.Utility;
namespace Content.Client.HUD.UI;
internal sealed class TopButton : ContainerButton
{
public const string StyleClassLabelTopButton = "topButtonLabel";
public const string StyleClassRedTopButton = "topButtonLabel";
private const float CustomTooltipDelay = 0.4f;
private static readonly Color ColorNormal = Color.FromHex("#7b7e9e");
private static readonly Color ColorRedNormal = Color.FromHex("#FEFEFE");
private static readonly Color ColorHovered = Color.FromHex("#9699bb");
private static readonly Color ColorRedHovered = Color.FromHex("#FFFFFF");
private static readonly Color ColorPressed = Color.FromHex("#789B8C");
private const float VertPad = 8f;
private Color NormalColor => HasStyleClass(StyleClassRedTopButton) ? ColorRedNormal : ColorNormal;
private Color HoveredColor => HasStyleClass(StyleClassRedTopButton) ? ColorRedHovered : ColorHovered;
private readonly TextureRect _textureRect;
private readonly Label _label;
private readonly BoundKeyFunction _function;
private readonly IInputManager _inputManager;
public TopButton(Texture texture, BoundKeyFunction function, IInputManager inputManager)
{
_function = function;
_inputManager = inputManager;
TooltipDelay = CustomTooltipDelay;
AddChild(
new BoxContainer
{
Orientation = BoxContainer.LayoutOrientation.Vertical,
Children =
{
(_textureRect = new TextureRect
{
TextureScale = (0.5f, 0.5f),
Texture = texture,
HorizontalAlignment = HAlignment.Center,
VerticalAlignment = VAlignment.Center,
VerticalExpand = true,
Margin = new Thickness(0, VertPad),
ModulateSelfOverride = NormalColor,
Stretch = TextureRect.StretchMode.KeepCentered
}),
(_label = new Label
{
Text = ShortKeyName(_function),
HorizontalAlignment = HAlignment.Center,
ModulateSelfOverride = NormalColor,
StyleClasses = {StyleClassLabelTopButton}
})
}
}
);
ToggleMode = true;
}
protected override void EnteredTree()
{
_inputManager.OnKeyBindingAdded += OnKeyBindingChanged;
_inputManager.OnKeyBindingRemoved += OnKeyBindingChanged;
_inputManager.OnInputModeChanged += OnKeyBindingChanged;
}
protected override void ExitedTree()
{
_inputManager.OnKeyBindingAdded -= OnKeyBindingChanged;
_inputManager.OnKeyBindingRemoved -= OnKeyBindingChanged;
_inputManager.OnInputModeChanged -= OnKeyBindingChanged;
}
private void OnKeyBindingChanged(IKeyBinding obj)
{
_label.Text = ShortKeyName(_function);
}
private void OnKeyBindingChanged()
{
_label.Text = ShortKeyName(_function);
}
private string ShortKeyName(BoundKeyFunction keyFunction)
{
// need to use shortened key names so they fit in the buttons.
return TryGetShortKeyName(keyFunction, out var name) ? Loc.GetString(name) : " ";
}
private bool TryGetShortKeyName(BoundKeyFunction keyFunction, [NotNullWhen(true)] out string? name)
{
if (_inputManager.TryGetKeyBinding(keyFunction, out var binding))
{
// can't possibly fit a modifier key in the top button, so omit it
var key = binding.BaseKey;
if (binding.Mod1 != Keyboard.Key.Unknown || binding.Mod2 != Keyboard.Key.Unknown ||
binding.Mod3 != Keyboard.Key.Unknown)
{
name = null;
return false;
}
name = null;
name = key switch
{
Keyboard.Key.Apostrophe => "'",
Keyboard.Key.Comma => ",",
Keyboard.Key.Delete => "Del",
Keyboard.Key.Down => "Dwn",
Keyboard.Key.Escape => "Esc",
Keyboard.Key.Equal => "=",
Keyboard.Key.Home => "Hom",
Keyboard.Key.Insert => "Ins",
Keyboard.Key.Left => "Lft",
Keyboard.Key.Menu => "Men",
Keyboard.Key.Minus => "-",
Keyboard.Key.Num0 => "0",
Keyboard.Key.Num1 => "1",
Keyboard.Key.Num2 => "2",
Keyboard.Key.Num3 => "3",
Keyboard.Key.Num4 => "4",
Keyboard.Key.Num5 => "5",
Keyboard.Key.Num6 => "6",
Keyboard.Key.Num7 => "7",
Keyboard.Key.Num8 => "8",
Keyboard.Key.Num9 => "9",
Keyboard.Key.Pause => "||",
Keyboard.Key.Period => ".",
Keyboard.Key.Return => "Ret",
Keyboard.Key.Right => "Rgt",
Keyboard.Key.Slash => "/",
Keyboard.Key.Space => "Spc",
Keyboard.Key.Tab => "Tab",
Keyboard.Key.Tilde => "~",
Keyboard.Key.BackSlash => "\\",
Keyboard.Key.BackSpace => "Bks",
Keyboard.Key.LBracket => "[",
Keyboard.Key.MouseButton4 => "M4",
Keyboard.Key.MouseButton5 => "M5",
Keyboard.Key.MouseButton6 => "M6",
Keyboard.Key.MouseButton7 => "M7",
Keyboard.Key.MouseButton8 => "M8",
Keyboard.Key.MouseButton9 => "M9",
Keyboard.Key.MouseLeft => "ML",
Keyboard.Key.MouseMiddle => "MM",
Keyboard.Key.MouseRight => "MR",
Keyboard.Key.NumpadDecimal => "N.",
Keyboard.Key.NumpadDivide => "N/",
Keyboard.Key.NumpadEnter => "Ent",
Keyboard.Key.NumpadMultiply => "*",
Keyboard.Key.NumpadNum0 => "0",
Keyboard.Key.NumpadNum1 => "1",
Keyboard.Key.NumpadNum2 => "2",
Keyboard.Key.NumpadNum3 => "3",
Keyboard.Key.NumpadNum4 => "4",
Keyboard.Key.NumpadNum5 => "5",
Keyboard.Key.NumpadNum6 => "6",
Keyboard.Key.NumpadNum7 => "7",
Keyboard.Key.NumpadNum8 => "8",
Keyboard.Key.NumpadNum9 => "9",
Keyboard.Key.NumpadSubtract => "N-",
Keyboard.Key.PageDown => "PgD",
Keyboard.Key.PageUp => "PgU",
Keyboard.Key.RBracket => "]",
Keyboard.Key.SemiColon => ";",
_ => DefaultShortKeyName(keyFunction)
};
return name != null;
}
name = null;
return false;
}
private string? DefaultShortKeyName(BoundKeyFunction keyFunction)
{
var name = FormattedMessage.EscapeText(_inputManager.GetKeyFunctionButtonString(keyFunction));
return name.Length > 3 ? null : name;
}
protected override void StylePropertiesChanged()
{
// colors of children depend on style, so ensure we update when style is changed
base.StylePropertiesChanged();
UpdateChildColors();
}
private void UpdateChildColors()
{
if (_label == null || _textureRect == null) return;
switch (DrawMode)
{
case DrawModeEnum.Normal:
_textureRect.ModulateSelfOverride = NormalColor;
_label.ModulateSelfOverride = NormalColor;
break;
case DrawModeEnum.Pressed:
_textureRect.ModulateSelfOverride = ColorPressed;
_label.ModulateSelfOverride = ColorPressed;
break;
case DrawModeEnum.Hover:
_textureRect.ModulateSelfOverride = HoveredColor;
_label.ModulateSelfOverride = HoveredColor;
break;
case DrawModeEnum.Disabled:
break;
}
}
protected override void DrawModeChanged()
{
base.DrawModeChanged();
UpdateChildColors();
}
}
| |
using System;
using System.Collections.Generic;
namespace LibGit2Sharp
{
/// <summary>
/// A Repository is the primary interface into a git repository
/// </summary>
public interface IRepository : IDisposable
{
/// <summary>
/// Shortcut to return the branch pointed to by HEAD
/// </summary>
Branch Head { get; }
/// <summary>
/// Provides access to the configuration settings for this repository.
/// </summary>
Configuration Config { get; }
/// <summary>
/// Gets the index.
/// </summary>
Index Index { get; }
/// <summary>
/// Lookup and enumerate references in the repository.
/// </summary>
ReferenceCollection Refs { get; }
/// <summary>
/// Lookup and enumerate commits in the repository.
/// Iterating this collection directly starts walking from the HEAD.
/// </summary>
IQueryableCommitLog Commits { get; }
/// <summary>
/// Lookup and enumerate branches in the repository.
/// </summary>
BranchCollection Branches { get; }
/// <summary>
/// Lookup and enumerate tags in the repository.
/// </summary>
TagCollection Tags { get; }
/// <summary>
/// Provides high level information about this repository.
/// </summary>
RepositoryInformation Info { get; }
/// <summary>
/// Provides access to diffing functionalities to show changes between the working tree and the index or a tree, changes between the index and a tree, changes between two trees, or changes between two files on disk.
/// </summary>
Diff Diff { get; }
/// <summary>
/// Gets the database.
/// </summary>
ObjectDatabase ObjectDatabase { get; }
/// <summary>
/// Lookup notes in the repository.
/// </summary>
NoteCollection Notes { get; }
/// <summary>
/// Submodules in the repository.
/// </summary>
SubmoduleCollection Submodules { get; }
/// <summary>
/// Worktrees in the repository.
/// </summary>
WorktreeCollection Worktrees { get; }
/// <summary>
/// Checkout the specified tree.
/// </summary>
/// <param name="tree">The <see cref="Tree"/> to checkout.</param>
/// <param name="paths">The paths to checkout.</param>
/// <param name="opts">Collection of parameters controlling checkout behavior.</param>
void Checkout(Tree tree, IEnumerable<string> paths, CheckoutOptions opts);
/// <summary>
/// Updates specifed paths in the index and working directory with the versions from the specified branch, reference, or SHA.
/// <para>
/// This method does not switch branches or update the current repository HEAD.
/// </para>
/// </summary>
/// <param name = "committishOrBranchSpec">A revparse spec for the commit or branch to checkout paths from.</param>
/// <param name="paths">The paths to checkout.</param>
/// <param name="checkoutOptions">Collection of parameters controlling checkout behavior.</param>
void CheckoutPaths(string committishOrBranchSpec, IEnumerable<string> paths, CheckoutOptions checkoutOptions);
/// <summary>
/// Try to lookup an object by its <see cref="ObjectId"/>. If no matching object is found, null will be returned.
/// </summary>
/// <param name="id">The id to lookup.</param>
/// <returns>The <see cref="GitObject"/> or null if it was not found.</returns>
GitObject Lookup(ObjectId id);
/// <summary>
/// Try to lookup an object by its sha or a reference canonical name. If no matching object is found, null will be returned.
/// </summary>
/// <param name="objectish">A revparse spec for the object to lookup.</param>
/// <returns>The <see cref="GitObject"/> or null if it was not found.</returns>
GitObject Lookup(string objectish);
/// <summary>
/// Try to lookup an object by its <see cref="ObjectId"/> and <see cref="ObjectType"/>. If no matching object is found, null will be returned.
/// </summary>
/// <param name="id">The id to lookup.</param>
/// <param name="type">The kind of GitObject being looked up</param>
/// <returns>The <see cref="GitObject"/> or null if it was not found.</returns>
GitObject Lookup(ObjectId id, ObjectType type);
/// <summary>
/// Try to lookup an object by its sha or a reference canonical name and <see cref="ObjectType"/>. If no matching object is found, null will be returned.
/// </summary>
/// <param name="objectish">A revparse spec for the object to lookup.</param>
/// <param name="type">The kind of <see cref="GitObject"/> being looked up</param>
/// <returns>The <see cref="GitObject"/> or null if it was not found.</returns>
GitObject Lookup(string objectish, ObjectType type);
/// <summary>
/// Stores the content of the <see cref="Repository.Index"/> as a new <see cref="LibGit2Sharp.Commit"/> into the repository.
/// The tip of the <see cref="Repository.Head"/> will be used as the parent of this new Commit.
/// Once the commit is created, the <see cref="Repository.Head"/> will move forward to point at it.
/// </summary>
/// <param name="message">The description of why a change was made to the repository.</param>
/// <param name="author">The <see cref="Signature"/> of who made the change.</param>
/// <param name="committer">The <see cref="Signature"/> of who added the change to the repository.</param>
/// <param name="options">The <see cref="CommitOptions"/> that specify the commit behavior.</param>
/// <returns>The generated <see cref="LibGit2Sharp.Commit"/>.</returns>
Commit Commit(string message, Signature author, Signature committer, CommitOptions options);
/// <summary>
/// Sets the current <see cref="Head"/> to the specified commit and optionally resets the <see cref="Index"/> and
/// the content of the working tree to match.
/// </summary>
/// <param name="resetMode">Flavor of reset operation to perform.</param>
/// <param name="commit">The target commit object.</param>
void Reset(ResetMode resetMode, Commit commit);
/// <summary>
/// Sets <see cref="Head"/> to the specified commit and optionally resets the <see cref="Index"/> and
/// the content of the working tree to match.
/// </summary>
/// <param name="resetMode">Flavor of reset operation to perform.</param>
/// <param name="commit">The target commit object.</param>
/// <param name="options">Collection of parameters controlling checkout behavior.</param>
void Reset(ResetMode resetMode, Commit commit, CheckoutOptions options);
/// <summary>
/// Clean the working tree by removing files that are not under version control.
/// </summary>
void RemoveUntrackedFiles();
/// <summary>
/// Revert the specified commit.
/// </summary>
/// <param name="commit">The <see cref="Commit"/> to revert.</param>
/// <param name="reverter">The <see cref="Signature"/> of who is performing the reverte.</param>
/// <param name="options"><see cref="RevertOptions"/> controlling revert behavior.</param>
/// <returns>The result of the revert.</returns>
RevertResult Revert(Commit commit, Signature reverter, RevertOptions options);
/// <summary>
/// Merge changes from commit into the branch pointed at by HEAD..
/// </summary>
/// <param name="commit">The commit to merge into the branch pointed at by HEAD.</param>
/// <param name="merger">The <see cref="Signature"/> of who is performing the merge.</param>
/// <param name="options">Specifies optional parameters controlling merge behavior; if null, the defaults are used.</param>
/// <returns>The <see cref="MergeResult"/> of the merge.</returns>
MergeResult Merge(Commit commit, Signature merger, MergeOptions options);
/// <summary>
/// Merges changes from branch into the branch pointed at by HEAD..
/// </summary>
/// <param name="branch">The branch to merge into the branch pointed at by HEAD.</param>
/// <param name="merger">The <see cref="Signature"/> of who is performing the merge.</param>
/// <param name="options">Specifies optional parameters controlling merge behavior; if null, the defaults are used.</param>
/// <returns>The <see cref="MergeResult"/> of the merge.</returns>
MergeResult Merge(Branch branch, Signature merger, MergeOptions options);
/// <summary>
/// Merges changes from the commit into the branch pointed at by HEAD.
/// </summary>
/// <param name="committish">The commit to merge into branch pointed at by HEAD.</param>
/// <param name="merger">The <see cref="Signature"/> of who is performing the merge.</param>
/// <param name="options">Specifies optional parameters controlling merge behavior; if null, the defaults are used.</param>
/// <returns>The <see cref="MergeResult"/> of the merge.</returns>
MergeResult Merge(string committish, Signature merger, MergeOptions options);
/// <summary>
/// Access to Rebase functionality.
/// </summary>
Rebase Rebase { get; }
/// <summary>
/// Merge the reference that was recently fetched. This will merge
/// the branch on the fetched remote that corresponded to the
/// current local branch when we did the fetch. This is the
/// second step in performing a pull operation (after having
/// performed said fetch).
/// </summary>
/// <param name="merger">The <see cref="Signature"/> of who is performing the merge.</param>
/// <param name="options">Specifies optional parameters controlling merge behavior; if null, the defaults are used.</param>
/// <returns>The <see cref="MergeResult"/> of the merge.</returns>
MergeResult MergeFetchedRefs(Signature merger, MergeOptions options);
/// <summary>
/// Cherry picks changes from the commit into the branch pointed at by HEAD.
/// </summary>
/// <param name="commit">The commit to cherry pick into branch pointed at by HEAD.</param>
/// <param name="committer">The <see cref="Signature"/> of who is performing the cherry pick.</param>
/// <param name="options">Specifies optional parameters controlling cherry pick behavior; if null, the defaults are used.</param>
/// <returns>The <see cref="MergeResult"/> of the merge.</returns>
CherryPickResult CherryPick(Commit commit, Signature committer, CherryPickOptions options);
/// <summary>
/// Manipulate the currently ignored files.
/// </summary>
Ignore Ignore { get; }
/// <summary>
/// Provides access to network functionality for a repository.
/// </summary>
Network Network { get; }
///<summary>
/// Lookup and enumerate stashes in the repository.
///</summary>
StashCollection Stashes { get; }
/// <summary>
/// Find where each line of a file originated.
/// </summary>
/// <param name="path">Path of the file to blame.</param>
/// <param name="options">Specifies optional parameters; if null, the defaults are used.</param>
/// <returns>The blame for the file.</returns>
BlameHunkCollection Blame(string path, BlameOptions options);
/// <summary>
/// Retrieves the state of a file in the working directory, comparing it against the staging area and the latest commit.
/// </summary>
/// <param name="filePath">The relative path within the working directory to the file.</param>
/// <returns>A <see cref="FileStatus"/> representing the state of the <paramref name="filePath"/> parameter.</returns>
FileStatus RetrieveStatus(string filePath);
/// <summary>
/// Retrieves the state of all files in the working directory, comparing them against the staging area and the latest commit.
/// </summary>
/// <param name="options">If set, the options that control the status investigation.</param>
/// <returns>A <see cref="RepositoryStatus"/> holding the state of all the files.</returns>
RepositoryStatus RetrieveStatus(StatusOptions options);
/// <summary>
/// Finds the most recent annotated tag that is reachable from a commit.
/// <para>
/// If the tag points to the commit, then only the tag is shown. Otherwise,
/// it suffixes the tag name with the number of additional commits on top
/// of the tagged object and the abbreviated object name of the most recent commit.
/// </para>
/// <para>
/// Optionally, the <paramref name="options"/> parameter allow to tweak the
/// search strategy (considering lightweight tags, or even branches as reference points)
/// and the formatting of the returned identifier.
/// </para>
/// </summary>
/// <param name="commit">The commit to be described.</param>
/// <param name="options">Determines how the commit will be described.</param>
/// <returns>A descriptive identifier for the commit based on the nearest annotated tag.</returns>
string Describe(Commit commit, DescribeOptions options);
/// <summary>
/// Parse an extended SHA-1 expression and retrieve the object and the reference
/// mentioned in the revision (if any).
/// </summary>
/// <param name="revision">An extended SHA-1 expression for the object to look up</param>
/// <param name="reference">The reference mentioned in the revision (if any)</param>
/// <param name="obj">The object which the revision resolves to</param>
void RevParse(string revision, out Reference reference, out GitObject obj);
}
}
| |
// 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 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.V10.Services
{
/// <summary>Settings for <see cref="ExperimentArmServiceClient"/> instances.</summary>
public sealed partial class ExperimentArmServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="ExperimentArmServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="ExperimentArmServiceSettings"/>.</returns>
public static ExperimentArmServiceSettings GetDefault() => new ExperimentArmServiceSettings();
/// <summary>Constructs a new <see cref="ExperimentArmServiceSettings"/> object with default settings.</summary>
public ExperimentArmServiceSettings()
{
}
private ExperimentArmServiceSettings(ExperimentArmServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
MutateExperimentArmsSettings = existing.MutateExperimentArmsSettings;
OnCopy(existing);
}
partial void OnCopy(ExperimentArmServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>ExperimentArmServiceClient.MutateExperimentArms</c> and
/// <c>ExperimentArmServiceClient.MutateExperimentArmsAsync</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 MutateExperimentArmsSettings { 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="ExperimentArmServiceSettings"/> object.</returns>
public ExperimentArmServiceSettings Clone() => new ExperimentArmServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="ExperimentArmServiceClient"/> to provide simple configuration of credentials,
/// endpoint etc.
/// </summary>
internal sealed partial class ExperimentArmServiceClientBuilder : gaxgrpc::ClientBuilderBase<ExperimentArmServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public ExperimentArmServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public ExperimentArmServiceClientBuilder()
{
UseJwtAccessWithScopes = ExperimentArmServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref ExperimentArmServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<ExperimentArmServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override ExperimentArmServiceClient Build()
{
ExperimentArmServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<ExperimentArmServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<ExperimentArmServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private ExperimentArmServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return ExperimentArmServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<ExperimentArmServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return ExperimentArmServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => ExperimentArmServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => ExperimentArmServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => ExperimentArmServiceClient.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>ExperimentArmService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage experiment arms.
/// </remarks>
public abstract partial class ExperimentArmServiceClient
{
/// <summary>
/// The default endpoint for the ExperimentArmService 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 ExperimentArmService scopes.</summary>
/// <remarks>
/// The default ExperimentArmService 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="ExperimentArmServiceClient"/> using the default credentials, endpoint
/// and settings. To specify custom credentials or other settings, use
/// <see cref="ExperimentArmServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="ExperimentArmServiceClient"/>.</returns>
public static stt::Task<ExperimentArmServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new ExperimentArmServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="ExperimentArmServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use
/// <see cref="ExperimentArmServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="ExperimentArmServiceClient"/>.</returns>
public static ExperimentArmServiceClient Create() => new ExperimentArmServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="ExperimentArmServiceClient"/> 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="ExperimentArmServiceSettings"/>.</param>
/// <returns>The created <see cref="ExperimentArmServiceClient"/>.</returns>
internal static ExperimentArmServiceClient Create(grpccore::CallInvoker callInvoker, ExperimentArmServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
ExperimentArmService.ExperimentArmServiceClient grpcClient = new ExperimentArmService.ExperimentArmServiceClient(callInvoker);
return new ExperimentArmServiceClientImpl(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 ExperimentArmService client</summary>
public virtual ExperimentArmService.ExperimentArmServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes experiment arms. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ExperimentArmError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </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 MutateExperimentArmsResponse MutateExperimentArms(MutateExperimentArmsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes experiment arms. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ExperimentArmError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </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<MutateExperimentArmsResponse> MutateExperimentArmsAsync(MutateExperimentArmsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes experiment arms. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ExperimentArmError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </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<MutateExperimentArmsResponse> MutateExperimentArmsAsync(MutateExperimentArmsRequest request, st::CancellationToken cancellationToken) =>
MutateExperimentArmsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates, or removes experiment arms. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ExperimentArmError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose experiments are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual experiment arm.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateExperimentArmsResponse MutateExperimentArms(string customerId, scg::IEnumerable<ExperimentArmOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateExperimentArms(new MutateExperimentArmsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes experiment arms. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ExperimentArmError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose experiments are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual experiment arm.
/// </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<MutateExperimentArmsResponse> MutateExperimentArmsAsync(string customerId, scg::IEnumerable<ExperimentArmOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateExperimentArmsAsync(new MutateExperimentArmsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes experiment arms. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ExperimentArmError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose experiments are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual experiment arm.
/// </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<MutateExperimentArmsResponse> MutateExperimentArmsAsync(string customerId, scg::IEnumerable<ExperimentArmOperation> operations, st::CancellationToken cancellationToken) =>
MutateExperimentArmsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>ExperimentArmService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage experiment arms.
/// </remarks>
public sealed partial class ExperimentArmServiceClientImpl : ExperimentArmServiceClient
{
private readonly gaxgrpc::ApiCall<MutateExperimentArmsRequest, MutateExperimentArmsResponse> _callMutateExperimentArms;
/// <summary>
/// Constructs a client wrapper for the ExperimentArmService service, with the specified gRPC client and
/// settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="ExperimentArmServiceSettings"/> used within this client.</param>
public ExperimentArmServiceClientImpl(ExperimentArmService.ExperimentArmServiceClient grpcClient, ExperimentArmServiceSettings settings)
{
GrpcClient = grpcClient;
ExperimentArmServiceSettings effectiveSettings = settings ?? ExperimentArmServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callMutateExperimentArms = clientHelper.BuildApiCall<MutateExperimentArmsRequest, MutateExperimentArmsResponse>(grpcClient.MutateExperimentArmsAsync, grpcClient.MutateExperimentArms, effectiveSettings.MutateExperimentArmsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateExperimentArms);
Modify_MutateExperimentArmsApiCall(ref _callMutateExperimentArms);
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_MutateExperimentArmsApiCall(ref gaxgrpc::ApiCall<MutateExperimentArmsRequest, MutateExperimentArmsResponse> call);
partial void OnConstruction(ExperimentArmService.ExperimentArmServiceClient grpcClient, ExperimentArmServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC ExperimentArmService client</summary>
public override ExperimentArmService.ExperimentArmServiceClient GrpcClient { get; }
partial void Modify_MutateExperimentArmsRequest(ref MutateExperimentArmsRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Creates, updates, or removes experiment arms. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ExperimentArmError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </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 MutateExperimentArmsResponse MutateExperimentArms(MutateExperimentArmsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateExperimentArmsRequest(ref request, ref callSettings);
return _callMutateExperimentArms.Sync(request, callSettings);
}
/// <summary>
/// Creates, updates, or removes experiment arms. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ExperimentArmError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </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<MutateExperimentArmsResponse> MutateExperimentArmsAsync(MutateExperimentArmsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateExperimentArmsRequest(ref request, ref callSettings);
return _callMutateExperimentArms.Async(request, callSettings);
}
}
}
| |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
#region "Entity classes"
class Entity
{
public enum Type {
SHIP = 0,
BARREL = 1,
CANNONBALL = 2,
MINE = 3
}
public int id;
public Type type;
public int x;
public int y;
public int rum;
public Entity()
{
// empty
}
public Entity(int id, Type type, int x, int y, int rum)
{
this.type = type;
Update(id, x, y, rum);
}
public void Update(int id, int x, int y, int rum)
{
this.id = id;
this.x = x;
this.y = y;
this.rum = rum;
Console.Error.WriteLine(ToString());
}
public override string ToString()
{
return "Entity " + id + ", " + type.ToString() + " (" + x + ", " + y + ") with " + rum + " rum";
}
public int getDistance(Entity e)
{
return getDistance(e.x, e.y);
}
public int getDistance(int x, int y)
{
return (Math.Abs(this.x - x) + Math.Abs(this.y - y));
}
}
class Ship : Entity {
public int rotation;
public int speed;
public int owner;
public int mineCooldown;
public Ship(int id, int x, int y, int rum, int rotation, int speed, int owner)
{
this.type = Type.SHIP;
Update(id, x, y, rum, rotation, speed, owner);
}
public void Update(int id, int x, int y, int rum, int rotation, int speed, int owner)
{
base.Update(id, x, y, rum);
Console.Error.WriteLine("Rotation: " + rotation + ", Speed: " + speed + ", Owner: " + owner);
this.rotation = rotation;
this.speed = speed;
this.owner = owner;
if (this.mineCooldown > 0)
this.mineCooldown--;
}
public void Move(Entity e)
{
Move(e.x, e.y);
}
public void Move(int x, int y)
{
Console.WriteLine("MOVE " + x + " " + y);
}
public void Wait()
{
Console.WriteLine("WAIT");
}
public void Slower()
{
Console.WriteLine("SLOWER");
}
public void Fire(Entity e)
{
Fire(e.x, e.y);
}
public void Fire(int x, int y)
{
Console.WriteLine("FIRE " + x + " " + y);
}
public void Mine()
{
Console.WriteLine("MINE");
this.mineCooldown = 4;
}
}
class Barrel : Entity {
public Barrel(int id, int x, int y, int rum)
{
this.type = Type.BARREL;
base.Update(id, x, y, rum);
}
}
class Cannonball : Entity {
public int owner;
public int impact;
public Cannonball(int id, int x, int y, int owner, int impact)
{
this.type = Type.CANNONBALL;
Update(id, x, y, owner, impact);
}
public void Update(int id, int x, int y, int owner, int impact)
{
base.Update(id, x, y, 25);
this.owner = owner;
this.impact = impact;
}
}
class Mine : Entity {
public Mine(int id, int x, int y)
{
this.type = Type.MINE;
Update(id, x, y);
}
public void Update(int id, int x, int y)
{
base.Update(id, x, y, 25);
}
}
#endregion
class Player
{
static void Main(string[] args)
{
Dictionary<int, Entity> entities = new Dictionary<int, Entity>();
List<Ship> ships = new List<Ship>();
List<Barrel> barrels = new List<Barrel>();
List<Cannonball> cannonballs = new List<Cannonball>();
List<Mine> mines = new List<Mine>();
// game loop
while (true)
{
// number of ships
int myShipCount = int.Parse(Console.ReadLine());
// the number of entities (e.g. ships, mines or cannonballs)
int entityCount = int.Parse(Console.ReadLine());
ships.Clear();
barrels.Clear();
for (int i = 0; i < entityCount; i++)
{
string line = Console.ReadLine();
string[] inputs = line.Split(' ');
//Console.Error.WriteLine("input: " + line);
int entityId = int.Parse(inputs[0]);
string entityType = inputs[1];
int x = int.Parse(inputs[2]);
int y = int.Parse(inputs[3]);
int arg1 = int.Parse(inputs[4]);
int arg2 = int.Parse(inputs[5]);
int arg3 = int.Parse(inputs[6]);
int arg4 = int.Parse(inputs[7]);
Entity e = null;
if (entities.ContainsKey(entityId))
{
e = entities[entityId];
if (entityType == "SHIP")
((Ship)e).Update(entityId, x, y, arg3, arg1, arg2, arg4);
else if (entityType == "BARREL")
((Barrel)e).Update(entityId, x, y, arg1);
else if (entityType == "CANNONBALL")
((Cannonball)e).Update(entityId, x, y, arg1, arg2);
else if (entityType == "MINE")
((Mine)e).Update(entityId, x, y);
}
else
{
if (entityType == "SHIP")
e = new Ship(entityId, x, y, arg3, arg1, arg2, arg4);
else if (entityType == "BARREL")
e = new Barrel(entityId, x, y, arg1);
else if (entityType == "CANNONBALL")
e = new Cannonball(entityId, x, y, arg1, arg2);
else if (entityType == "MINE")
e = new Mine(entityId, x, y);
entities[entityId] = e;
}
// add to the list
if (entityType == "SHIP")
ships.Add((Ship)e);
else if (entityType == "BARREL")
barrels.Add((Barrel)e);
else if (entityType == "CANNONBALL")
cannonballs.Add((Cannonball)e);
else if (entityType == "MINE")
mines.Add((Mine)e);
}
foreach (Ship ship in ships)
{
if (ship.owner != 1)
continue;
if (barrels.Count == 0)
{
ship.Fire(ships[1]);
continue;
}
barrels.Sort((b1, b2) => ship.getDistance(b1) - ship.getDistance(b2));
Console.Error.WriteLine("Best barrel: " + barrels[0]);
ship.Move(barrels[0]);
}
}
}
}
| |
using System;
using System.IO;
using System.Runtime.InteropServices;
using Omnius.Base;
namespace Omnius.Io
{
public class UnbufferedFileStream : Stream
{
private class BlockInfo
{
public bool IsUpdated { get; set; }
public long Position { get; set; }
public int Offset { get; set; }
public int Count { get; set; }
public byte[] Value { get; set; }
}
private string _path;
private BufferManager _bufferManager;
private long _position;
private long _length;
private FileStream _stream;
private BlockInfo _blockInfo;
private bool _isDisposed;
private const int SectorSize = 1024 * 256;
public UnbufferedFileStream(string path, FileMode mode, FileAccess access, FileShare share, FileOptions options, BufferManager bufferManager)
{
_path = path;
_bufferManager = bufferManager;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
const FileOptions FileFlagNoBuffering = (FileOptions)0x20000000;
_stream = new FileStream(path, mode, access, share, 8, options | FileFlagNoBuffering);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
_stream = new FileStream(path, mode, access, share, 8, options);
}
_blockInfo = new BlockInfo();
{
_blockInfo.IsUpdated = false;
_blockInfo.Position = -1;
_blockInfo.Offset = 0;
_blockInfo.Count = 0;
_blockInfo.Value = _bufferManager.TakeBuffer(SectorSize);
}
_position = _stream.Position;
_length = _stream.Length;
}
public string Name
{
get
{
return _stream.Name;
}
}
public override bool CanRead
{
get
{
if (_isDisposed) throw new ObjectDisposedException(this.GetType().FullName);
return _stream.CanRead;
}
}
public override bool CanWrite
{
get
{
if (_isDisposed) throw new ObjectDisposedException(this.GetType().FullName);
return _stream.CanWrite;
}
}
public override bool CanSeek
{
get
{
if (_isDisposed) throw new ObjectDisposedException(this.GetType().FullName);
return _stream.CanSeek;
}
}
public override long Position
{
get
{
if (_isDisposed) throw new ObjectDisposedException(this.GetType().FullName);
return _position;
}
set
{
if (_isDisposed) throw new ObjectDisposedException(this.GetType().FullName);
if (_position == value) return;
if (_blockInfo.IsUpdated)
{
this.Flush();
}
else
{
long p = (value / SectorSize) * SectorSize;
if (_blockInfo.Position != p)
{
_blockInfo.Position = -1;
_blockInfo.Offset = 0;
_blockInfo.Count = 0;
}
}
_position = value;
}
}
public override long Length
{
get
{
if (_isDisposed) throw new ObjectDisposedException(this.GetType().FullName);
return _length;
}
}
public override long Seek(long offset, SeekOrigin origin)
{
if (_isDisposed) throw new ObjectDisposedException(this.GetType().FullName);
if (origin == SeekOrigin.Begin)
{
return this.Position = offset;
}
else if (origin == SeekOrigin.Current)
{
return this.Position += offset;
}
else if (origin == SeekOrigin.End)
{
return this.Position = this.Length + offset;
}
else
{
throw new NotSupportedException();
}
}
public override void SetLength(long value)
{
if (_isDisposed) throw new ObjectDisposedException(this.GetType().FullName);
_length = value;
}
public override int Read(byte[] buffer, int offset, int count)
{
if (_isDisposed) throw new ObjectDisposedException(this.GetType().FullName);
if (offset < 0 || buffer.Length < offset) throw new ArgumentOutOfRangeException(nameof(offset));
if (count < 0 || (buffer.Length - offset) < count) throw new ArgumentOutOfRangeException(nameof(count));
if (count == 0) return 0;
if (_blockInfo.IsUpdated)
{
this.Flush();
}
count = (int)Math.Min(count, _length - _position);
int readSumLength = 0;
while (count > 0)
{
long p = (_position / SectorSize) * SectorSize;
if (_blockInfo.Position != p)
{
_blockInfo.Position = p;
_blockInfo.Offset = 0;
_stream.Seek(_blockInfo.Position, SeekOrigin.Begin);
int readLength = _stream.Read(_blockInfo.Value, 0, SectorSize);
readLength = (int)Math.Min(_length - _blockInfo.Position, readLength);
_blockInfo.Count = readLength;
}
int blockReadPosition = (int)(_position - p);
int length = Math.Min(SectorSize - blockReadPosition, count);
Unsafe.Copy(_blockInfo.Value, blockReadPosition, buffer, offset, length);
offset += length;
count -= length;
_position += length;
readSumLength += length;
}
return readSumLength;
}
public override void Write(byte[] buffer, int offset, int count)
{
if (_isDisposed) throw new ObjectDisposedException(this.GetType().FullName);
if (offset < 0 || buffer.Length < offset) throw new ArgumentOutOfRangeException(nameof(offset));
if (count < 0 || (buffer.Length - offset) < count) throw new ArgumentOutOfRangeException(nameof(count));
if (count == 0) return;
while (count > 0)
{
long p = (_position / SectorSize) * SectorSize;
if (_blockInfo.Position != p)
{
this.Flush();
}
_stream.Seek(p, SeekOrigin.Begin);
int blockWritePosition = (int)(_position - p);
int length = Math.Min(SectorSize - blockWritePosition, count);
_blockInfo.Position = p;
Unsafe.Copy(buffer, offset, _blockInfo.Value, blockWritePosition, length);
if (_blockInfo.Count == 0) _blockInfo.Offset = blockWritePosition;
_blockInfo.Count = (length + blockWritePosition) - _blockInfo.Offset;
_blockInfo.IsUpdated = true;
offset += length;
count -= length;
_position += length;
}
}
public override void Flush()
{
if (_blockInfo.Position == -1) return;
if (_blockInfo.IsUpdated)
{
_length = Math.Max(_length, _blockInfo.Position + _blockInfo.Offset + _blockInfo.Count);
if (_blockInfo.Offset != 0 || _blockInfo.Count != SectorSize)
{
using (var safeBuffer = _bufferManager.CreateSafeBuffer(SectorSize))
{
_stream.Seek(_blockInfo.Position, SeekOrigin.Begin);
int readLength = _stream.Read(safeBuffer.Value, 0, SectorSize);
readLength = (int)Math.Min(_length - _blockInfo.Position, readLength);
Unsafe.Zero(safeBuffer.Value, readLength, SectorSize - readLength);
Unsafe.Copy(_blockInfo.Value, _blockInfo.Offset, safeBuffer.Value, _blockInfo.Offset, _blockInfo.Count);
_stream.Seek(_blockInfo.Position, SeekOrigin.Begin);
_stream.Write(safeBuffer.Value, 0, SectorSize);
}
}
else
{
_stream.Seek(_blockInfo.Position, SeekOrigin.Begin);
_stream.Write(_blockInfo.Value, 0, _blockInfo.Count);
}
}
_blockInfo.IsUpdated = false;
_blockInfo.Position = -1;
_blockInfo.Offset = 0;
_blockInfo.Count = 0;
_stream.Flush();
}
protected override void Dispose(bool isDisposing)
{
try
{
if (_isDisposed) return;
_isDisposed = true;
if (isDisposing)
{
this.Flush();
if (_stream != null)
{
try
{
_stream.Dispose();
}
catch (Exception)
{
}
_stream = null;
}
if (_blockInfo.Value != null)
{
try
{
_bufferManager.ReturnBuffer(_blockInfo.Value);
}
catch (Exception)
{
}
_blockInfo.Value = null;
}
try
{
using (var stream = new FileStream(_path, FileMode.Open))
{
if (stream.Length != _length)
{
stream.SetLength(_length);
}
}
}
catch (Exception)
{
}
}
}
finally
{
base.Dispose(isDisposing);
}
}
}
}
| |
using Color = UnityEngine.Color;
using Texture2D = UnityEngine.Texture2D;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using Ecosim;
namespace Ecosim.SceneData
{
public class TileType
{
public const string XML_ELEMENT = "tile";
public class TreeData
{
public TreeData ()
{
}
public TreeData (TreeData source)
{
x = source.x;
y = source.y;
r = source.r;
prototypeIndex = source.prototypeIndex;
minHeight = source.minHeight;
maxHeight = source.maxHeight;
minWidthVariance = source.minWidthVariance;
minWidthVariance = source.maxWidthVariance;
colorFrom = source.colorFrom;
colorTo = source.colorTo;
}
static Color start = new Color (0.5625f, 0.5625f, 0.5625f, 1f);
static Color end = new Color (0.75f, 0.75f, 0.75f, 1f);
public string GetName ()
{
return EcoTerrainElements.GetTreePrototypeNameForIndex(prototypeIndex);
}
public int prototypeIndex;
public float x = 0.5f;
public float y = 0.5f;
public float r = 0.2f;
public float minHeight = 0.9f;
public float maxHeight = 1.1f;
public float minWidthVariance = 0.9f;
public float maxWidthVariance = 1.1f;
public Color colorFrom = start;
public Color colorTo = end;
}
public class ObjectData
{
public ObjectData ()
{
}
public ObjectData (ObjectData source)
{
x = source.x;
y = source.y;
r = source.r;
angle = source.angle;
index = source.index;
minHeight = source.minHeight;
maxHeight = source.maxHeight;
minWidthVariance = source.minWidthVariance;
minWidthVariance = source.maxWidthVariance;
}
public string GetName ()
{
return null; // TODO JElements.GetTileObjectPrefab(index).name;
}
public int index;
public float x = 0.5f;
public float y = 0.5f;
public float r = 0.0f;
public float angle = 0f;
public float minHeight = 0.9f;
public float maxHeight = 1.1f;
public float minWidthVariance = 0.9f;
public float maxWidthVariance = 1.1f;
}
public string name;
public int index;
public VegetationType vegetationType;
private Texture2D icon;
public TileType() {
}
/**
* Copies current tile to destinatioon tile dst
* dst will be an exact copy of this tile (including index and vegetation link)
*/
public void CopyTo(TileType dst) {
CopyTo(dst, false);
}
/**
* Copies current tile to destination tile dst
* if keepVegetationLink is true, the index and vegetation type of destination tile is not changed
*/
public void CopyTo(TileType dst, bool keepVegetationLink) {
if (!keepVegetationLink) {
dst.index = index;
dst.vegetationType = vegetationType;
}
dst.splat0 = splat0;
dst.splat1 = splat1;
dst.splat2 = splat2;
dst.trees = new TreeData[trees.Length];
for (int i = 0; i < trees.Length; i++) {
dst.trees[i] = new TreeData(trees[i]);
}
dst.objects = new ObjectData[objects.Length];
for (int i = 0; i < objects.Length; i++) {
dst.objects[i] = new ObjectData(objects[i]);
}
dst.decals = (int[]) decals.Clone();
dst.detailCounts = (int[]) detailCounts.Clone();
}
public TileType(VegetationType veg) {
this.index = veg.tiles.Length;
this.vegetationType = veg;
splat0 = 1f;
trees = new TreeData[0];
objects = new ObjectData[0];
decals = new int[0];
detailCounts = new int[0];
if (veg.tiles.Length > 0) {
TileType firstTile = veg.tiles[0];
splat0 = firstTile.splat0;
splat1 = firstTile.splat1;
splat2 = firstTile.splat2;
}
List<TileType> tmpTilesList = new List<TileType>(veg.tiles);
tmpTilesList.Add(this);
veg.tiles = tmpTilesList.ToArray();
}
public Texture2D GetIcon ()
{
if (icon == null) {
icon = RenderTileIcons.RenderTile(this);
}
return icon;
}
public void SetIcon (Texture2D icon)
{
this.icon = icon;
}
public float splat0; // for splat map (tile colour)
public float splat1;
public float splat2;
public TreeData[] trees;
public ObjectData[] objects;
public int[] decals;
public int[] detailCounts;
public void Save (XmlTextWriter writer, Scene scene)
{
writer.WriteStartElement (XML_ELEMENT);
writer.WriteAttributeString ("splat0", splat0.ToString ());
writer.WriteAttributeString ("splat1", splat1.ToString ());
writer.WriteAttributeString ("splat2", splat2.ToString ());
foreach (int decal in decals) {
writer.WriteStartElement ("tilelayer");
writer.WriteAttributeString ("name", EcoTerrainElements.GetDecalNameForIndex(decal));
writer.WriteAttributeString ("index", decal.ToString());
writer.WriteEndElement (); // ~tilelayer
}
foreach (TreeData td in trees) {
writer.WriteStartElement ("tree");
writer.WriteAttributeString ("x", td.x.ToString ());
writer.WriteAttributeString ("y", td.y.ToString ());
writer.WriteAttributeString ("r", td.r.ToString ());
writer.WriteAttributeString ("prototypeName", td.GetName ());
writer.WriteAttributeString ("prototype", td.prototypeIndex.ToString ());
writer.WriteAttributeString ("minHeight", td.minHeight.ToString ());
writer.WriteAttributeString ("maxHeight", td.maxHeight.ToString ());
writer.WriteAttributeString ("minWidthVariance", td.minWidthVariance.ToString ());
writer.WriteAttributeString ("maxWidthVariance", td.maxWidthVariance.ToString ());
writer.WriteAttributeString ("fromColour", StringUtil.ColorToString (td.colorFrom));
writer.WriteAttributeString ("toColour", StringUtil.ColorToString (td.colorTo));
writer.WriteEndElement (); // ~tree
}
foreach (ObjectData od in objects) {
writer.WriteStartElement ("object");
writer.WriteAttributeString ("x", od.x.ToString ());
writer.WriteAttributeString ("y", od.y.ToString ());
writer.WriteAttributeString ("r", od.r.ToString ());
writer.WriteAttributeString ("angle", od.angle.ToString ());
writer.WriteAttributeString ("name", EcoTerrainElements.GetObjectNames () [od.index]);
writer.WriteAttributeString ("objectIndex", od.index.ToString ());
writer.WriteAttributeString ("minHeight", od.minHeight.ToString ());
writer.WriteAttributeString ("maxHeight", od.maxHeight.ToString ());
writer.WriteAttributeString ("minWidthVariance", od.minWidthVariance.ToString ());
writer.WriteAttributeString ("maxWidthVariance", od.maxWidthVariance.ToString ());
writer.WriteEndElement (); // ~object
}
int index = 0;
foreach (int count in detailCounts) {
if (count > 0) {
writer.WriteStartElement ("detail");
writer.WriteAttributeString ("name", EcoTerrainElements.GetDetailNameForIndex(index));
writer.WriteAttributeString ("index", index.ToString ());
writer.WriteAttributeString ("count", count.ToString ());
writer.WriteEndElement (); // ~detail
}
index++;
}
writer.WriteEndElement (); // ~tile
}
public static TileType Load (XmlTextReader reader, Scene scene)
{
TileType tt = new TileType ();
tt.splat0 = float.Parse (reader.GetAttribute ("splat0"));
tt.splat1 = float.Parse (reader.GetAttribute ("splat1"));
tt.splat2 = float.Parse (reader.GetAttribute ("splat2"));
int maxDetailIndex = -1;
List<int> tileLayers = new List<int> ();
if (!reader.IsEmptyElement) {
List<TreeData> treeList = new List<TreeData> ();
List<ObjectData> objectList = new List<ObjectData> ();
Dictionary<int, int> detailDict = new Dictionary<int, int> ();
while (reader.Read()) {
XmlNodeType nType = reader.NodeType;
if ((nType == XmlNodeType.Element) && (reader.Name.ToLower () == "image")) {
nType = reader.NodeType;
IOUtil.ReadUntilEndElement (reader, "image");
}
if ((nType == XmlNodeType.Element) && (reader.Name.ToLower () == "tree")) {
TreeData tree = new TreeData ();
tree.x = float.Parse (reader.GetAttribute ("x"));
tree.y = float.Parse (reader.GetAttribute ("y"));
tree.r = float.Parse (reader.GetAttribute ("r"));
int index = -1;
string prototypeName = reader.GetAttribute ("prototypeName");
if (prototypeName != null) {
index = EcoTerrainElements.GetIndexOfTreePrototype (prototypeName);
}
if (index >= 0) {
// index = int.Parse(reader.GetAttribute("prototype"));
tree.prototypeIndex = index;
tree.minHeight = float.Parse (reader.GetAttribute ("minHeight"));
tree.maxHeight = float.Parse (reader.GetAttribute ("maxHeight"));
tree.minWidthVariance = float.Parse (reader.GetAttribute ("minWidthVariance"));
tree.maxWidthVariance = float.Parse (reader.GetAttribute ("maxWidthVariance"));
tree.colorFrom = StringUtil.StringToColor (reader.GetAttribute ("fromColour"));
tree.colorTo = StringUtil.StringToColor (reader.GetAttribute ("toColour"));
treeList.Add (tree);
IOUtil.ReadUntilEndElement (reader, "tree");
}
} else if ((nType == XmlNodeType.Element) && (reader.Name.ToLower () == "object")) {
ObjectData obj = new ObjectData ();
obj.x = float.Parse (reader.GetAttribute ("x"));
obj.y = float.Parse (reader.GetAttribute ("y"));
obj.r = float.Parse (reader.GetAttribute ("r"));
obj.angle = float.Parse (reader.GetAttribute ("angle"));
int index = -1;
string prototypeName = reader.GetAttribute ("name");
if (prototypeName != null) {
index = EcoTerrainElements.GetIndexOfObject (prototypeName);
}
if (index >= 0) {
// index = int.Parse(reader.GetAttribute("objectIndex"));
obj.index = index;
obj.minHeight = float.Parse (reader.GetAttribute ("minHeight"));
obj.maxHeight = float.Parse (reader.GetAttribute ("maxHeight"));
obj.minWidthVariance = float.Parse (reader.GetAttribute ("minWidthVariance"));
obj.maxWidthVariance = float.Parse (reader.GetAttribute ("maxWidthVariance"));
objectList.Add (obj);
}
else {
Log.LogError("Can't find tile object '" + prototypeName + "'");
}
IOUtil.ReadUntilEndElement (reader, "object");
} else if ((nType == XmlNodeType.Element) && (reader.Name.ToLower () == "detail")) {
int index = -1;
string detailName = reader.GetAttribute ("name");
if (detailName != null) {
index = EcoTerrainElements.GetIndexOfDetailPrototype (detailName);
}
if (index >= 0) {
// index = int.Parse(reader.GetAttribute("index"));
int count = int.Parse (reader.GetAttribute ("count"));
maxDetailIndex = System.Math.Max (maxDetailIndex, index);
if (!detailDict.ContainsKey (index)) {
detailDict.Add (index, count);
}
}
IOUtil.ReadUntilEndElement (reader, "detail");
} else if ((nType == XmlNodeType.Element) && (reader.Name.ToLower () == "tilelayer")) {
string name = reader.GetAttribute ("name");
int id = EcoTerrainElements.GetIndexOfDecal (name);
if (id >= 0) {
// id = int.Parse(reader.GetAttribute("index"));
tileLayers.Add (id);
}
IOUtil.ReadUntilEndElement (reader, "tilelayer");
} else if ((nType == XmlNodeType.EndElement) && (reader.Name.ToLower () == XML_ELEMENT)) {
break;
}
}
tt.trees = treeList.ToArray ();
tt.objects = objectList.ToArray ();
tt.decals = tileLayers.ToArray ();
tt.detailCounts = new int[maxDetailIndex + 1];
foreach (KeyValuePair<int, int> v in detailDict) {
tt.detailCounts [v.Key] = v.Value;
}
} else {
tt.trees = new TreeData[0];
tt.detailCounts = new int[0];
tt.objects = new ObjectData[0];
tt.decals = new int[0];
}
return tt;
}
public void UpdateLinks (Scene scene, VegetationType veg) {
vegetationType = veg;
}
}
}
| |
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Shared.Preview;
using Microsoft.CodeAnalysis.Editor.Shared.Tagging;
using Microsoft.CodeAnalysis.Editor.UnitTests.Squiggles;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Differencing;
using Microsoft.VisualStudio.Text.Tagging;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using Microsoft.CodeAnalysis.Editor.Implementation.Preview;
using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Preview
{
public class PreviewWorkspaceTests
{
[Fact, Trait(Traits.Editor, Traits.Editors.Preview)]
public void TestPreviewCreationDefault()
{
using (var previewWorkspace = new PreviewWorkspace())
{
Assert.NotNull(previewWorkspace.CurrentSolution);
}
}
[Fact, Trait(Traits.Editor, Traits.Editors.Preview)]
public void TestPreviewCreationWithExplicitHostServices()
{
var assembly = typeof(ISolutionCrawlerService).Assembly;
using (var previewWorkspace = new PreviewWorkspace(MefHostServices.Create(MefHostServices.DefaultAssemblies.Concat(assembly))))
{
Assert.NotNull(previewWorkspace.CurrentSolution);
}
}
[Fact, Trait(Traits.Editor, Traits.Editors.Preview)]
public void TestPreviewCreationWithSolution()
{
using (var custom = new AdhocWorkspace())
using (var previewWorkspace = new PreviewWorkspace(custom.CurrentSolution))
{
Assert.NotNull(previewWorkspace.CurrentSolution);
}
}
[Fact, Trait(Traits.Editor, Traits.Editors.Preview)]
public void TestPreviewAddRemoveProject()
{
using (var previewWorkspace = new PreviewWorkspace())
{
var solution = previewWorkspace.CurrentSolution;
var project = solution.AddProject("project", "project.dll", LanguageNames.CSharp);
Assert.True(previewWorkspace.TryApplyChanges(project.Solution));
var newSolution = previewWorkspace.CurrentSolution.RemoveProject(project.Id);
Assert.True(previewWorkspace.TryApplyChanges(newSolution));
Assert.Equal(0, previewWorkspace.CurrentSolution.ProjectIds.Count);
}
}
[Fact, Trait(Traits.Editor, Traits.Editors.Preview)]
public void TestPreviewProjectChanges()
{
using (var previewWorkspace = new PreviewWorkspace())
{
var solution = previewWorkspace.CurrentSolution;
var project = solution.AddProject("project", "project.dll", LanguageNames.CSharp);
Assert.True(previewWorkspace.TryApplyChanges(project.Solution));
var addedSolution = previewWorkspace.CurrentSolution.Projects.First()
.AddMetadataReference(TestReferences.NetFx.v4_0_30319.mscorlib)
.AddDocument("document", "").Project.Solution;
Assert.True(previewWorkspace.TryApplyChanges(addedSolution));
Assert.Equal(1, previewWorkspace.CurrentSolution.Projects.First().MetadataReferences.Count);
Assert.Equal(1, previewWorkspace.CurrentSolution.Projects.First().DocumentIds.Count);
var text = "class C {}";
var changedSolution = previewWorkspace.CurrentSolution.Projects.First().Documents.First().WithText(SourceText.From(text)).Project.Solution;
Assert.True(previewWorkspace.TryApplyChanges(changedSolution));
Assert.Equal(previewWorkspace.CurrentSolution.Projects.First().Documents.First().GetTextAsync().Result.ToString(), text);
var removedSolution = previewWorkspace.CurrentSolution.Projects.First()
.RemoveMetadataReference(previewWorkspace.CurrentSolution.Projects.First().MetadataReferences[0])
.RemoveDocument(previewWorkspace.CurrentSolution.Projects.First().DocumentIds[0]).Solution;
Assert.True(previewWorkspace.TryApplyChanges(removedSolution));
Assert.Equal(0, previewWorkspace.CurrentSolution.Projects.First().MetadataReferences.Count);
Assert.Equal(0, previewWorkspace.CurrentSolution.Projects.First().DocumentIds.Count);
}
}
[WorkItem(923121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/923121")]
[WpfFact, Trait(Traits.Editor, Traits.Editors.Preview)]
public void TestPreviewOpenCloseFile()
{
using (var previewWorkspace = new PreviewWorkspace())
{
var solution = previewWorkspace.CurrentSolution;
var project = solution.AddProject("project", "project.dll", LanguageNames.CSharp);
var document = project.AddDocument("document", "");
Assert.True(previewWorkspace.TryApplyChanges(document.Project.Solution));
previewWorkspace.OpenDocument(document.Id);
Assert.Equal(1, previewWorkspace.GetOpenDocumentIds().Count());
Assert.True(previewWorkspace.IsDocumentOpen(document.Id));
previewWorkspace.CloseDocument(document.Id);
Assert.Equal(0, previewWorkspace.GetOpenDocumentIds().Count());
Assert.False(previewWorkspace.IsDocumentOpen(document.Id));
}
}
[Fact, Trait(Traits.Editor, Traits.Editors.Preview)]
public void TestPreviewServices()
{
using (var previewWorkspace = new PreviewWorkspace(MefV1HostServices.Create(EditorServicesUtil.ExportProvider.AsExportProvider())))
{
var service = previewWorkspace.Services.GetService<ISolutionCrawlerRegistrationService>();
Assert.True(service is PreviewSolutionCrawlerRegistrationServiceFactory.Service);
var persistentService = previewWorkspace.Services.GetService<IPersistentStorageService>();
Assert.NotNull(persistentService);
var storage = persistentService.GetStorage(previewWorkspace.CurrentSolution);
Assert.True(storage is NoOpPersistentStorage);
}
}
[WorkItem(923196, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/923196")]
[WpfFact, Trait(Traits.Editor, Traits.Editors.Preview)]
public void TestPreviewDiagnostic()
{
var diagnosticService = EditorServicesUtil.ExportProvider.GetExportedValue<IDiagnosticAnalyzerService>() as IDiagnosticUpdateSource;
var taskSource = new TaskCompletionSource<DiagnosticsUpdatedArgs>();
diagnosticService.DiagnosticsUpdated += (s, a) => taskSource.TrySetResult(a);
using (var previewWorkspace = new PreviewWorkspace(MefV1HostServices.Create(EditorServicesUtil.ExportProvider.AsExportProvider())))
{
var solution = previewWorkspace.CurrentSolution
.AddProject("project", "project.dll", LanguageNames.CSharp)
.AddDocument("document", "class { }")
.Project
.Solution;
Assert.True(previewWorkspace.TryApplyChanges(solution));
previewWorkspace.OpenDocument(previewWorkspace.CurrentSolution.Projects.First().DocumentIds[0]);
previewWorkspace.EnableDiagnostic();
// wait 20 seconds
taskSource.Task.Wait(20000);
Assert.True(taskSource.Task.IsCompleted);
var args = taskSource.Task.Result;
Assert.True(args.Diagnostics.Length > 0);
}
}
[WpfFact]
public async Task TestPreviewDiagnosticTagger()
{
using (var workspace = TestWorkspace.CreateCSharp("class { }", exportProvider: EditorServicesUtil.ExportProvider))
using (var previewWorkspace = new PreviewWorkspace(workspace.CurrentSolution))
{
//// preview workspace and owner of the solution now share solution and its underlying text buffer
var hostDocument = workspace.Projects.First().Documents.First();
//// enable preview diagnostics
previewWorkspace.EnableDiagnostic();
var diagnosticsAndErrorsSpans = await SquiggleUtilities.GetDiagnosticsAndErrorSpansAsync<DiagnosticsSquiggleTaggerProvider>(workspace);
const string AnalzyerCount = "Analyzer Count: ";
Assert.Equal(AnalzyerCount + 1, AnalzyerCount + diagnosticsAndErrorsSpans.Item1.Length);
const string SquigglesCount = "Squiggles Count: ";
Assert.Equal(SquigglesCount + 1, SquigglesCount + diagnosticsAndErrorsSpans.Item2.Length);
}
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/14444")]
public async Task TestPreviewDiagnosticTaggerInPreviewPane()
{
using (var workspace = TestWorkspace.CreateCSharp("class { }", exportProvider: EditorServicesUtil.ExportProvider))
{
// set up listener to wait until diagnostic finish running
var diagnosticService = workspace.ExportProvider.GetExportedValue<IDiagnosticService>() as DiagnosticService;
// no easy way to setup waiter. kind of hacky way to setup waiter
var source = new CancellationTokenSource();
var taskSource = new TaskCompletionSource<DiagnosticsUpdatedArgs>();
diagnosticService.DiagnosticsUpdated += (s, a) =>
{
source.Cancel();
source = new CancellationTokenSource();
var cancellationToken = source.Token;
Task.Delay(2000, cancellationToken).ContinueWith(t => taskSource.TrySetResult(a), CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Current);
};
var hostDocument = workspace.Projects.First().Documents.First();
// make a change to remove squiggle
var oldDocument = workspace.CurrentSolution.GetDocument(hostDocument.Id);
var oldText = oldDocument.GetTextAsync().Result;
var newDocument = oldDocument.WithText(oldText.WithChanges(new TextChange(new TextSpan(0, oldText.Length), "class C { }")));
// create a diff view
WpfTestCase.RequireWpfFact($"{nameof(TestPreviewDiagnosticTaggerInPreviewPane)} creates a {nameof(DifferenceViewerPreview)}");
var previewFactoryService = workspace.ExportProvider.GetExportedValue<IPreviewFactoryService>();
using (var diffView = (DifferenceViewerPreview)(await previewFactoryService.CreateChangedDocumentPreviewViewAsync(oldDocument, newDocument, CancellationToken.None)))
{
var foregroundService = workspace.GetService<IForegroundNotificationService>();
var waiter = new ErrorSquiggleWaiter();
var listeners = AsynchronousOperationListener.CreateListeners(FeatureAttribute.ErrorSquiggles, waiter);
// set up tagger for both buffers
var leftBuffer = diffView.Viewer.LeftView.BufferGraph.GetTextBuffers(t => t.ContentType.IsOfType(ContentTypeNames.CSharpContentType)).First();
var leftProvider = new DiagnosticsSquiggleTaggerProvider(diagnosticService, foregroundService, listeners);
var leftTagger = leftProvider.CreateTagger<IErrorTag>(leftBuffer);
using (var leftDisposable = leftTagger as IDisposable)
{
var rightBuffer = diffView.Viewer.RightView.BufferGraph.GetTextBuffers(t => t.ContentType.IsOfType(ContentTypeNames.CSharpContentType)).First();
var rightProvider = new DiagnosticsSquiggleTaggerProvider(diagnosticService, foregroundService, listeners);
var rightTagger = rightProvider.CreateTagger<IErrorTag>(rightBuffer);
using (var rightDisposable = rightTagger as IDisposable)
{
// wait up to 20 seconds for diagnostics
taskSource.Task.Wait(20000);
if (!taskSource.Task.IsCompleted)
{
// something is wrong
FatalError.Report(new System.Exception("not finished after 20 seconds"));
}
// wait taggers
await waiter.CreateWaitTask();
// check left buffer
var leftSnapshot = leftBuffer.CurrentSnapshot;
var leftSpans = leftTagger.GetTags(leftSnapshot.GetSnapshotSpanCollection()).ToList();
Assert.Equal(1, leftSpans.Count);
// check right buffer
var rightSnapshot = rightBuffer.CurrentSnapshot;
var rightSpans = rightTagger.GetTags(rightSnapshot.GetSnapshotSpanCollection()).ToList();
Assert.Equal(0, rightSpans.Count);
}
}
}
}
}
private class ErrorSquiggleWaiter : AsynchronousOperationListener { }
}
}
| |
namespace AlfrescoWord2007
{
partial class AlfrescoPane
{
/// <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.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AlfrescoPane));
this.lnkShowConfiguration = new System.Windows.Forms.LinkLabel();
this.pnlConfiguration = new System.Windows.Forms.Panel();
this.lnkBackToBrowser = new System.Windows.Forms.LinkLabel();
this.label7 = new System.Windows.Forms.Label();
this.grpConfiguration = new System.Windows.Forms.GroupBox();
this.btnDetailsOK = new System.Windows.Forms.Button();
this.btnDetailsCancel = new System.Windows.Forms.Button();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.chkRememberAuth = new System.Windows.Forms.CheckBox();
this.txtPassword = new System.Windows.Forms.TextBox();
this.label8 = new System.Windows.Forms.Label();
this.txtUsername = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.grpDetails = new System.Windows.Forms.GroupBox();
this.txtCIFSServer = new System.Windows.Forms.TextBox();
this.label5 = new System.Windows.Forms.Label();
this.txtWebDAVURL = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.txtWebClientURL = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.tipGeneral = new System.Windows.Forms.ToolTip(this.components);
this.tipMandatory = new System.Windows.Forms.ToolTip(this.components);
this.tipOptional = new System.Windows.Forms.ToolTip(this.components);
this.pnlWebBrowser = new System.Windows.Forms.Panel();
this.webBrowser = new System.Windows.Forms.WebBrowser();
this.pnlConfiguration.SuspendLayout();
this.grpConfiguration.SuspendLayout();
this.groupBox1.SuspendLayout();
this.grpDetails.SuspendLayout();
this.pnlWebBrowser.SuspendLayout();
this.SuspendLayout();
//
// lnkShowConfiguration
//
this.lnkShowConfiguration.Location = new System.Drawing.Point(3, 657);
this.lnkShowConfiguration.Name = "lnkShowConfiguration";
this.lnkShowConfiguration.Size = new System.Drawing.Size(286, 30);
this.lnkShowConfiguration.TabIndex = 6;
this.lnkShowConfiguration.TabStop = true;
this.lnkShowConfiguration.Text = "Click here to Configure the Alfresco Server URLs";
this.lnkShowConfiguration.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.lnkShowConfiguration.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkShowConfiguration_LinkClicked);
//
// pnlConfiguration
//
this.pnlConfiguration.BackColor = System.Drawing.Color.White;
this.pnlConfiguration.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("pnlConfiguration.BackgroundImage")));
this.pnlConfiguration.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None;
this.pnlConfiguration.Controls.Add(this.lnkBackToBrowser);
this.pnlConfiguration.Controls.Add(this.label7);
this.pnlConfiguration.Controls.Add(this.grpConfiguration);
this.pnlConfiguration.Dock = System.Windows.Forms.DockStyle.Fill;
this.pnlConfiguration.Location = new System.Drawing.Point(0, 0);
this.pnlConfiguration.Name = "pnlConfiguration";
this.pnlConfiguration.Size = new System.Drawing.Size(292, 689);
this.pnlConfiguration.TabIndex = 7;
//
// lnkBackToBrowser
//
this.lnkBackToBrowser.Location = new System.Drawing.Point(3, 657);
this.lnkBackToBrowser.Name = "lnkBackToBrowser";
this.lnkBackToBrowser.Size = new System.Drawing.Size(286, 30);
this.lnkBackToBrowser.TabIndex = 4;
this.lnkBackToBrowser.TabStop = true;
this.lnkBackToBrowser.Text = "Click here to return to the Office Web Client view";
this.lnkBackToBrowser.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.lnkBackToBrowser.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkBackToBrowser_LinkClicked);
//
// label7
//
this.label7.Font = new System.Drawing.Font("Trebuchet MS", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label7.ForeColor = System.Drawing.SystemColors.ControlDarkDark;
this.label7.Location = new System.Drawing.Point(4, 77);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(285, 46);
this.label7.TabIndex = 3;
this.label7.Text = "Welcome to the Alfresco Add-In for Microsoft Office 2007";
this.label7.TextAlign = System.Drawing.ContentAlignment.TopCenter;
//
// grpConfiguration
//
this.grpConfiguration.Controls.Add(this.btnDetailsOK);
this.grpConfiguration.Controls.Add(this.btnDetailsCancel);
this.grpConfiguration.Controls.Add(this.groupBox1);
this.grpConfiguration.Controls.Add(this.label6);
this.grpConfiguration.Controls.Add(this.grpDetails);
this.grpConfiguration.Location = new System.Drawing.Point(0, 150);
this.grpConfiguration.Name = "grpConfiguration";
this.grpConfiguration.Size = new System.Drawing.Size(292, 474);
this.grpConfiguration.TabIndex = 2;
this.grpConfiguration.TabStop = false;
this.grpConfiguration.Text = "Configuration";
//
// btnDetailsOK
//
this.btnDetailsOK.BackColor = System.Drawing.SystemColors.ButtonFace;
this.btnDetailsOK.Location = new System.Drawing.Point(98, 440);
this.btnDetailsOK.Name = "btnDetailsOK";
this.btnDetailsOK.Size = new System.Drawing.Size(100, 23);
this.btnDetailsOK.TabIndex = 8;
this.btnDetailsOK.Text = "Save Settings";
this.btnDetailsOK.UseVisualStyleBackColor = false;
this.btnDetailsOK.Click += new System.EventHandler(this.btnDetailsOK_Click);
this.btnDetailsOK.TextChanged += new System.EventHandler(this.btnDetailsOK_Click);
//
// btnDetailsCancel
//
this.btnDetailsCancel.BackColor = System.Drawing.SystemColors.ButtonFace;
this.btnDetailsCancel.Location = new System.Drawing.Point(204, 440);
this.btnDetailsCancel.Name = "btnDetailsCancel";
this.btnDetailsCancel.Size = new System.Drawing.Size(75, 23);
this.btnDetailsCancel.TabIndex = 7;
this.btnDetailsCancel.Text = "Reset";
this.btnDetailsCancel.UseVisualStyleBackColor = false;
this.btnDetailsCancel.Click += new System.EventHandler(this.btnDetailsCancel_Click);
this.btnDetailsCancel.TextChanged += new System.EventHandler(this.btnDetailsCancel_Click);
//
// groupBox1
//
this.groupBox1.Controls.Add(this.chkRememberAuth);
this.groupBox1.Controls.Add(this.txtPassword);
this.groupBox1.Controls.Add(this.label8);
this.groupBox1.Controls.Add(this.txtUsername);
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.Location = new System.Drawing.Point(12, 281);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(267, 153);
this.groupBox1.TabIndex = 6;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Authentication";
//
// chkRememberAuth
//
this.chkRememberAuth.AutoSize = true;
this.chkRememberAuth.Location = new System.Drawing.Point(9, 119);
this.chkRememberAuth.Name = "chkRememberAuth";
this.chkRememberAuth.Size = new System.Drawing.Size(180, 17);
this.chkRememberAuth.TabIndex = 4;
this.chkRememberAuth.Text = "Remember authentication details";
this.chkRememberAuth.UseVisualStyleBackColor = true;
//
// txtPassword
//
this.txtPassword.Location = new System.Drawing.Point(9, 83);
this.txtPassword.Name = "txtPassword";
this.txtPassword.PasswordChar = '*';
this.txtPassword.Size = new System.Drawing.Size(251, 20);
this.txtPassword.TabIndex = 3;
this.tipOptional.SetToolTip(this.txtPassword, "Enter your Alfresco password here if you want to be automatically logged-on.");
this.txtPassword.TextChanged += new System.EventHandler(this.txtPassword_TextChanged);
//
// label8
//
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point(6, 66);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(53, 13);
this.label8.TabIndex = 2;
this.label8.Text = "Password";
//
// txtUsername
//
this.txtUsername.Location = new System.Drawing.Point(9, 37);
this.txtUsername.Name = "txtUsername";
this.txtUsername.Size = new System.Drawing.Size(251, 20);
this.txtUsername.TabIndex = 1;
this.tipOptional.SetToolTip(this.txtUsername, "Enter your Alfresco username here if you want to be automatically logged-on.");
this.txtUsername.TextChanged += new System.EventHandler(this.txtUsername_TextChanged);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(6, 21);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(55, 13);
this.label1.TabIndex = 0;
this.label1.Text = "Username";
//
// label6
//
this.label6.Location = new System.Drawing.Point(7, 20);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(273, 87);
this.label6.TabIndex = 5;
this.label6.Text = resources.GetString("label6.Text");
//
// grpDetails
//
this.grpDetails.Controls.Add(this.txtCIFSServer);
this.grpDetails.Controls.Add(this.label5);
this.grpDetails.Controls.Add(this.txtWebDAVURL);
this.grpDetails.Controls.Add(this.label4);
this.grpDetails.Controls.Add(this.txtWebClientURL);
this.grpDetails.Controls.Add(this.label3);
this.grpDetails.Location = new System.Drawing.Point(12, 110);
this.grpDetails.Name = "grpDetails";
this.grpDetails.Size = new System.Drawing.Size(267, 165);
this.grpDetails.TabIndex = 4;
this.grpDetails.TabStop = false;
this.grpDetails.Text = "Location";
//
// txtCIFSServer
//
this.txtCIFSServer.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest;
this.txtCIFSServer.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.CustomSource;
this.txtCIFSServer.Location = new System.Drawing.Point(9, 125);
this.txtCIFSServer.Name = "txtCIFSServer";
this.txtCIFSServer.Size = new System.Drawing.Size(251, 20);
this.txtCIFSServer.TabIndex = 9;
this.tipOptional.SetToolTip(this.txtCIFSServer, "The UNC path, or mapped drive, to the Alfresco CIFS server.");
this.txtCIFSServer.TextChanged += new System.EventHandler(this.txtCIFSServer_TextChanged);
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(6, 109);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(67, 13);
this.label5.TabIndex = 8;
this.label5.Text = "CIFS Server:";
//
// txtWebDAVURL
//
this.txtWebDAVURL.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest;
this.txtWebDAVURL.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.CustomSource;
this.txtWebDAVURL.Location = new System.Drawing.Point(9, 81);
this.txtWebDAVURL.Name = "txtWebDAVURL";
this.txtWebDAVURL.Size = new System.Drawing.Size(251, 20);
this.txtWebDAVURL.TabIndex = 7;
this.tipMandatory.SetToolTip(this.txtWebDAVURL, "The URL for the Alfresco Web Client.");
this.txtWebDAVURL.TextChanged += new System.EventHandler(this.txtWebDAVURL_TextChanged);
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(6, 65);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(80, 13);
this.label4.TabIndex = 6;
this.label4.Text = "WebDAV URL:";
//
// txtWebClientURL
//
this.txtWebClientURL.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest;
this.txtWebClientURL.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.AllUrl;
this.txtWebClientURL.Location = new System.Drawing.Point(9, 37);
this.txtWebClientURL.Name = "txtWebClientURL";
this.txtWebClientURL.Size = new System.Drawing.Size(251, 20);
this.txtWebClientURL.TabIndex = 5;
this.tipMandatory.SetToolTip(this.txtWebClientURL, "The URL for the Alfresco Web Client.");
this.txtWebClientURL.TextChanged += new System.EventHandler(this.txtWebClientURL_TextChanged);
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(6, 21);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(87, 13);
this.label3.TabIndex = 4;
this.label3.Text = "Web Client URL:";
//
// tipGeneral
//
this.tipGeneral.AutoPopDelay = 5000;
this.tipGeneral.InitialDelay = 500;
this.tipGeneral.ReshowDelay = 100;
this.tipGeneral.ToolTipTitle = "Alfresco";
//
// tipMandatory
//
this.tipMandatory.AutoPopDelay = 5000;
this.tipMandatory.InitialDelay = 500;
this.tipMandatory.ReshowDelay = 100;
this.tipMandatory.ToolTipTitle = "Mandatory Setting";
//
// tipOptional
//
this.tipOptional.AutoPopDelay = 5000;
this.tipOptional.InitialDelay = 500;
this.tipOptional.ReshowDelay = 100;
this.tipOptional.ToolTipTitle = "Optional Setting";
//
// pnlWebBrowser
//
this.pnlWebBrowser.BackColor = System.Drawing.Color.White;
this.pnlWebBrowser.Controls.Add(this.webBrowser);
this.pnlWebBrowser.Dock = System.Windows.Forms.DockStyle.Fill;
this.pnlWebBrowser.Location = new System.Drawing.Point(0, 0);
this.pnlWebBrowser.Name = "pnlWebBrowser";
this.pnlWebBrowser.Size = new System.Drawing.Size(292, 689);
this.pnlWebBrowser.TabIndex = 8;
//
// webBrowser
//
this.webBrowser.AllowWebBrowserDrop = false;
this.webBrowser.Dock = System.Windows.Forms.DockStyle.Top;
this.webBrowser.Location = new System.Drawing.Point(0, 0);
this.webBrowser.MinimumSize = new System.Drawing.Size(20, 20);
this.webBrowser.Name = "webBrowser";
this.webBrowser.ScrollBarsEnabled = false;
this.webBrowser.Size = new System.Drawing.Size(292, 654);
this.webBrowser.TabIndex = 1;
this.webBrowser.WebBrowserShortcutsEnabled = false;
this.webBrowser.Navigated += new System.Windows.Forms.WebBrowserNavigatedEventHandler(this.webBrowser_Navigated);
//
// AlfrescoPane
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.White;
this.Controls.Add(this.pnlConfiguration);
this.Controls.Add(this.lnkShowConfiguration);
this.Controls.Add(this.pnlWebBrowser);
this.Name = "AlfrescoPane";
this.Size = new System.Drawing.Size(292, 689);
this.pnlConfiguration.ResumeLayout(false);
this.grpConfiguration.ResumeLayout(false);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.grpDetails.ResumeLayout(false);
this.grpDetails.PerformLayout();
this.pnlWebBrowser.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.LinkLabel lnkShowConfiguration;
private System.Windows.Forms.Panel pnlConfiguration;
private System.Windows.Forms.LinkLabel lnkBackToBrowser;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.GroupBox grpConfiguration;
private System.Windows.Forms.Button btnDetailsOK;
private System.Windows.Forms.Button btnDetailsCancel;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.CheckBox chkRememberAuth;
private System.Windows.Forms.TextBox txtPassword;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.TextBox txtUsername;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.GroupBox grpDetails;
private System.Windows.Forms.TextBox txtCIFSServer;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.TextBox txtWebDAVURL;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox txtWebClientURL;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.ToolTip tipGeneral;
private System.Windows.Forms.ToolTip tipMandatory;
private System.Windows.Forms.ToolTip tipOptional;
private System.Windows.Forms.Panel pnlWebBrowser;
private System.Windows.Forms.WebBrowser webBrowser;
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Data;
using System.Web;
using System.Collections;
using System.Collections.Generic;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.ComponentModel;
using Microsoft.Web.Services3;
using WebsitePanel.Providers;
using WebsitePanel.Providers.Web;
using WebsitePanel.Server.Utils;
using WebsitePanel.Providers.ResultObjects;
using WebsitePanel.Providers.WebAppGallery;
using WebsitePanel.Providers.Common;
using Microsoft.Web.Administration;
using Microsoft.Web.Management.Server;
namespace WebsitePanel.Server
{
/// <summary>
/// Summary description for WebServer
/// </summary>
[WebService(Namespace = "http://smbsaas/websitepanel/server/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[Policy("ServerPolicy")]
[ToolboxItem(false)]
public class WebServer : HostingServiceProviderWebService, IWebServer
{
private IWebServer WebProvider
{
get { return (IWebServer)Provider; }
}
#region Web Sites
[WebMethod, SoapHeader("settings")]
public void ChangeSiteState(string siteId, ServerState state)
{
try
{
Log.WriteStart("'{0}' ChangeSiteState", ProviderSettings.ProviderName);
WebProvider.ChangeSiteState(siteId, state);
Log.WriteEnd("'{0}' ChangeSiteState", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' ChangeSiteState", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public ServerState GetSiteState(string siteId)
{
try
{
Log.WriteStart("'{0}' GetSiteState", ProviderSettings.ProviderName);
ServerState result = WebProvider.GetSiteState(siteId);
Log.WriteEnd("'{0}' GetSiteState", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetSiteState", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public string GetSiteId(string siteName)
{
try
{
Log.WriteStart("'{0}' GetSiteId", ProviderSettings.ProviderName);
string result = WebProvider.GetSiteId(siteName);
Log.WriteEnd("'{0}' GetSiteId", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetSiteId", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public string[] GetSitesAccounts(string[] siteIds)
{
try
{
Log.WriteStart("'{0}' GetSitesAccounts", ProviderSettings.ProviderName);
string[] result = WebProvider.GetSitesAccounts(siteIds);
Log.WriteEnd("'{0}' GetSitesAccounts", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetSitesAccounts", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public bool SiteExists(string siteId)
{
try
{
Log.WriteStart("'{0}' SiteIdExists", ProviderSettings.ProviderName);
bool result = WebProvider.SiteExists(siteId);
Log.WriteEnd("'{0}' SiteIdExists", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' SiteIdExists", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public string[] GetSites()
{
try
{
Log.WriteStart("'{0}' GetSites", ProviderSettings.ProviderName);
string[] result = WebProvider.GetSites();
Log.WriteEnd("'{0}' GetSites", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetSites", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public WebSite GetSite(string siteId)
{
try
{
Log.WriteStart("'{0}' GetSite", ProviderSettings.ProviderName);
WebSite result = WebProvider.GetSite(siteId);
Log.WriteEnd("'{0}' GetSite", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetSite", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public ServerBinding[] GetSiteBindings(string siteId)
{
try
{
Log.WriteStart("'{0}' GetSiteBindings", ProviderSettings.ProviderName);
ServerBinding[] result = WebProvider.GetSiteBindings(siteId);
Log.WriteEnd("'{0}' GetSiteBindings", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetSiteBindings", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public string CreateSite(WebSite site)
{
try
{
Log.WriteStart("'{0}' CreateSite", ProviderSettings.ProviderName);
string result = WebProvider.CreateSite(site);
Log.WriteEnd("'{0}' CreateSite", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' CreateSite", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void UpdateSite(WebSite site)
{
try
{
Log.WriteStart("'{0}' UpdateSite", ProviderSettings.ProviderName);
WebProvider.UpdateSite(site);
Log.WriteEnd("'{0}' UpdateSite", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' UpdateSite", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void UpdateSiteBindings(string siteId, ServerBinding[] bindings, bool emptyBindingsAllowed)
{
try
{
Log.WriteStart("'{0}' UpdateSiteBindings", ProviderSettings.ProviderName);
WebProvider.UpdateSiteBindings(siteId, bindings, emptyBindingsAllowed);
Log.WriteEnd("'{0}' UpdateSiteBindings", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' UpdateSiteBindings", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void DeleteSite(string siteId)
{
try
{
Log.WriteStart("'{0}' DeleteSite", ProviderSettings.ProviderName);
WebProvider.DeleteSite(siteId);
Log.WriteEnd("'{0}' DeleteSite", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' DeleteSite", ProviderSettings.ProviderName), ex);
throw;
}
}
// AppPool
[WebMethod, SoapHeader("settings")]
public void ChangeAppPoolState(string siteId, AppPoolState state)
{
try
{
Log.WriteStart("'{0}' ChangeAppPoolState", ProviderSettings.ProviderName);
WebProvider.ChangeAppPoolState(siteId, state);
Log.WriteEnd("'{0}' ChangeAppPoolState", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' ChangeAppPoolState", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public AppPoolState GetAppPoolState(string siteId)
{
try
{
Log.WriteStart("'{0}' GetAppPoolState", ProviderSettings.ProviderName);
AppPoolState result = WebProvider.GetAppPoolState(siteId);
Log.WriteEnd("'{0}' GetAppPoolState", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetAppPoolState", ProviderSettings.ProviderName), ex);
throw;
}
}
#endregion
#region Virtual Directories
[WebMethod, SoapHeader("settings")]
public bool VirtualDirectoryExists(string siteId, string directoryName)
{
try
{
Log.WriteStart("'{0}' VirtualDirectoryExists", ProviderSettings.ProviderName);
bool result = WebProvider.VirtualDirectoryExists(siteId, directoryName);
Log.WriteEnd("'{0}' VirtualDirectoryExists", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' VirtualDirectoryExists", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public WebVirtualDirectory[] GetVirtualDirectories(string siteId)
{
try
{
Log.WriteStart("'{0}' GetVirtualDirectories", ProviderSettings.ProviderName);
WebVirtualDirectory[] result = WebProvider.GetVirtualDirectories(siteId);
Log.WriteEnd("'{0}' GetVirtualDirectories", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetVirtualDirectories", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public WebVirtualDirectory GetVirtualDirectory(string siteId, string directoryName)
{
try
{
Log.WriteStart("'{0}' GetVirtualDirectory", ProviderSettings.ProviderName);
WebVirtualDirectory result = WebProvider.GetVirtualDirectory(siteId, directoryName);
Log.WriteEnd("'{0}' GetVirtualDirectory", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetVirtualDirectory", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void CreateVirtualDirectory(string siteId, WebVirtualDirectory directory)
{
try
{
Log.WriteStart("'{0}' CreateVirtualDirectory", ProviderSettings.ProviderName);
WebProvider.CreateVirtualDirectory(siteId, directory);
Log.WriteEnd("'{0}' CreateVirtualDirectory", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' CreateVirtualDirectory", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void CreateEnterpriseStorageVirtualDirectory(string siteId, WebVirtualDirectory directory)
{
try
{
Log.WriteStart("'{0}' CreateEnterpriseStorageVirtualDirectory", ProviderSettings.ProviderName);
WebProvider.CreateEnterpriseStorageVirtualDirectory(siteId, directory);
Log.WriteEnd("'{0}' CreateEnterpriseStorageVirtualDirectory", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' CreateEnterpriseStorageVirtualDirectory", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void UpdateVirtualDirectory(string siteId, WebVirtualDirectory directory)
{
try
{
Log.WriteStart("'{0}' UpdateVirtualDirectory", ProviderSettings.ProviderName);
WebProvider.UpdateVirtualDirectory(siteId, directory);
Log.WriteEnd("'{0}' UpdateVirtualDirectory", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' UpdateVirtualDirectory", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void DeleteVirtualDirectory(string siteId, string directoryName)
{
try
{
Log.WriteStart("'{0}' DeleteVirtualDirectory", ProviderSettings.ProviderName);
WebProvider.DeleteVirtualDirectory(siteId, directoryName);
Log.WriteEnd("'{0}' DeleteVirtualDirectory", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' DeleteVirtualDirectory", ProviderSettings.ProviderName), ex);
throw;
}
}
#endregion
#region FrontPage
[WebMethod, SoapHeader("settings")]
public bool IsFrontPageSystemInstalled()
{
try
{
Log.WriteStart("'{0}' IsFrontPageSystemInstalled", ProviderSettings.ProviderName);
bool result = WebProvider.IsFrontPageSystemInstalled();
Log.WriteEnd("'{0}' IsFrontPageSystemInstalled", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' IsFrontPageSystemInstalled", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public bool IsFrontPageInstalled(string siteId)
{
try
{
Log.WriteStart("'{0}' IsFrontPageInstalled", ProviderSettings.ProviderName);
bool result = WebProvider.IsFrontPageInstalled(siteId);
Log.WriteEnd("'{0}' IsFrontPageInstalled", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' IsFrontPageInstalled", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public bool InstallFrontPage(string siteId, string username, string password)
{
try
{
Log.WriteStart("'{0}' InstallFrontPage", ProviderSettings.ProviderName);
bool result = WebProvider.InstallFrontPage(siteId, username, password);
Log.WriteEnd("'{0}' InstallFrontPage", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' InstallFrontPage", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void UninstallFrontPage(string siteId, string username)
{
try
{
Log.WriteStart("'{0}' UninstallFrontPage", ProviderSettings.ProviderName);
WebProvider.UninstallFrontPage(siteId, username);
Log.WriteEnd("'{0}' UninstallFrontPage", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' UninstallFrontPage", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void ChangeFrontPagePassword(string username, string password)
{
try
{
Log.WriteStart("'{0}' ChangeFrontPagePassword", ProviderSettings.ProviderName);
WebProvider.ChangeFrontPagePassword(username, password);
Log.WriteEnd("'{0}' ChangeFrontPagePassword", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' ChangeFrontPagePassword", ProviderSettings.ProviderName), ex);
throw;
}
}
#endregion
#region ColdFusion
[WebMethod, SoapHeader("settings")]
public bool IsColdFusionSystemInstalled()
{
try
{
Log.WriteStart("'{0}' IsColdFusionSystemInstalled", ProviderSettings.ProviderName);
bool result = WebProvider.IsColdFusionSystemInstalled();
Log.WriteEnd("'{0}' IsColdFusionSystemInstalled", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' IsColdFusionSystemInstalled", ProviderSettings.ProviderName), ex);
throw;
}
}
#endregion
#region Permissions
[WebMethod, SoapHeader("settings")]
public void GrantWebSiteAccess(string path, string siteId, NTFSPermission permission)
{
try
{
Log.WriteStart("'{0}' GrantWebSiteAccess", ProviderSettings.ProviderName);
WebProvider.GrantWebSiteAccess(path, siteId, permission);
Log.WriteEnd("'{0}' GrantWebSiteAccess", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GrantWebSiteAccess", ProviderSettings.ProviderName), ex);
throw;
}
}
#endregion
#region Secured Folders
[WebMethod, SoapHeader("settings")]
public void InstallSecuredFolders(string siteId)
{
try
{
Log.WriteStart("'{0}' InstallSecuredFolders", ProviderSettings.ProviderName);
WebProvider.InstallSecuredFolders(siteId);
Log.WriteEnd("'{0}' InstallSecuredFolders", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' InstallSecuredFolders", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void UninstallSecuredFolders(string siteId)
{
try
{
Log.WriteStart("'{0}' UninstallSecuredFolders", ProviderSettings.ProviderName);
WebProvider.UninstallSecuredFolders(siteId);
Log.WriteEnd("'{0}' UninstallSecuredFolders", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' UninstallSecuredFolders", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public List<WebFolder> GetFolders(string siteId)
{
try
{
Log.WriteStart("'{0}' GetFolders", ProviderSettings.ProviderName);
List<WebFolder> result = WebProvider.GetFolders(siteId);
Log.WriteEnd("'{0}' GetFolders", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetFolders", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public WebFolder GetFolder(string siteId, string folderPath)
{
try
{
Log.WriteStart("'{0}' GetFolder", ProviderSettings.ProviderName);
WebFolder result = WebProvider.GetFolder(siteId, folderPath);
Log.WriteEnd("'{0}' GetFolder", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetFolder", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void UpdateFolder(string siteId, WebFolder folder)
{
try
{
Log.WriteStart("'{0}' UpdateFolder", ProviderSettings.ProviderName);
WebProvider.UpdateFolder(siteId, folder);
Log.WriteEnd("'{0}' UpdateFolder", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' UpdateFolder", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void DeleteFolder(string siteId, string folderPath)
{
try
{
Log.WriteStart("'{0}' DeleteFolder", ProviderSettings.ProviderName);
WebProvider.DeleteFolder(siteId, folderPath);
Log.WriteEnd("'{0}' DeleteFolder", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' DeleteFolder", ProviderSettings.ProviderName), ex);
throw;
}
}
#endregion
#region Secured Users
[WebMethod, SoapHeader("settings")]
public List<WebUser> GetUsers(string siteId)
{
try
{
Log.WriteStart("'{0}' GetUsers", ProviderSettings.ProviderName);
List<WebUser> result = WebProvider.GetUsers(siteId);
Log.WriteEnd("'{0}' GetUsers", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetUsers", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public WebUser GetUser(string siteId, string userName)
{
try
{
Log.WriteStart("'{0}' GetUser", ProviderSettings.ProviderName);
WebUser result = WebProvider.GetUser(siteId, userName);
Log.WriteEnd("'{0}' GetUser", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetUser", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void UpdateUser(string siteId, WebUser user)
{
try
{
Log.WriteStart("'{0}' UpdateUser", ProviderSettings.ProviderName);
WebProvider.UpdateUser(siteId, user);
Log.WriteEnd("'{0}' UpdateUser", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' UpdateUser", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void DeleteUser(string siteId, string userName)
{
try
{
Log.WriteStart("'{0}' DeleteUser", ProviderSettings.ProviderName);
WebProvider.DeleteUser(siteId, userName);
Log.WriteEnd("'{0}' DeleteUser", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' DeleteUser", ProviderSettings.ProviderName), ex);
throw;
}
}
#endregion
#region Secured Groups
[WebMethod, SoapHeader("settings")]
public List<WebGroup> GetGroups(string siteId)
{
try
{
Log.WriteStart("'{0}' GetGroups", ProviderSettings.ProviderName);
List<WebGroup> result = WebProvider.GetGroups(siteId);
Log.WriteEnd("'{0}' GetGroups", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetGroups", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public WebGroup GetGroup(string siteId, string groupName)
{
try
{
Log.WriteStart("'{0}' GetGroup", ProviderSettings.ProviderName);
WebGroup result = WebProvider.GetGroup(siteId, groupName);
Log.WriteEnd("'{0}' GetGroup", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetGroup", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void UpdateGroup(string siteId, WebGroup group)
{
try
{
Log.WriteStart("'{0}' UpdateGroup", ProviderSettings.ProviderName);
WebProvider.UpdateGroup(siteId, group);
Log.WriteEnd("'{0}' UpdateGroup", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' UpdateGroup", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void DeleteGroup(string siteId, string groupName)
{
try
{
Log.WriteStart("'{0}' DeleteGroup", ProviderSettings.ProviderName);
WebProvider.DeleteGroup(siteId, groupName);
Log.WriteEnd("'{0}' DeleteGroup", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' DeleteGroup", ProviderSettings.ProviderName), ex);
throw;
}
}
#endregion
#region Helicon Ape
[WebMethod, SoapHeader("settings")]
public HeliconApeStatus GetHeliconApeStatus(string siteId)
{
HeliconApeStatus status;
try
{
Log.WriteStart("'{0}' GetHeliconApeStatus", ProviderSettings.ProviderName);
status = WebProvider.GetHeliconApeStatus(siteId);
Log.WriteEnd("'{0}' GetHeliconApeStatus", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetHeliconApeStatus", ProviderSettings.ProviderName), ex);
throw;
}
return status;
}
[WebMethod, SoapHeader("settings")]
public void InstallHeliconApe(string ServiceId)
{
try
{
Log.WriteStart("'{0}' InstallHeliconApe", ProviderSettings.ProviderName);
WebProvider.InstallHeliconApe(ServiceId);
Log.WriteEnd("'{0}' InstallHeliconApe", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' InstallHeliconApe", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void EnableHeliconApe(string siteId)
{
try
{
Log.WriteStart("'{0}' EnableHeliconApe", ProviderSettings.ProviderName);
WebProvider.EnableHeliconApe(siteId);
Log.WriteEnd("'{0}' EnableHeliconApe", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' EnableHeliconApe", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void DisableHeliconApe(string siteId)
{
try
{
Log.WriteStart("'{0}' DisableHeliconApe", ProviderSettings.ProviderName);
WebProvider.DisableHeliconApe(siteId);
Log.WriteEnd("'{0}' DisableHeliconApe", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' DisableHeliconApe", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public List<HtaccessFolder> GetHeliconApeFolders(string siteId)
{
try
{
Log.WriteStart("'{0}' GetHeliconApeFolders", ProviderSettings.ProviderName);
List<HtaccessFolder> result = WebProvider.GetHeliconApeFolders(siteId);
Log.WriteEnd("'{0}' GetHeliconApeFolders", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetHeliconApeFolders", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public HtaccessFolder GetHeliconApeHttpdFolder()
{
try
{
Log.WriteStart("'{0}' GetHeliconApeFolder", ProviderSettings.ProviderName);
HtaccessFolder result = WebProvider.GetHeliconApeHttpdFolder();
Log.WriteEnd("'{0}' GetHeliconApeFolder", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetHeliconApeFolder", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public HtaccessFolder GetHeliconApeFolder(string siteId, string folderPath)
{
try
{
Log.WriteStart("'{0}' GetHeliconApeFolder", ProviderSettings.ProviderName);
HtaccessFolder result = WebProvider.GetHeliconApeFolder(siteId, folderPath);
Log.WriteEnd("'{0}' GetHeliconApeFolder", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetHeliconApeFolder", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void UpdateHeliconApeFolder(string siteId, HtaccessFolder folder)
{
try
{
Log.WriteStart("'{0}' UpdateHeliconApeFolder", ProviderSettings.ProviderName);
WebProvider.UpdateHeliconApeFolder(siteId, folder);
Log.WriteEnd("'{0}' UpdateHeliconApeFolder", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' UpdateHeliconApeFolder", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void UpdateHeliconApeHttpdFolder(HtaccessFolder folder)
{
try
{
Log.WriteStart("'{0}' UpdateHeliconApeHttpdFolder", ProviderSettings.ProviderName);
WebProvider.UpdateHeliconApeHttpdFolder(folder);
Log.WriteEnd("'{0}' UpdateHeliconApeHttpdFolder", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' UpdateHeliconApeHttpdFolder", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void DeleteHeliconApeFolder(string siteId, string folderPath)
{
try
{
Log.WriteStart("'{0}' DeleteHeliconApeFolder", ProviderSettings.ProviderName);
WebProvider.DeleteHeliconApeFolder(siteId, folderPath);
Log.WriteEnd("'{0}' DeleteHeliconApeFolder", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' DeleteHeliconApeFolder", ProviderSettings.ProviderName), ex);
throw;
}
}
#endregion
#region Helicon Ape Users
[WebMethod, SoapHeader("settings")]
public List<HtaccessUser> GetHeliconApeUsers(string siteId)
{
try
{
Log.WriteStart("'{0}' GetHeliconApeUsers", ProviderSettings.ProviderName);
List<HtaccessUser> result = WebProvider.GetHeliconApeUsers(siteId);
Log.WriteEnd("'{0}' GetHeliconApeUsers", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GeHeliconApetUsers", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public HtaccessUser GetHeliconApeUser(string siteId, string userName)
{
try
{
Log.WriteStart("'{0}' GetHeliconApeUser", ProviderSettings.ProviderName);
HtaccessUser result = WebProvider.GetHeliconApeUser(siteId, userName);
Log.WriteEnd("'{0}' GetHeliconApeUser", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetHeliconApeUser", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void UpdateHeliconApeUser(string siteId, HtaccessUser user)
{
try
{
Log.WriteStart("'{0}' UpdateHeliconApeUser", ProviderSettings.ProviderName);
WebProvider.UpdateHeliconApeUser(siteId, user);
Log.WriteEnd("'{0}' UpdateHeliconApeUser", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' UpdateHeliconApeUser", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void DeleteHeliconApeUser(string siteId, string userName)
{
try
{
Log.WriteStart("'{0}' DeleteHeliconApeUser", ProviderSettings.ProviderName);
WebProvider.DeleteHeliconApeUser(siteId, userName);
Log.WriteEnd("'{0}' DeleteHeliconApeUser", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' DeleteHeliconApeUser", ProviderSettings.ProviderName), ex);
throw;
}
}
#endregion
#region Helicon Ape Groups
[WebMethod, SoapHeader("settings")]
public List<WebGroup> GetHeliconApeGroups(string siteId)
{
try
{
Log.WriteStart("'{0}' GetHeliconApeGroups", ProviderSettings.ProviderName);
List<WebGroup> result = WebProvider.GetHeliconApeGroups(siteId);
Log.WriteEnd("'{0}' GetHeliconApeGroups", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetHeliconApeGroups", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public WebGroup GetHeliconApeGroup(string siteId, string groupName)
{
try
{
Log.WriteStart("'{0}' GetHeliconApeGroup", ProviderSettings.ProviderName);
WebGroup result = WebProvider.GetHeliconApeGroup(siteId, groupName);
Log.WriteEnd("'{0}' GetHeliconApeGroup", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetHeliconApeGroup", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void UpdateHeliconApeGroup(string siteId, WebGroup group)
{
try
{
Log.WriteStart("'{0}' UpdateHeliconApeGroup", ProviderSettings.ProviderName);
WebProvider.UpdateHeliconApeGroup(siteId, group);
Log.WriteEnd("'{0}' UpdateHeliconApeGroup", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' UpdateHeliconApeGroup", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void GrantWebDeployPublishingAccess(string siteId, string accountName, string accountPassword)
{
try
{
Log.WriteStart("'{0}' GrantWebDeployPublishingAccess", ProviderSettings.ProviderName);
WebProvider.GrantWebDeployPublishingAccess(siteId, accountName, accountPassword);
Log.WriteEnd("'{0}' GrantWebDeployPublishingAccess", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GrantWebDeployPublishingAccess", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void RevokeWebDeployPublishingAccess(string siteId, string accountName)
{
try
{
Log.WriteStart("'{0}' RevokeWebDeployPublishingAccess", ProviderSettings.ProviderName);
WebProvider.RevokeWebDeployPublishingAccess(siteId, accountName);
Log.WriteEnd("'{0}' RevokeWebDeployPublishingAccess", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' RevokeWebDeployPublishingAccess", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void DeleteHeliconApeGroup(string siteId, string groupName)
{
try
{
Log.WriteStart("'{0}' DeleteHeliconApeGroup", ProviderSettings.ProviderName);
WebProvider.DeleteHeliconApeGroup(siteId, groupName);
Log.WriteEnd("'{0}' DeleteHeliconApeGroup", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' DeleteHeliconApeGroup", ProviderSettings.ProviderName), ex);
throw;
}
}
#endregion
#region Helicon Zoo
[WebMethod, SoapHeader("settings")]
public WebVirtualDirectory[] GetZooApplications(string siteId)
{
try
{
Log.WriteStart("'{0}' GetZooApplications", ProviderSettings.ProviderName);
WebVirtualDirectory[] result = WebProvider.GetZooApplications(siteId);
Log.WriteEnd("'{0}' GetZooApplications", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetZooApplications", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public StringResultObject SetZooEnvironmentVariable(string siteId, string appName, string envName, string envValue)
{
try
{
Log.WriteStart("'{0}' SetZooEnvironmentVariable", ProviderSettings.ProviderName);
StringResultObject result = WebProvider.SetZooEnvironmentVariable(siteId, appName, envName, envValue);
Log.WriteEnd("'{0}' SetZooEnvironmentVariable", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' SetZooEnvironmentVariable", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public StringResultObject SetZooConsoleEnabled(string siteId, string appName)
{
try
{
Log.WriteStart("'{0}' SetZooConsoleEnabled", ProviderSettings.ProviderName);
StringResultObject result = WebProvider.SetZooConsoleEnabled(siteId, appName);
Log.WriteEnd("'{0}' SetZooConsoleEnabled", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' SetZooConsoleEnabled", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public StringResultObject SetZooConsoleDisabled(string siteId, string appName)
{
try
{
Log.WriteStart("'{0}' SetZooConsoleDisabled", ProviderSettings.ProviderName);
StringResultObject result = WebProvider.SetZooConsoleDisabled(siteId, appName);
Log.WriteEnd("'{0}' SetZooConsoleDisabled", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' SetZooConsoleDisabled", ProviderSettings.ProviderName), ex);
throw;
}
}
#endregion
#region Web Application Gallery
[WebMethod, SoapHeader("settings")]
public bool CheckLoadUserProfile()
{
try
{
Log.WriteStart("CheckLoadUserProfile");
bool bResult = WebProvider.CheckLoadUserProfile();
Log.WriteEnd("CheckLoadUserProfile");
return bResult;
}
catch (Exception ex)
{
Log.WriteError("CheckLoadUserProfile", ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void EnableLoadUserProfile()
{
try
{
Log.WriteStart("EnableLoadUserProfile");
WebProvider.EnableLoadUserProfile();
Log.WriteEnd("EnableLoadUserProfile");
}
catch (Exception ex)
{
Log.WriteError("EnableLoadUserProfile", ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void InitFeeds(int UserId, string[] feeds)
{
try
{
Log.WriteStart("'{0}' InitFeeds", ProviderSettings.ProviderName);
WebProvider.InitFeeds(UserId, feeds);
Log.WriteEnd("'{0}' InitFeeds", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' InitFeeds", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void SetResourceLanguage(int UserId, string resourceLanguage)
{
try
{
Log.WriteStart("'{0}' SetResourceLanguage", ProviderSettings.ProviderName);
WebProvider.SetResourceLanguage(UserId,resourceLanguage);
Log.WriteEnd("'{0}' SetResourceLanguage", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' SetResourceLanguage", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public GalleryLanguagesResult GetGalleryLanguages(int UserId)
{
try
{
Log.WriteStart("'{0}' GalleryLanguagesResult", ProviderSettings.ProviderName);
GalleryLanguagesResult result = WebProvider.GetGalleryLanguages(UserId);
Log.WriteEnd("'{0}' GalleryLanguagesResult", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GalleryLanguagesResult", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public GalleryCategoriesResult GetGalleryCategories(int UserId)
{
try
{
Log.WriteStart("'{0}' GalleryCategoriesResult", ProviderSettings.ProviderName);
GalleryCategoriesResult result = WebProvider.GetGalleryCategories(UserId);
Log.WriteEnd("'{0}' GalleryCategoriesResult", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GalleryCategoriesResult", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public GalleryApplicationsResult GetGalleryApplications(int UserId, string categoryId)
{
try
{
Log.WriteStart("'{0}' GetGalleryApplications", ProviderSettings.ProviderName);
GalleryApplicationsResult result = WebProvider.GetGalleryApplications(UserId,categoryId);
Log.WriteEnd("'{0}' GetGalleryApplications", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetGalleryApplications", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public GalleryApplicationsResult GetGalleryApplicationsFiltered(int UserId, string pattern)
{
try
{
Log.WriteStart("'{0}' GetGalleryApplicationsFiltered", ProviderSettings.ProviderName);
GalleryApplicationsResult result = WebProvider.GetGalleryApplicationsFiltered(UserId,pattern);
Log.WriteEnd("'{0}' GetGalleryApplicationsFiltered", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetGalleryApplicationsFiltered", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public bool IsMsDeployInstalled()
{
try
{
Log.WriteStart("'{0}' IsMsDeployInstalled", ProviderSettings.ProviderName);
bool result = WebProvider.IsMsDeployInstalled();
Log.WriteEnd("'{0}' IsMsDeployInstalled", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' IsMsDeployInstalled", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public GalleryApplicationResult GetGalleryApplication(int UserId, string id)
{
try
{
Log.WriteStart("'{0}' GetGalleryApplication", ProviderSettings.ProviderName);
GalleryApplicationResult result = WebProvider.GetGalleryApplication(UserId,id);
Log.WriteEnd("'{0}' GetGalleryApplication", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetGalleryApplication", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public GalleryWebAppStatus GetGalleryApplicationStatus(int UserId, string id)
{
try
{
Log.WriteStart("'{0}' GetGalleryApplicationStatus", ProviderSettings.ProviderName);
GalleryWebAppStatus result = WebProvider.GetGalleryApplicationStatus(UserId,id);
Log.WriteEnd("'{0}' GetGalleryApplicationStatus", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetGalleryApplicationStatus", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public GalleryWebAppStatus DownloadGalleryApplication(int UserId, string id)
{
try
{
Log.WriteStart("'{0}' DownloadGalleryApplication", ProviderSettings.ProviderName);
GalleryWebAppStatus result = WebProvider.DownloadGalleryApplication(UserId,id);
Log.WriteEnd("'{0}' DownloadGalleryApplication", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' DownloadGalleryApplication", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public DeploymentParametersResult GetGalleryApplicationParameters(int UserId, string id)
{
try
{
Log.WriteStart("'{0}' GetGalleryApplicationParameters", ProviderSettings.ProviderName);
DeploymentParametersResult result = WebProvider.GetGalleryApplicationParameters(UserId,id);
Log.WriteEnd("'{0}' GetGalleryApplicationParameters", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetGalleryApplicationParameters", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public StringResultObject InstallGalleryApplication(int UserId, string id, List<DeploymentParameter> updatedValues, string languageId)
{
try
{
Log.WriteStart("'{0}' InstallGalleryApplication", ProviderSettings.ProviderName);
StringResultObject result = WebProvider.InstallGalleryApplication(UserId,id, updatedValues, languageId);
Log.WriteEnd("'{0}' InstallGalleryApplication", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' InstallGalleryApplication", ProviderSettings.ProviderName), ex);
throw;
}
}
#endregion
#region WebManagement Access
[WebMethod, SoapHeader("settings")]
public bool CheckWebManagementAccountExists(string accountName)
{
try
{
bool accountExists;
//
Log.WriteStart("'{0}' CheckWebManagementAccountExtsts", ProviderSettings.ProviderName);
//
accountExists = WebProvider.CheckWebManagementAccountExists(accountName);
//
Log.WriteEnd("'{0}' CheckWebManagementAccountExtsts", ProviderSettings.ProviderName);
//
return accountExists;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' CheckWebManagementAccountExtsts", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public ResultObject CheckWebManagementPasswordComplexity(string accountPassword)
{
try
{
ResultObject result;
Log.WriteStart("'{0}' CheckWebManagementPasswordComplexity", ProviderSettings.ProviderName);
result = WebProvider.CheckWebManagementPasswordComplexity(accountPassword);
Log.WriteEnd("'{0}' CheckWebManagementPasswordComplexity", ProviderSettings.ProviderName);
//
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' CheckWebManagementPasswordComplexity", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void GrantWebManagementAccess(string siteId, string accountName, string accountPassword)
{
try
{
Log.WriteStart("'{0}' GrantWebManagementAccess", ProviderSettings.ProviderName);
WebProvider.GrantWebManagementAccess(siteId, accountName, accountPassword);
Log.WriteEnd("'{0}' GrantWebManagementAccess", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GrantWebManagementAccess", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void RevokeWebManagementAccess(string siteId, string accountName)
{
try
{
Log.WriteStart("'{0}' RevokeWebManagementAccess", ProviderSettings.ProviderName);
WebProvider.RevokeWebManagementAccess(siteId, accountName);
Log.WriteEnd("'{0}' RevokeWebManagementAccess", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' RevokeWebManagementAccess", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void ChangeWebManagementAccessPassword(string accountName, string accountPassword)
{
try
{
Log.WriteStart("'{0}' ChangeWebManagementAccessPassword", ProviderSettings.ProviderName);
WebProvider.ChangeWebManagementAccessPassword(accountName, accountPassword);
Log.WriteEnd("'{0}' ChangeWebManagementAccessPassword", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' ChangeWebManagementAccessPassword", ProviderSettings.ProviderName), ex);
throw;
}
}
#endregion
#region SSL Management
[WebMethod, SoapHeader("settings")]
public SSLCertificate generateCSR(SSLCertificate certificate)
{
try
{
Log.WriteStart("'{0}' generateCSR", ProviderSettings.ProviderName);
certificate = WebProvider.generateCSR(certificate);
Log.WriteEnd("'{0}' generateCSR", ProviderSettings.ProviderName);
return certificate;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' generateCSR", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public SSLCertificate generateRenewalCSR(SSLCertificate certificate)
{
try
{
Log.WriteStart("'{0}' generateCSR", ProviderSettings.ProviderName);
certificate = WebProvider.generateCSR(certificate);
Log.WriteEnd("'{0}' generateCSR", ProviderSettings.ProviderName);
return certificate;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' generateCSR", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public SSLCertificate getCertificate(WebSite site)
{
throw new NotImplementedException();
}
[WebMethod, SoapHeader("settings")]
public SSLCertificate installCertificate(SSLCertificate certificate, WebSite website)
{
try
{
Log.WriteStart("'{0}' installCertificate", ProviderSettings.ProviderName);
SSLCertificate result = WebProvider.installCertificate(certificate, website);
Log.WriteEnd("'{0}' installCertificate", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' generateCSR", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public SSLCertificate installPFX(byte[] certificate, string password, WebSite website)
{
try
{
Log.WriteStart("'{0}' installPFX", ProviderSettings.ProviderName);
SSLCertificate response = WebProvider.installPFX(certificate, password, website);
if (response.Hash == null)
{
Log.WriteError(String.Format("'{0}' installPFX", ProviderSettings.ProviderName), null);
}
else
{
Log.WriteEnd("'{0}' installPFX", ProviderSettings.ProviderName);
}
return response;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' generateCSR", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public byte[] exportCertificate(string serialNumber, string password)
{
return WebProvider.exportCertificate(serialNumber, password);
}
[WebMethod, SoapHeader("settings")]
public List<SSLCertificate> getServerCertificates()
{
return WebProvider.getServerCertificates();
}
[WebMethod, SoapHeader("settings")]
public ResultObject DeleteCertificate(SSLCertificate certificate, WebSite website)
{
return WebProvider.DeleteCertificate(certificate, website);
}
[WebMethod, SoapHeader("settings")]
public SSLCertificate ImportCertificate(WebSite website)
{
return WebProvider.ImportCertificate(website);
}
[WebMethod, SoapHeader("settings")]
public bool CheckCertificate(WebSite webSite)
{
return WebProvider.CheckCertificate(webSite);
}
#endregion
#region Directory Browsing
[WebMethod, SoapHeader("settings")]
public bool GetDirectoryBrowseEnabled(string siteId)
{
return WebProvider.GetDirectoryBrowseEnabled(siteId);
}
[WebMethod, SoapHeader("settings")]
public void SetDirectoryBrowseEnabled(string siteId, bool enabled)
{
WebProvider.SetDirectoryBrowseEnabled(siteId, enabled);
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#if !FEATURE_NETNATIVE
using System.Collections.Generic;
using System.IdentityModel.Policy;
using System.Runtime;
using System.Security;
using System.Security.Principal;
using System.ServiceModel;
namespace System.IdentityModel.Claims
{
public class WindowsClaimSet : ClaimSet, IIdentityInfo, IDisposable
{
internal const bool DefaultIncludeWindowsGroups = true;
private WindowsIdentity _windowsIdentity;
private DateTime _expirationTime;
private bool _includeWindowsGroups;
private IList<Claim> _claims;
private bool _disposed = false;
private string _authenticationType;
public WindowsClaimSet(WindowsIdentity windowsIdentity)
: this(windowsIdentity, DefaultIncludeWindowsGroups)
{
}
public WindowsClaimSet(WindowsIdentity windowsIdentity, bool includeWindowsGroups)
: this(windowsIdentity, includeWindowsGroups, DateTime.UtcNow.AddHours(10))
{
}
public WindowsClaimSet(WindowsIdentity windowsIdentity, DateTime expirationTime)
: this(windowsIdentity, DefaultIncludeWindowsGroups, expirationTime)
{
}
public WindowsClaimSet(WindowsIdentity windowsIdentity, bool includeWindowsGroups, DateTime expirationTime)
: this(windowsIdentity, null, includeWindowsGroups, expirationTime, true)
{
}
public WindowsClaimSet(WindowsIdentity windowsIdentity, string authenticationType, bool includeWindowsGroups, DateTime expirationTime)
: this( windowsIdentity, authenticationType, includeWindowsGroups, expirationTime, true )
{
}
internal WindowsClaimSet(WindowsIdentity windowsIdentity, string authenticationType, bool includeWindowsGroups, bool clone)
: this( windowsIdentity, authenticationType, includeWindowsGroups, DateTime.UtcNow.AddHours( 10 ), clone )
{
}
internal WindowsClaimSet(WindowsIdentity windowsIdentity, string authenticationType, bool includeWindowsGroups, DateTime expirationTime, bool clone)
{
if (windowsIdentity == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("windowsIdentity");
_windowsIdentity = clone ? SecurityUtils.CloneWindowsIdentityIfNecessary(windowsIdentity, authenticationType) : windowsIdentity;
_includeWindowsGroups = includeWindowsGroups;
_expirationTime = expirationTime;
_authenticationType = authenticationType;
}
private WindowsClaimSet(WindowsClaimSet from)
: this(from.WindowsIdentity, from._authenticationType, from._includeWindowsGroups, from._expirationTime, true)
{
}
public override Claim this[int index]
{
get
{
ThrowIfDisposed();
EnsureClaims();
return _claims[index];
}
}
public override int Count
{
get
{
ThrowIfDisposed();
EnsureClaims();
return _claims.Count;
}
}
IIdentity IIdentityInfo.Identity
{
get
{
ThrowIfDisposed();
return _windowsIdentity;
}
}
public WindowsIdentity WindowsIdentity
{
get
{
ThrowIfDisposed();
return _windowsIdentity;
}
}
public override ClaimSet Issuer
{
get { return ClaimSet.Windows; }
}
public DateTime ExpirationTime
{
get { return _expirationTime; }
}
internal WindowsClaimSet Clone()
{
ThrowIfDisposed();
return new WindowsClaimSet(this);
}
public void Dispose()
{
if (!_disposed)
{
_disposed = true;
_windowsIdentity.Dispose();
}
}
IList<Claim> InitializeClaimsCore()
{
if (_windowsIdentity.AccessToken == null)
return new List<Claim>();
List<Claim> claims = new List<Claim>(3);
claims.Add(new Claim(ClaimTypes.Sid, _windowsIdentity.User, Rights.Identity));
Claim claim;
if (TryCreateWindowsSidClaim(_windowsIdentity, out claim))
{
claims.Add(claim);
}
claims.Add(Claim.CreateNameClaim(_windowsIdentity.Name));
if (_includeWindowsGroups)
{
// claims.AddRange(Groups);
}
return claims;
}
void EnsureClaims()
{
if (_claims != null)
return;
_claims = InitializeClaimsCore();
}
void ThrowIfDisposed()
{
if (_disposed)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(this.GetType().FullName));
}
}
static bool SupportedClaimType(string claimType)
{
return claimType == null ||
ClaimTypes.Sid == claimType ||
ClaimTypes.DenyOnlySid == claimType ||
ClaimTypes.Name == claimType;
}
// Note: null string represents any.
public override IEnumerable<Claim> FindClaims(string claimType, string right)
{
ThrowIfDisposed();
if (!SupportedClaimType(claimType) || !ClaimSet.SupportedRight(right))
{
yield break;
}
else if (_claims == null && (ClaimTypes.Sid == claimType || ClaimTypes.DenyOnlySid == claimType))
{
if (ClaimTypes.Sid == claimType)
{
if (right == null || Rights.Identity == right)
{
yield return new Claim(ClaimTypes.Sid, _windowsIdentity.User, Rights.Identity);
}
}
if (right == null || Rights.PossessProperty == right)
{
Claim sid;
if (TryCreateWindowsSidClaim(_windowsIdentity, out sid))
{
if (claimType == sid.ClaimType)
{
yield return sid;
}
}
}
if (_includeWindowsGroups && (right == null || Rights.PossessProperty == right))
{
// Not sure yet if GroupSidClaimCollections are necessary in .NET Core, but default
// _includeWindowsGroups is true; don't throw here or we bust the default case on UWP/.NET Core
}
}
else
{
EnsureClaims();
bool anyClaimType = (claimType == null);
bool anyRight = (right == null);
for (int i = 0; i < _claims.Count; ++i)
{
Claim claim = _claims[i];
if ((claim != null) &&
(anyClaimType || claimType == claim.ClaimType) &&
(anyRight || right == claim.Right))
{
yield return claim;
}
}
}
}
public override IEnumerator<Claim> GetEnumerator()
{
ThrowIfDisposed();
EnsureClaims();
return _claims.GetEnumerator();
}
public override string ToString()
{
return _disposed ? base.ToString() : SecurityUtils.ClaimSetToString(this);
}
public static bool TryCreateWindowsSidClaim(WindowsIdentity windowsIdentity, out Claim claim)
{
throw ExceptionHelper.PlatformNotSupported("CreateWindowsSidClaim is not yet supported");
}
}
}
#endif // !FEATURE_NETNATIVE
| |
//
// XwtComponent.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Reflection;
using Xwt.Backends;
using System.Threading;
namespace Xwt
{
/// <summary>
/// The base class for all Xwt components.
/// </summary>
[System.ComponentModel.DesignerCategory ("Code")]
public abstract class XwtComponent : Component, IFrontend, ISynchronizeInvoke
{
BackendHost backendHost;
public XwtComponent ()
{
backendHost = CreateBackendHost ();
backendHost.Parent = this;
}
/// <summary>
/// Creates the backend host.
/// </summary>
/// <returns>The backend host.</returns>
protected virtual BackendHost CreateBackendHost ()
{
return new BackendHost ();
}
/// <summary>
/// Gets the backend host.
/// </summary>
/// <value>The backend host.</value>
protected BackendHost BackendHost {
get { return backendHost; }
}
Toolkit IFrontend.ToolkitEngine {
get { return backendHost.ToolkitEngine; }
}
object IFrontend.Backend {
get { return backendHost.Backend; }
}
/// <summary>
/// A value, that can be used to identify this component
/// </summary>
public object Tag { get; set; }
/// <summary>
/// Maps an event handler of an Xwt component to an event identifier.
/// </summary>
/// <param name="eventId">The event identifier (must be valid event enum value
/// like <see cref="Xwt.Backends.WidgetEvent"/>, identifying component specific events).</param>
/// <param name="type">The Xwt component type.</param>
/// <param name="methodName">The <see cref="System.Reflection.MethodInfo.Name"/> of the event handler.</param>
protected static void MapEvent (object eventId, Type type, string methodName)
{
EventHost.MapEvent (eventId, type, methodName);
}
/// <summary>
/// Verifies that the constructor is not called from a sublass.
/// </summary>
/// <param name="t">This constructed base instance.</param>
/// <typeparam name="T">The base type to verify the constructor for.</typeparam>
internal void VerifyConstructorCall<T> (T t)
{
if (GetType () != typeof(T))
throw new InvalidConstructorInvocation (typeof(T));
}
#region ISynchronizeInvoke implementation
IAsyncResult ISynchronizeInvoke.BeginInvoke (Delegate method, object[] args)
{
var asyncResult = new AsyncInvokeResult ();
asyncResult.Invoke (method, args);
return asyncResult;
}
object ISynchronizeInvoke.EndInvoke (IAsyncResult result)
{
var xwtResult = result as AsyncInvokeResult;
if (xwtResult != null) {
xwtResult.AsyncResetEvent.Wait ();
if (xwtResult.Exception != null)
throw xwtResult.Exception;
} else {
result.AsyncWaitHandle.WaitOne ();
}
return result.AsyncState;
}
object ISynchronizeInvoke.Invoke (Delegate method, object[] args)
{
return ((ISynchronizeInvoke)this).EndInvoke (((ISynchronizeInvoke)this).BeginInvoke (method, args));
}
bool ISynchronizeInvoke.InvokeRequired {
get {
return Application.UIThread != Thread.CurrentThread;
}
}
#endregion
}
class AsyncInvokeResult : IAsyncResult
{
ManualResetEventSlim asyncResetEvent = new ManualResetEventSlim (false);
public AsyncInvokeResult ()
{
this.asyncResetEvent = new ManualResetEventSlim ();
}
internal void Invoke (Delegate method, object[] args)
{
Application.Invoke (delegate {
try {
AsyncState = method.DynamicInvoke(args);
} catch (Exception ex){
Exception = ex;
} finally {
IsCompleted = true;
asyncResetEvent.Set ();
}
});
}
#region IAsyncResult implementation
public object AsyncState {
get;
private set;
}
public Exception Exception {
get;
private set;
}
internal ManualResetEventSlim AsyncResetEvent {
get {
return asyncResetEvent;
}
}
public WaitHandle AsyncWaitHandle {
get {
if (asyncResetEvent == null) {
asyncResetEvent = new ManualResetEventSlim(false);
if (IsCompleted)
asyncResetEvent.Set();
}
return asyncResetEvent.WaitHandle;
}
}
public bool CompletedSynchronously { get { return false; } }
public bool IsCompleted {
get;
private set;
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Build.Execution;
using Microsoft.Build.Framework;
using Microsoft.Build.Logging;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Roslyn.Utilities;
using MSB = Microsoft.Build;
namespace Microsoft.CodeAnalysis.MSBuild
{
internal abstract class ProjectFile : IProjectFile
{
private readonly ProjectFileLoader _loader;
private readonly MSB.Evaluation.Project _loadedProject;
private readonly string _errorMessage;
public ProjectFile(ProjectFileLoader loader, MSB.Evaluation.Project loadedProject, string errorMessage)
{
_loader = loader;
_loadedProject = loadedProject;
_errorMessage = errorMessage;
}
~ProjectFile()
{
try
{
// unload project so collection will release global strings
_loadedProject.ProjectCollection.UnloadAllProjects();
}
catch
{
}
}
public virtual string FilePath
{
get { return _loadedProject.FullPath; }
}
public string ErrorMessage
{
get { return _errorMessage; }
}
public string GetPropertyValue(string name)
{
return _loadedProject.GetPropertyValue(name);
}
public abstract SourceCodeKind GetSourceCodeKind(string documentFileName);
public abstract string GetDocumentExtension(SourceCodeKind kind);
public abstract Task<ProjectFileInfo> GetProjectFileInfoAsync(CancellationToken cancellationToken);
async Task<IProjectFileInfo> IProjectFile.GetProjectFileInfoAsync(CancellationToken cancellationToken)
{
var t = this.GetProjectFileInfoAsync(cancellationToken);
await t.ConfigureAwait(false);
return t.Result as IProjectFileInfo;
}
public struct BuildInfo
{
public readonly ProjectInstance Project;
public readonly string ErrorMessage;
public BuildInfo(ProjectInstance project, string errorMessage)
{
this.Project = project;
this.ErrorMessage = errorMessage;
}
}
protected async Task<BuildInfo> BuildAsync(string taskName, MSB.Framework.ITaskHost taskHost, CancellationToken cancellationToken)
{
// create a project instance to be executed by build engine.
// The executed project will hold the final model of the project after execution via msbuild.
var executedProject = _loadedProject.CreateProjectInstance();
if (!executedProject.Targets.ContainsKey("Compile"))
{
return new BuildInfo(executedProject, null);
}
var hostServices = new Microsoft.Build.Execution.HostServices();
// connect the host "callback" object with the host services, so we get called back with the exact inputs to the compiler task.
hostServices.RegisterHostObject(_loadedProject.FullPath, "CoreCompile", taskName, taskHost);
var buildParameters = new BuildParameters(_loadedProject.ProjectCollection);
// capture errors that are output in the build log
var errorBuilder = new StringWriter();
var errorLogger = new ErrorLogger(errorBuilder) { Verbosity = LoggerVerbosity.Normal };
buildParameters.Loggers = new ILogger[] { errorLogger };
var buildRequestData = new BuildRequestData(executedProject, new string[] { "Compile" }, hostServices);
BuildResult result = await this.BuildAsync(buildParameters, buildRequestData, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
if (result.OverallResult == BuildResultCode.Failure)
{
if (result.Exception != null)
{
return new BuildInfo(executedProject, result.Exception.Message);
}
else
{
return new BuildInfo(executedProject, errorBuilder.ToString());
}
}
else
{
return new BuildInfo(executedProject, null);
}
}
private class ErrorLogger : ILogger
{
private readonly TextWriter _writer;
private bool _hasError;
private IEventSource _eventSource;
public string Parameters { get; set; }
public LoggerVerbosity Verbosity { get; set; }
public ErrorLogger(TextWriter writer)
{
_writer = writer;
}
public void Initialize(IEventSource eventSource)
{
_eventSource = eventSource;
_eventSource.ErrorRaised += OnErrorRaised;
}
private void OnErrorRaised(object sender, BuildErrorEventArgs e)
{
if (_hasError)
{
_writer.WriteLine();
}
_writer.Write($"{e.File}: ({e.LineNumber}, {e.ColumnNumber}): {e.Message}");
_hasError = true;
}
public void Shutdown()
{
if (_eventSource != null)
{
_eventSource.ErrorRaised -= OnErrorRaised;
}
}
}
// this lock is static because we are using the default build manager, and there is only one per process
private static readonly SemaphoreSlim s_buildManagerLock = new SemaphoreSlim(initialCount: 1);
private async Task<MSB.Execution.BuildResult> BuildAsync(MSB.Execution.BuildParameters parameters, MSB.Execution.BuildRequestData requestData, CancellationToken cancellationToken)
{
// only allow one build to use the default build manager at a time
using (await s_buildManagerLock.DisposableWaitAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))
{
return await BuildAsync(MSB.Execution.BuildManager.DefaultBuildManager, parameters, requestData, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
}
}
private static Task<MSB.Execution.BuildResult> BuildAsync(MSB.Execution.BuildManager buildManager, MSB.Execution.BuildParameters parameters, MSB.Execution.BuildRequestData requestData, CancellationToken cancellationToken)
{
var taskSource = new TaskCompletionSource<MSB.Execution.BuildResult>();
buildManager.BeginBuild(parameters);
// enable cancellation of build
CancellationTokenRegistration registration = default(CancellationTokenRegistration);
if (cancellationToken.CanBeCanceled)
{
registration = cancellationToken.Register(() =>
{
try
{
buildManager.CancelAllSubmissions();
buildManager.EndBuild();
registration.Dispose();
}
finally
{
taskSource.TrySetCanceled();
}
});
}
// execute build async
try
{
buildManager.PendBuildRequest(requestData).ExecuteAsync(sub =>
{
// when finished
try
{
var result = sub.BuildResult;
buildManager.EndBuild();
registration.Dispose();
taskSource.TrySetResult(result);
}
catch (Exception e)
{
taskSource.TrySetException(e);
}
}, null);
}
catch (Exception e)
{
taskSource.SetException(e);
}
return taskSource.Task;
}
protected virtual string GetOutputDirectory()
{
var targetPath = _loadedProject.GetPropertyValue("TargetPath");
if (string.IsNullOrEmpty(targetPath))
{
targetPath = _loadedProject.DirectoryPath;
}
return Path.GetDirectoryName(this.GetAbsolutePath(targetPath));
}
protected virtual string GetAssemblyName()
{
var assemblyName = _loadedProject.GetPropertyValue("AssemblyName");
if (string.IsNullOrEmpty(assemblyName))
{
assemblyName = Path.GetFileNameWithoutExtension(_loadedProject.FullPath);
}
return PathUtilities.GetFileName(assemblyName);
}
protected bool IsProjectReferenceOutputAssembly(MSB.Framework.ITaskItem item)
{
return item.GetMetadata("ReferenceOutputAssembly") == "true";
}
protected IEnumerable<ProjectFileReference> GetProjectReferences(ProjectInstance executedProject)
{
return executedProject
.GetItems("ProjectReference")
.Where(i => !string.Equals(
i.GetMetadataValue("ReferenceOutputAssembly"),
bool.FalseString,
StringComparison.OrdinalIgnoreCase))
.Select(CreateProjectFileReference);
}
/// <summary>
/// Create a <see cref="ProjectFileReference"/> from a ProjectReference node in the MSBuild file.
/// </summary>
protected virtual ProjectFileReference CreateProjectFileReference(ProjectItemInstance reference)
{
return new ProjectFileReference(
path: reference.EvaluatedInclude,
aliases: ImmutableArray<string>.Empty);
}
protected virtual IEnumerable<MSB.Framework.ITaskItem> GetDocumentsFromModel(MSB.Execution.ProjectInstance executedProject)
{
return executedProject.GetItems("Compile");
}
protected virtual IEnumerable<MSB.Framework.ITaskItem> GetMetadataReferencesFromModel(MSB.Execution.ProjectInstance executedProject)
{
return executedProject.GetItems("ReferencePath");
}
protected virtual IEnumerable<MSB.Framework.ITaskItem> GetAnalyzerReferencesFromModel(MSB.Execution.ProjectInstance executedProject)
{
return executedProject.GetItems("Analyzer");
}
protected virtual IEnumerable<MSB.Framework.ITaskItem> GetAdditionalFilesFromModel(MSB.Execution.ProjectInstance executedProject)
{
return executedProject.GetItems("AdditionalFiles");
}
public MSB.Evaluation.ProjectProperty GetProperty(string name)
{
return _loadedProject.GetProperty(name);
}
protected IEnumerable<MSB.Framework.ITaskItem> GetTaskItems(MSB.Execution.ProjectInstance executedProject, string itemType)
{
return executedProject.GetItems(itemType);
}
protected string GetItemString(MSB.Execution.ProjectInstance executedProject, string itemType)
{
string text = "";
foreach (var item in executedProject.GetItems(itemType))
{
if (text.Length > 0)
{
text = text + " ";
}
text = text + item.EvaluatedInclude;
}
return text;
}
protected string ReadPropertyString(MSB.Execution.ProjectInstance executedProject, string propertyName)
{
return this.ReadPropertyString(executedProject, propertyName, propertyName);
}
protected string ReadPropertyString(MSB.Execution.ProjectInstance executedProject, string executedPropertyName, string evaluatedPropertyName)
{
var executedProperty = executedProject.GetProperty(executedPropertyName);
if (executedProperty != null)
{
return executedProperty.EvaluatedValue;
}
var evaluatedProperty = _loadedProject.GetProperty(evaluatedPropertyName);
if (evaluatedProperty != null)
{
return evaluatedProperty.EvaluatedValue;
}
return null;
}
protected bool ReadPropertyBool(MSB.Execution.ProjectInstance executedProject, string propertyName)
{
return ConvertToBool(ReadPropertyString(executedProject, propertyName));
}
protected bool ReadPropertyBool(MSB.Execution.ProjectInstance executedProject, string executedPropertyName, string evaluatedPropertyName)
{
return ConvertToBool(ReadPropertyString(executedProject, executedPropertyName, evaluatedPropertyName));
}
private static bool ConvertToBool(string value)
{
return value != null && (string.Equals("true", value, StringComparison.OrdinalIgnoreCase) ||
string.Equals("On", value, StringComparison.OrdinalIgnoreCase));
}
protected int ReadPropertyInt(MSB.Execution.ProjectInstance executedProject, string propertyName)
{
return ConvertToInt(ReadPropertyString(executedProject, propertyName));
}
protected int ReadPropertyInt(MSB.Execution.ProjectInstance executedProject, string executedPropertyName, string evaluatedPropertyName)
{
return ConvertToInt(ReadPropertyString(executedProject, executedPropertyName, evaluatedPropertyName));
}
private static int ConvertToInt(string value)
{
if (value == null)
{
return 0;
}
else
{
int.TryParse(value, out var result);
return result;
}
}
protected ulong ReadPropertyULong(MSB.Execution.ProjectInstance executedProject, string propertyName)
{
return ConvertToULong(ReadPropertyString(executedProject, propertyName));
}
protected ulong ReadPropertyULong(MSB.Execution.ProjectInstance executedProject, string executedPropertyName, string evaluatedPropertyName)
{
return ConvertToULong(this.ReadPropertyString(executedProject, executedPropertyName, evaluatedPropertyName));
}
private static ulong ConvertToULong(string value)
{
if (value == null)
{
return 0;
}
else
{
ulong.TryParse(value, out var result);
return result;
}
}
protected TEnum? ReadPropertyEnum<TEnum>(MSB.Execution.ProjectInstance executedProject, string propertyName)
where TEnum : struct
{
return ConvertToEnum<TEnum>(ReadPropertyString(executedProject, propertyName));
}
protected TEnum? ReadPropertyEnum<TEnum>(MSB.Execution.ProjectInstance executedProject, string executedPropertyName, string evaluatedPropertyName)
where TEnum : struct
{
return ConvertToEnum<TEnum>(ReadPropertyString(executedProject, executedPropertyName, evaluatedPropertyName));
}
private static TEnum? ConvertToEnum<TEnum>(string value)
where TEnum : struct
{
if (value == null)
{
return null;
}
else
{
if (Enum.TryParse<TEnum>(value, out var result))
{
return result;
}
else
{
return null;
}
}
}
/// <summary>
/// Resolves the given path that is possibly relative to the project directory.
/// </summary>
/// <remarks>
/// The resulting path is absolute but might not be normalized.
/// </remarks>
protected string GetAbsolutePath(string path)
{
// TODO (tomat): should we report an error when drive-relative path (e.g. "C:foo.cs") is encountered?
return Path.GetFullPath(FileUtilities.ResolveRelativePath(path, _loadedProject.DirectoryPath) ?? path);
}
protected string GetDocumentFilePath(MSB.Framework.ITaskItem documentItem)
{
return GetAbsolutePath(documentItem.ItemSpec);
}
protected static bool IsDocumentLinked(MSB.Framework.ITaskItem documentItem)
{
return !string.IsNullOrEmpty(documentItem.GetMetadata("Link"));
}
private IDictionary<string, MSB.Evaluation.ProjectItem> _documents;
protected bool IsDocumentGenerated(MSB.Framework.ITaskItem documentItem)
{
if (_documents == null)
{
_documents = new Dictionary<string, MSB.Evaluation.ProjectItem>();
foreach (var item in _loadedProject.GetItems("compile"))
{
_documents[GetAbsolutePath(item.EvaluatedInclude)] = item;
}
}
return !_documents.ContainsKey(GetAbsolutePath(documentItem.ItemSpec));
}
protected static string GetDocumentLogicalPath(MSB.Framework.ITaskItem documentItem, string projectDirectory)
{
var link = documentItem.GetMetadata("Link");
if (!string.IsNullOrEmpty(link))
{
// if a specific link is specified in the project file then use it to form the logical path.
return link;
}
else
{
var result = documentItem.ItemSpec;
if (Path.IsPathRooted(result))
{
// If we have an absolute path, there are two possibilities:
result = Path.GetFullPath(result);
// If the document is within the current project directory (or subdirectory), then the logical path is the relative path
// from the project's directory.
if (result.StartsWith(projectDirectory, StringComparison.OrdinalIgnoreCase))
{
result = result.Substring(projectDirectory.Length);
}
else
{
// if the document lies outside the project's directory (or subdirectory) then place it logically at the root of the project.
// if more than one document ends up with the same logical name then so be it (the workspace will survive.)
return Path.GetFileName(result);
}
}
return result;
}
}
protected string GetReferenceFilePath(ProjectItemInstance projectItem)
{
return GetAbsolutePath(projectItem.EvaluatedInclude);
}
public void AddDocument(string filePath, string logicalPath = null)
{
var relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, filePath);
Dictionary<string, string> metadata = null;
if (logicalPath != null && relativePath != logicalPath)
{
metadata = new Dictionary<string, string>();
metadata.Add("link", logicalPath);
relativePath = filePath; // link to full path
}
_loadedProject.AddItem("Compile", relativePath, metadata);
}
public void RemoveDocument(string filePath)
{
var relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, filePath);
var items = _loadedProject.GetItems("Compile");
var item = items.FirstOrDefault(it => PathUtilities.PathsEqual(it.EvaluatedInclude, relativePath)
|| PathUtilities.PathsEqual(it.EvaluatedInclude, filePath));
if (item != null)
{
_loadedProject.RemoveItem(item);
}
}
public void AddMetadataReference(MetadataReference reference, AssemblyIdentity identity)
{
var peRef = reference as PortableExecutableReference;
if (peRef != null && peRef.FilePath != null)
{
var metadata = new Dictionary<string, string>();
if (!peRef.Properties.Aliases.IsEmpty)
{
metadata.Add("Aliases", string.Join(",", peRef.Properties.Aliases));
}
if (IsInGAC(peRef.FilePath) && identity != null)
{
// Since the location of the reference is in GAC, need to use full identity name to find it again.
// This typically happens when you base the reference off of a reflection assembly location.
_loadedProject.AddItem("Reference", identity.GetDisplayName(), metadata);
}
else if (IsFrameworkReferenceAssembly(peRef.FilePath))
{
// just use short name since this will be resolved by msbuild relative to the known framework reference assemblies.
var fileName = identity != null ? identity.Name : Path.GetFileNameWithoutExtension(peRef.FilePath);
_loadedProject.AddItem("Reference", fileName, metadata);
}
else // other location -- need hint to find correct assembly
{
string relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, peRef.FilePath);
var fileName = Path.GetFileNameWithoutExtension(peRef.FilePath);
metadata.Add("HintPath", relativePath);
_loadedProject.AddItem("Reference", fileName, metadata);
}
}
}
private bool IsInGAC(string filePath)
{
return GlobalAssemblyCacheLocation.RootLocations.Any(gloc => PathUtilities.IsChildPath(gloc, filePath));
}
private static string s_frameworkRoot;
private static string FrameworkRoot
{
get
{
if (string.IsNullOrEmpty(s_frameworkRoot))
{
var runtimeDir = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory();
s_frameworkRoot = Path.GetDirectoryName(runtimeDir); // back out one directory level to be root path of all framework versions
}
return s_frameworkRoot;
}
}
private bool IsFrameworkReferenceAssembly(string filePath)
{
return PathUtilities.IsChildPath(FrameworkRoot, filePath);
}
public void RemoveMetadataReference(MetadataReference reference, AssemblyIdentity identity)
{
var peRef = reference as PortableExecutableReference;
if (peRef != null && peRef.FilePath != null)
{
var item = FindReferenceItem(identity, peRef.FilePath);
if (item != null)
{
_loadedProject.RemoveItem(item);
}
}
}
private MSB.Evaluation.ProjectItem FindReferenceItem(AssemblyIdentity identity, string filePath)
{
var references = _loadedProject.GetItems("Reference");
MSB.Evaluation.ProjectItem item = null;
var fileName = Path.GetFileNameWithoutExtension(filePath);
if (identity != null)
{
var shortAssemblyName = identity.Name;
var fullAssemblyName = identity.GetDisplayName();
// check for short name match
item = references.FirstOrDefault(it => string.Compare(it.EvaluatedInclude, shortAssemblyName, StringComparison.OrdinalIgnoreCase) == 0);
// check for full name match
if (item == null)
{
item = references.FirstOrDefault(it => string.Compare(it.EvaluatedInclude, fullAssemblyName, StringComparison.OrdinalIgnoreCase) == 0);
}
}
// check for file path match
if (item == null)
{
string relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, filePath);
item = references.FirstOrDefault(it => PathUtilities.PathsEqual(it.EvaluatedInclude, filePath)
|| PathUtilities.PathsEqual(it.EvaluatedInclude, relativePath)
|| PathUtilities.PathsEqual(GetHintPath(it), filePath)
|| PathUtilities.PathsEqual(GetHintPath(it), relativePath));
}
// check for partial name match
if (item == null && identity != null)
{
var partialName = identity.Name + ",";
var items = references.Where(it => it.EvaluatedInclude.StartsWith(partialName, StringComparison.OrdinalIgnoreCase)).ToList();
if (items.Count == 1)
{
item = items[0];
}
}
return item;
}
private string GetHintPath(MSB.Evaluation.ProjectItem item)
{
return item.Metadata.FirstOrDefault(m => m.Name == "HintPath")?.EvaluatedValue ?? "";
}
public void AddProjectReference(string projectName, IProjectFileReference reference) { AddProjectReference(projectName, reference); }
public void AddProjectReference(string projectName, ProjectFileReference reference)
{
var metadata = new Dictionary<string, string>();
metadata.Add("Name", projectName);
if (!reference.Aliases.IsEmpty)
{
metadata.Add("Aliases", string.Join(",", reference.Aliases));
}
string relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, reference.Path);
_loadedProject.AddItem("ProjectReference", relativePath, metadata);
}
public void RemoveProjectReference(string projectName, string projectFilePath)
{
string relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, projectFilePath);
var item = FindProjectReferenceItem(projectName, projectFilePath);
if (item != null)
{
_loadedProject.RemoveItem(item);
}
}
private MSB.Evaluation.ProjectItem FindProjectReferenceItem(string projectName, string projectFilePath)
{
var references = _loadedProject.GetItems("ProjectReference");
string relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, projectFilePath);
MSB.Evaluation.ProjectItem item = null;
// find by project file path
item = references.First(it => PathUtilities.PathsEqual(it.EvaluatedInclude, relativePath)
|| PathUtilities.PathsEqual(it.EvaluatedInclude, projectFilePath));
// try to find by project name
if (item == null)
{
item = references.First(it => string.Compare(projectName, it.GetMetadataValue("Name"), StringComparison.OrdinalIgnoreCase) == 0);
}
return item;
}
public void AddAnalyzerReference(AnalyzerReference reference)
{
var fileRef = reference as AnalyzerFileReference;
if (fileRef != null)
{
string relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, fileRef.FullPath);
_loadedProject.AddItem("Analyzer", relativePath);
}
}
public void RemoveAnalyzerReference(AnalyzerReference reference)
{
var fileRef = reference as AnalyzerFileReference;
if (fileRef != null)
{
string relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, fileRef.FullPath);
var analyzers = _loadedProject.GetItems("Analyzer");
var item = analyzers.FirstOrDefault(it => PathUtilities.PathsEqual(it.EvaluatedInclude, relativePath)
|| PathUtilities.PathsEqual(it.EvaluatedInclude, fileRef.FullPath));
if (item != null)
{
_loadedProject.RemoveItem(item);
}
}
}
public void Save()
{
_loadedProject.Save();
}
internal static bool TryGetOutputKind(string outputKind, out OutputKind kind)
{
if (string.Equals(outputKind, "Library", StringComparison.OrdinalIgnoreCase))
{
kind = OutputKind.DynamicallyLinkedLibrary;
return true;
}
else if (string.Equals(outputKind, "Exe", StringComparison.OrdinalIgnoreCase))
{
kind = OutputKind.ConsoleApplication;
return true;
}
else if (string.Equals(outputKind, "WinExe", StringComparison.OrdinalIgnoreCase))
{
kind = OutputKind.WindowsApplication;
return true;
}
else if (string.Equals(outputKind, "Module", StringComparison.OrdinalIgnoreCase))
{
kind = OutputKind.NetModule;
return true;
}
else if (string.Equals(outputKind, "WinMDObj", StringComparison.OrdinalIgnoreCase))
{
kind = OutputKind.WindowsRuntimeMetadata;
return true;
}
else
{
kind = OutputKind.DynamicallyLinkedLibrary;
return false;
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
using OpenMetaverse;
namespace OpenSim.Framework
{
public class LandAccessEntry
{
public UUID AgentID;
public int Expires;
public AccessList Flags;
}
/// <summary>
/// Details of a Parcel of land
/// </summary>
public class LandData
{
// use only one serializer to give the runtime a chance to
// optimize it (it won't do that if you use a new instance
// every time)
private static XmlSerializer serializer = new XmlSerializer(typeof(LandData));
private Vector3 _AABBMax = new Vector3();
private Vector3 _AABBMin = new Vector3();
private int _area = 0;
private uint _auctionID = 0; //Unemplemented. If set to 0, not being auctioned
private UUID _authBuyerID = UUID.Zero; //Unemplemented. Authorized Buyer's UUID
private ParcelCategory _category = ParcelCategory.None; //Unemplemented. Parcel's chosen category
private int _claimDate = 0;
private int _claimPrice = 0; //Unemplemented
private UUID _globalID = UUID.Zero;
private UUID _groupID = UUID.Zero;
private bool _isGroupOwned = false;
private byte[] _bitmap = new byte[512];
private string _description = String.Empty;
private uint _flags = (uint)ParcelFlags.AllowFly | (uint)ParcelFlags.AllowLandmark |
(uint)ParcelFlags.AllowAPrimitiveEntry |
(uint)ParcelFlags.AllowDeedToGroup |
(uint)ParcelFlags.CreateObjects | (uint)ParcelFlags.AllowOtherScripts |
(uint)ParcelFlags.AllowVoiceChat;
private byte _landingType = (byte)OpenMetaverse.LandingType.Direct;
private string _name = "Your Parcel";
private ParcelStatus _status = ParcelStatus.Leased;
private int _localID = 0;
private byte _mediaAutoScale = 0;
private UUID _mediaID = UUID.Zero;
private string _mediaURL = String.Empty;
private string _musicURL = String.Empty;
private UUID _ownerID = UUID.Zero;
private List<LandAccessEntry> _parcelAccessList = new List<LandAccessEntry>();
private float _passHours = 0;
private int _passPrice = 0;
private int _salePrice = 0; //Unemeplemented. Parcels price.
private int _simwideArea = 0;
private int _simwidePrims = 0;
private UUID _snapshotID = UUID.Zero;
private Vector3 _userLocation = new Vector3();
private Vector3 _userLookAt = new Vector3();
private int _otherCleanTime = 0;
private string _mediaType = "none/none";
private string _mediaDescription = "";
private int _mediaHeight = 0;
private int _mediaWidth = 0;
private bool _mediaLoop = false;
private bool _obscureMusic = false;
private bool _obscureMedia = false;
private float m_dwell = 0;
public double LastDwellTimeMS;
public bool SeeAVs { get; set; }
public bool AnyAVSounds { get; set; }
public bool GroupAVSounds { get; set; }
/// <summary>
/// Traffic count of parcel
/// </summary>
[XmlIgnore]
public float Dwell
{
get
{
return m_dwell;
}
set
{
m_dwell = value;
LastDwellTimeMS = Util.GetTimeStampMS();
}
}
/// <summary>
/// Whether to obscure parcel media URL
/// </summary>
[XmlIgnore]
public bool ObscureMedia
{
get
{
return _obscureMedia;
}
set
{
_obscureMedia = value;
}
}
/// <summary>
/// Whether to obscure parcel music URL
/// </summary>
[XmlIgnore]
public bool ObscureMusic
{
get
{
return _obscureMusic;
}
set
{
_obscureMusic = value;
}
}
/// <summary>
/// Whether to loop parcel media
/// </summary>
[XmlIgnore]
public bool MediaLoop
{
get
{
return _mediaLoop;
}
set
{
_mediaLoop = value;
}
}
/// <summary>
/// Height of parcel media render
/// </summary>
[XmlIgnore]
public int MediaHeight
{
get
{
return _mediaHeight;
}
set
{
_mediaHeight = value;
}
}
/// <summary>
/// Width of parcel media render
/// </summary>
[XmlIgnore]
public int MediaWidth
{
get
{
return _mediaWidth;
}
set
{
_mediaWidth = value;
}
}
/// <summary>
/// Upper corner of the AABB for the parcel
/// </summary>
[XmlIgnore]
public Vector3 AABBMax
{
get
{
return _AABBMax;
}
set
{
_AABBMax = value;
}
}
/// <summary>
/// Lower corner of the AABB for the parcel
/// </summary>
[XmlIgnore]
public Vector3 AABBMin
{
get
{
return _AABBMin;
}
set
{
_AABBMin = value;
}
}
/// <summary>
/// Area in meters^2 the parcel contains
/// </summary>
public int Area
{
get
{
return _area;
}
set
{
_area = value;
}
}
/// <summary>
/// ID of auction (3rd Party Integration) when parcel is being auctioned
/// </summary>
public uint AuctionID
{
get
{
return _auctionID;
}
set
{
_auctionID = value;
}
}
/// <summary>
/// UUID of authorized buyer of parcel. This is UUID.Zero if anyone can buy it.
/// </summary>
public UUID AuthBuyerID
{
get
{
return _authBuyerID;
}
set
{
_authBuyerID = value;
}
}
/// <summary>
/// Category of parcel. Used for classifying the parcel in classified listings
/// </summary>
public ParcelCategory Category
{
get
{
return _category;
}
set
{
_category = value;
}
}
/// <summary>
/// Date that the current owner purchased or claimed the parcel
/// </summary>
public int ClaimDate
{
get
{
return _claimDate;
}
set
{
_claimDate = value;
}
}
/// <summary>
/// The last price that the parcel was sold at
/// </summary>
public int ClaimPrice
{
get
{
return _claimPrice;
}
set
{
_claimPrice = value;
}
}
/// <summary>
/// Global ID for the parcel. (3rd Party Integration)
/// </summary>
public UUID GlobalID
{
get
{
return _globalID;
}
set
{
_globalID = value;
}
}
/// <summary>
/// Unique ID of the Group that owns
/// </summary>
public UUID GroupID
{
get
{
return _groupID;
}
set
{
_groupID = value;
}
}
/// <summary>
/// Returns true if the Land Parcel is owned by a group
/// </summary>
public bool IsGroupOwned
{
get
{
return _isGroupOwned;
}
set
{
_isGroupOwned = value;
}
}
/// <summary>
/// jp2 data for the image representative of the parcel in the parcel dialog
/// </summary>
public byte[] Bitmap
{
get
{
return _bitmap;
}
set
{
_bitmap = value;
}
}
/// <summary>
/// Parcel Description
/// </summary>
public string Description
{
get
{
return _description;
}
set
{
_description = value;
}
}
/// <summary>
/// Parcel settings. Access flags, Fly, NoPush, Voice, Scripts allowed, etc. ParcelFlags
/// </summary>
public uint Flags
{
get
{
return _flags;
}
set
{
_flags = value;
}
}
/// <summary>
/// Determines if people are able to teleport where they please on the parcel or if they
/// get constrainted to a specific point on teleport within the parcel
/// </summary>
public byte LandingType
{
get
{
return _landingType;
}
set
{
_landingType = value;
}
}
/// <summary>
/// Parcel Name
/// </summary>
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
/// <summary>
/// Status of Parcel, Leased, Abandoned, For Sale
/// </summary>
public ParcelStatus Status
{
get
{
return _status;
}
set
{
_status = value;
}
}
/// <summary>
/// Internal ID of the parcel. Sometimes the client will try to use this value
/// </summary>
public int LocalID
{
get
{
return _localID;
}
set
{
_localID = value;
}
}
/// <summary>
/// Determines if we scale the media based on the surface it's on
/// </summary>
public byte MediaAutoScale
{
get
{
return _mediaAutoScale;
}
set
{
_mediaAutoScale = value;
}
}
/// <summary>
/// Texture Guid to replace with the output of the media stream
/// </summary>
public UUID MediaID
{
get
{
return _mediaID;
}
set
{
_mediaID = value;
}
}
/// <summary>
/// URL to the media file to display
/// </summary>
public string MediaURL
{
get
{
return _mediaURL;
}
set
{
_mediaURL = value;
}
}
public string MediaType
{
get
{
return _mediaType;
}
set
{
_mediaType = value;
}
}
/// <summary>
/// URL to the shoutcast music stream to play on the parcel
/// </summary>
public string MusicURL
{
get
{
return _musicURL;
}
set
{
_musicURL = value;
}
}
/// <summary>
/// Owner Avatar or Group of the parcel. Naturally, all land masses must be
/// owned by someone
/// </summary>
public UUID OwnerID
{
get
{
return _ownerID;
}
set
{
_ownerID = value;
}
}
/// <summary>
/// List of access data for the parcel. User data, some bitflags, and a time
/// </summary>
public List<LandAccessEntry> ParcelAccessList
{
get
{
return _parcelAccessList;
}
set
{
_parcelAccessList = value;
}
}
/// <summary>
/// How long in hours a Pass to the parcel is given
/// </summary>
public float PassHours
{
get
{
return _passHours;
}
set
{
_passHours = value;
}
}
/// <summary>
/// Price to purchase a Pass to a restricted parcel
/// </summary>
public int PassPrice
{
get
{
return _passPrice;
}
set
{
_passPrice = value;
}
}
/// <summary>
/// When the parcel is being sold, this is the price to purchase the parcel
/// </summary>
public int SalePrice
{
get
{
return _salePrice;
}
set
{
_salePrice = value;
}
}
/// <summary>
/// Number of meters^2 that the land owner has in the Simulator
/// </summary>
[XmlIgnore]
public int SimwideArea
{
get
{
return _simwideArea;
}
set
{
_simwideArea = value;
}
}
/// <summary>
/// Number of SceneObjectPart in the Simulator
/// </summary>
[XmlIgnore]
public int SimwidePrims
{
get
{
return _simwidePrims;
}
set
{
_simwidePrims = value;
}
}
/// <summary>
/// ID of the snapshot used in the client parcel dialog of the parcel
/// </summary>
public UUID SnapshotID
{
get
{
return _snapshotID;
}
set
{
_snapshotID = value;
}
}
/// <summary>
/// When teleporting is restricted to a certain point, this is the location
/// that the user will be redirected to
/// </summary>
public Vector3 UserLocation
{
get
{
return _userLocation;
}
set
{
_userLocation = value;
}
}
/// <summary>
/// When teleporting is restricted to a certain point, this is the rotation
/// that the user will be positioned
/// </summary>
public Vector3 UserLookAt
{
get
{
return _userLookAt;
}
set
{
_userLookAt = value;
}
}
/// <summary>
/// Autoreturn number of minutes to return SceneObjectGroup that are owned by someone who doesn't own
/// the parcel and isn't set to the same 'group' as the parcel.
/// </summary>
public int OtherCleanTime
{
get
{
return _otherCleanTime;
}
set
{
_otherCleanTime = value;
}
}
/// <summary>
/// parcel media description
/// </summary>
public string MediaDescription
{
get
{
return _mediaDescription;
}
set
{
_mediaDescription = value;
}
}
public LandData()
{
_globalID = UUID.Random();
SeeAVs = true;
AnyAVSounds = true;
GroupAVSounds = true;
LastDwellTimeMS = Util.GetTimeStampMS();
}
/// <summary>
/// Make a new copy of the land data
/// </summary>
/// <returns></returns>
public LandData Copy()
{
LandData landData = new LandData();
landData._AABBMax = _AABBMax;
landData._AABBMin = _AABBMin;
landData._area = _area;
landData._auctionID = _auctionID;
landData._authBuyerID = _authBuyerID;
landData._category = _category;
landData._claimDate = _claimDate;
landData._claimPrice = _claimPrice;
landData._globalID = _globalID;
landData._groupID = _groupID;
landData._isGroupOwned = _isGroupOwned;
landData._localID = _localID;
landData._landingType = _landingType;
landData._mediaAutoScale = _mediaAutoScale;
landData._mediaID = _mediaID;
landData._mediaURL = _mediaURL;
landData._musicURL = _musicURL;
landData._ownerID = _ownerID;
landData._bitmap = (byte[])_bitmap.Clone();
landData._description = _description;
landData._flags = _flags;
landData._name = _name;
landData._status = _status;
landData._passHours = _passHours;
landData._passPrice = _passPrice;
landData._salePrice = _salePrice;
landData._snapshotID = _snapshotID;
landData._userLocation = _userLocation;
landData._userLookAt = _userLookAt;
landData._otherCleanTime = _otherCleanTime;
landData._mediaType = _mediaType;
landData._mediaDescription = _mediaDescription;
landData._mediaWidth = _mediaWidth;
landData._mediaHeight = _mediaHeight;
landData._mediaLoop = _mediaLoop;
landData._obscureMusic = _obscureMusic;
landData._obscureMedia = _obscureMedia;
landData._simwideArea = _simwideArea;
landData._simwidePrims = _simwidePrims;
landData.m_dwell = m_dwell;
landData.SeeAVs = SeeAVs;
landData.AnyAVSounds = AnyAVSounds;
landData.GroupAVSounds = GroupAVSounds;
landData._parcelAccessList.Clear();
foreach (LandAccessEntry entry in _parcelAccessList)
{
LandAccessEntry newEntry = new LandAccessEntry();
newEntry.AgentID = entry.AgentID;
newEntry.Flags = entry.Flags;
newEntry.Expires = entry.Expires;
landData._parcelAccessList.Add(newEntry);
}
return landData;
}
// public void ToXml(XmlWriter xmlWriter)
// {
// serializer.Serialize(xmlWriter, this);
// }
/// <summary>
/// Restore a LandData object from the serialized xml representation.
/// </summary>
/// <param name="xmlReader"></param>
/// <returns></returns>
// public static LandData FromXml(XmlReader xmlReader)
// {
// LandData land = (LandData)serializer.Deserialize(xmlReader);
//
// return land;
// }
}
}
| |
//
// IGraphService.cs
//
// Author:
// Henning Rauch <Henning@RauchEntwicklung.biz>
//
// Copyright (c) 2012-2015 Henning Rauch
//
// 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.
#region Usings
using NoSQL.GraphDB.Service.REST.Result;
using NoSQL.GraphDB.Service.REST.Specification;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ServiceModel;
using System.ServiceModel.Web;
#endregion
namespace NoSQL.GraphDB.Service.REST
{
/// <summary>
/// The Fallen-8 graph service.
/// </summary>
[ServiceContract(Namespace = "Fallen-8", Name = "Fallen-8 graph service")]
public interface IGraphService : IRESTService
{
#region Create/Add/Delete GRAPHELEMENT
/// <summary>
/// Adds a vertex to the Fallen-8
/// </summary>
/// <param name="definition"> The vertex specification </param>
/// <returns> The new vertex id </returns>
[OperationContract(Name = "CreateVertex")]
[Description("[F8Graph] F8Graph.CreateVertex: Adds a vertex to the Fallen-8.")]
[WebInvoke(UriTemplate = "/Vertex/Create", Method = "POST", RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
Int32 AddVertex(VertexSpecification definition);
/// <summary>
/// Adds an edge to the Fallen-8
/// </summary>
/// <param name="definition"> The edge specification </param>
/// <returns> The new edge id </returns>
[OperationContract(Name = "CreateEdge")]
[Description("[F8Graph] F8Graph.CreateEdge: Adds an edge to the Fallen-8.")]
[WebInvoke(UriTemplate = "/Edge/Create", Method = "POST", RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
Int32 AddEdge(EdgeSpecification definition);
/// <summary>
/// Returns all graph element properties
/// </summary>
/// <param name="graphElementIdentifier"> The graph element identifier </param>
/// <returns> PropertyName -> PropertyValue </returns>
[OperationContract(Name = "GraphElementProperties")]
[Description("[F8Graph] F8Graph.GraphElementProperties: Returns all graph element properties.")]
[WebGet(UriTemplate = "/GraphElements/{graphElementIdentifier}/Properties", ResponseFormat = WebMessageFormat.Json)]
PropertiesREST GetAllGraphelementProperties(String graphElementIdentifier);
/// <summary>
/// Tries to add a property to a graph element
/// </summary>
/// <param name="graphElementIdentifier"> The graph element identifier </param>
/// <param name="propertyId"> The property identifier </param>
/// <param name="definition"> The property specification </param>
/// <returns> True for success, otherwise false </returns>
[OperationContract(Name = "TryAddProperty")]
[Description("[F8Graph] F8Graph.TryAddProperty: Tries to add a property to a graph element.")]
[WebInvoke(UriTemplate = "/GraphElements/{graphElementIdentifier}/TryAddProperty?propertyId={propertyId}", Method = "POST",
RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
Boolean TryAddProperty(string graphElementIdentifier, string propertyId, PropertySpecification definition);
/// <summary>
/// Tries to delete a property from a graph element
/// </summary>
/// <param name="graphElementIdentifier"> The graph element identifier </param>
/// <param name="propertyId"> The property identifier </param>
/// <returns> True for success, otherwise false </returns>
[OperationContract(Name = "TryDeleteProperty")]
[Description("[F8Graph] F8Graph.TryDeleteProperty: Tries to delete a property from a graph element.")]
[WebGet(UriTemplate = "/GraphElements/{graphElementIdentifier}/TryDeleteProperty?propertyId={propertyId}",
ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
Boolean TryRemoveProperty(string graphElementIdentifier, string propertyId);
/// <summary>
/// Tries to delete a graph element
/// </summary>
/// <param name="graphElementIdentifier"> The graph element identifier </param>
/// <returns> True for success, otherwise false </returns>
[OperationContract(Name = "TryDeleteGraphElement")]
[Description("[F8Graph] F8Graph.TryDeleteGraphElement: Tries to delete a graph element.")]
[WebGet(UriTemplate = "/GraphElements/{graphElementIdentifier}/TryDelete",
ResponseFormat = WebMessageFormat.Json)]
Boolean TryRemoveGraphElement(string graphElementIdentifier);
#endregion
#region Create/Add/Delete INDEX
/// <summary>
/// Creates an index
/// </summary>
/// <param name="definition"> The index specification </param>
/// <returns> True for success otherwise false </returns>
[OperationContract(Name = "CreateIndex")]
[Description("[F8Graph] F8Graph.CreateIndex: Creates an index.")]
[WebInvoke(
UriTemplate = "/Index/Create",
Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
bool CreateIndex(PluginSpecification definition);
/// <summary>
/// Updates an index
/// </summary>
/// <param name="definition"> The update specification </param>
/// <returns> True for success otherwise false </returns>
[OperationContract(Name = "AddToIndex")]
[Description("[F8Graph] F8Graph.AddToIndex: Updates an index.")]
[WebInvoke(
UriTemplate = "/Index/AddTo",
Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
bool AddToIndex(IndexAddToSpecification definition);
/// <summary>
/// Deletes an index
/// </summary>
/// <param name="definition"> The index delete specification </param>
/// <returns> True for success otherwise false </returns>
[OperationContract(Name = "DeleteIndex")]
[Description("[F8Graph] F8Graph.DeleteIndex: Deletes an index.")]
[WebInvoke(UriTemplate = "/Index/Delete", ResponseFormat = WebMessageFormat.Json,
Method = "POST",
RequestFormat = WebMessageFormat.Json)]
bool DeleteIndex(IndexDeleteSpecificaton definition);
/// <summary>
/// Deletes a key from an index
/// </summary>
/// <param name="definition"> The index delete specification </param>
/// <returns> True for success otherwise false </returns>
[OperationContract(Name = "DeleteKeyFromIndex")]
[Description("[F8Graph] F8Graph.DeleteKeyFromIndex: Deletes a key from an index.")]
[WebInvoke(UriTemplate = "/Index/DeleteKey", ResponseFormat = WebMessageFormat.Json,
Method = "POST",
RequestFormat = WebMessageFormat.Json)]
bool RemoveKeyFromIndex(IndexRemoveKeyFromIndexSpecification definition);
/// <summary>
/// Deletes a graph element from an index
/// </summary>
/// <param name="definition"> The index delete specification </param>
/// <returns> True for success otherwise false </returns>
[OperationContract(Name = "RemoveGraphElementFromIndex")]
[Description("[F8Graph] F8Graph.RemoveGraphElementFromIndex: Deletes a graph element from an index.")]
[WebInvoke(UriTemplate = "/Index/DeleteGraphElement",
Method = "POST",
ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
bool RemoveGraphElementFromIndex(IndexRemoveGraphelementFromIndexSpecification definition);
#endregion
#region Read
/// <summary>
/// Returns the source vertex of the edge
/// </summary>
/// <param name="edgeIdentifier"> The edge identifier </param>
/// <returns> source vertex id </returns>
[OperationContract(Name = "EdgeSourceVertex")]
[Description("[F8Graph] F8Graph.EdgeSourceVertex: Returns the source vertex of the edge.")]
[WebGet(UriTemplate = "/Edges/{edgeIdentifier}/Source", ResponseFormat = WebMessageFormat.Json)]
Int32 GetSourceVertexForEdge(String edgeIdentifier);
/// <summary>
/// Returns the target vertex of the edge
/// </summary>
/// <param name="edgeIdentifier"> The edge identifier </param>
/// <returns> target vertex id </returns>
[OperationContract(Name = "EdgeTargetVertex")]
[Description("[F8Graph] F8Graph.EdgeTargetVertex: Returns the target vertex of the edge.")]
[WebGet(UriTemplate = "/Edges/{edgeIdentifier}/Target", ResponseFormat = WebMessageFormat.Json)]
Int32 GetTargetVertexForEdge(String edgeIdentifier);
/// <summary>
/// Returns all available outgoing edges for a given vertex
/// </summary>
/// <param name="vertexIdentifier"> The vertex identifier </param>
/// <returns> List of available incoming edge property ids </returns>
[OperationContract(Name = "AvailableOutEdges")]
[Description("[F8Graph] F8Graph.AvailableOutEdges: Returns all available outgoing edges for a given vertex.")]
[WebGet(UriTemplate = "/Vertices/{vertexIdentifier}/AvailableOutEdges", ResponseFormat = WebMessageFormat.Json)]
List<UInt16> GetAllAvailableOutEdgesOnVertex(String vertexIdentifier);
/// <summary>
/// Returns all available incoming edges for a given vertex
/// </summary>
/// <param name="vertexIdentifier"> The vertex identifier </param>
/// <returns> List of available incoming edge property ids </returns>
[OperationContract(Name = "AvailableInEdges")]
[Description("[F8Graph] F8Graph.AvailableInEdges: Returns all available incoming edges for a given vertex.")]
[WebGet(UriTemplate = "/Vertices/{vertexIdentifier}/AvailableInEdges", ResponseFormat = WebMessageFormat.Json)]
List<UInt16> GetAllAvailableIncEdgesOnVertex(String vertexIdentifier);
/// <summary>
/// Returns all outgoing edges for a given edge property
/// </summary>
/// <param name="vertexIdentifier"> The vertex identifier </param>
/// <param name="edgePropertyIdentifier"> The edge property identifier </param>
/// <returns> List of edge ids </returns>
[OperationContract(Name = "OutEdges")]
[Description("[F8Graph] F8Graph.OutEdges: Returns all outgoing edges for a given edge property.")]
[WebGet(UriTemplate = "/Vertices/{vertexIdentifier}/OutEdges/{edgePropertyIdentifier}",
ResponseFormat = WebMessageFormat.Json)]
List<Int32> GetOutgoingEdges(String vertexIdentifier, String edgePropertyIdentifier);
/// <summary>
/// Returns all incoming edges for a given edge property
/// </summary>
/// <param name="vertexIdentifier"> The vertex identifier </param>
/// <param name="edgePropertyIdentifier"> The edge property identifier </param>
/// <returns> List of edge ids </returns>
[OperationContract(Name = "IncEdges")]
[Description("[F8Graph] F8Graph.IncEdges: Returns all incoming edges for a given edge property.")]
[WebGet(UriTemplate = "/Vertices/{vertexIdentifier}/IncEdges/{edgePropertyIdentifier}",
ResponseFormat = WebMessageFormat.Json)]
List<Int32> GetIncomingEdges(String vertexIdentifier, String edgePropertyIdentifier);
/// <summary>
/// Returns the in-degree of the vertex
/// </summary>
/// <param name="vertexIdentifier"> The vertex identifier </param>
/// <returns> In-degree </returns>
[OperationContract(Name = "InDegree")]
[Description("[F8Graph] F8Graph.InDegree: Returns the in-degree of the vertex.")]
[WebGet(UriTemplate = "/Vertices/{vertexIdentifier}/InDegree",
ResponseFormat = WebMessageFormat.Json)]
UInt32 GetInDegree(String vertexIdentifier);
/// <summary>
/// Returns the out-degree of the vertex
/// </summary>
/// <param name="vertexIdentifier"> The vertex identifier </param>
/// <returns> In-degree </returns>
[OperationContract(Name = "OutDegree")]
[Description("[F8Graph] F8Graph.OutDegree: Returns the out-degree of the vertex.")]
[WebGet(UriTemplate = "/Vertices/{vertexIdentifier}/OutDegree",
ResponseFormat = WebMessageFormat.Json)]
UInt32 GetOutDegree(String vertexIdentifier);
/// <summary>
/// Returns the degree of an incoming edge
/// </summary>
/// <param name="vertexIdentifier"> The vertex identifier </param>
/// <param name="edgePropertyIdentifier"> The edge property identifier </param>
/// <returns> Degree of an incoming edge </returns>
[OperationContract(Name = "IncEdgesDegree")]
[Description("[F8Graph] F8Graph.IncEdgesDegree: Returns the degree of an incoming edge.")]
[WebGet(UriTemplate = "/Vertices/{vertexIdentifier}/IncEdges/{edgePropertyIdentifier}/Degree",
ResponseFormat = WebMessageFormat.Json)]
UInt32 GetInEdgeDegree(String vertexIdentifier, String edgePropertyIdentifier);
/// <summary>
/// Returns the degree of an outgoing edge
/// </summary>
/// <param name="vertexIdentifier"> The vertex identifier </param>
/// <param name="edgePropertyIdentifier"> The edge property identifier </param>
/// <returns> Degree of an incoming edge </returns>
[OperationContract(Name = "OutEdgesDegree")]
[Description("[F8Graph] F8Graph.OutEdgesDegree: Returns the degree of an outgoing edge.")]
[WebGet(UriTemplate = "/Vertices/{vertexIdentifier}/OutEdges/{edgePropertyIdentifier}/Degree",
ResponseFormat = WebMessageFormat.Json)]
UInt32 GetOutEdgeDegree(String vertexIdentifier, String edgePropertyIdentifier);
#endregion
#region scan
/// <summary>
/// Full graph scan for graph elements
/// </summary>
/// <param name="propertyId"> The property identifier </param>
/// <param name="definition"> The scan specification </param>
/// <returns> The matching identifier </returns>
[OperationContract(Name = "GraphScan")]
[Description("[F8Graph] F8Graph.GraphScan: Full graph scan for graph elements.")]
[WebInvoke(UriTemplate = "/Scan/Graph?propertyId={propertyId}", Method = "POST",
RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
IEnumerable<Int32> GraphScan(String propertyId, ScanSpecification definition);
/// <summary>
/// Index scan for graph elements
/// </summary>
/// <param name="definition"> The scan specification </param>
/// <returns> The matching identifier </returns>
[OperationContract(Name = "IndexScan")]
[Description("[F8Graph] F8Graph.IndexScan: Index scan for graph elements.")]
[WebInvoke(UriTemplate = "/Scan/Index", Method = "POST",
RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
IEnumerable<Int32> IndexScan(IndexScanSpecification definition);
/// <summary>
/// Scan for graph elements by a specified property range.
/// </summary>
/// <param name="definition"> The scan specification </param>
/// <returns> The matching identifier </returns>
[OperationContract(Name = "RangeIndexScan")]
[Description("[F8Graph] F8Graph.RangeIndexScan: Scan for graph elements by a specified property range.")]
[WebInvoke(UriTemplate = "/Scan/Index/Range", Method = "POST",
RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
IEnumerable<Int32> RangeIndexScan(RangeIndexScanSpecification definition);
/// <summary>
/// Fulltext scan for graph elements.
/// </summary>
/// <param name="definition"> The scan specification </param>
/// <returns> The matching identifier </returns>
[OperationContract(Name = "FulltextIndexScan")]
[Description("[F8Graph] F8Graph.FulltextIndexScan: Fulltext scan for graph elements.")]
[WebInvoke(UriTemplate = "/Scan/Index/Fulltext", Method = "POST",
RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
FulltextSearchResultREST FulltextIndexScan(FulltextIndexScanSpecification definition);
/// <summary>
/// Spatial index scan for graph elements. Finds all objects in a certain distance to a given graph element
/// </summary>
/// <param name="definition"> The search distance specification </param>
/// <returns> The matching identifier </returns>
[OperationContract(Name = "SpatialIndexScan")]
[Description("[F8Graph] F8Graph.SpatialIndexScan: Spatial index scan for graph elements. Finds all objects in a certain distance to a given graph element.")]
[WebInvoke(UriTemplate = "/Scan/Index/Spatial/SearchDistance", Method = "POST",
RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
IEnumerable<Int32> SpatialIndexScanSearchDistance(SearchDistanceSpecification definition);
#endregion
#region path
/// <summary>
/// Path traverser
/// </summary>
[OperationContract(Name = "Paths")]
[Description("[F8Graph] F8Graph.Paths: Path traverser.")]
[WebInvoke(
UriTemplate = "/Scan/Paths?from={from}&to={to}",
Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
List<PathREST> GetPaths(String from, String to, PathSpecification definition);
/// <summary>
/// Path traverser starting at a given vertex.
/// </summary>
/// <param name="vertexIdentifier"> The vertex identifier </param>
/// <param name="to">The destination</param>
/// <param name="definition">The definition of the path traversal</param>
/// <returns> PropertyName -> PropertyValue </returns>
[OperationContract(Name = "PathFromVertex")]
[Description("[F8Graph] F8Graph.PathFromVertex: Path traverser starting at a given vertex.")]
[WebInvoke(
UriTemplate = "/Vertices/{vertexIdentifier}/Paths?to={to}",
Method = "POST", RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
List<PathREST> GetPathsByVertex(String vertexIdentifier, String to, PathSpecification definition);
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Orleans.GrainDirectory;
using Orleans.Runtime.Scheduler;
using Orleans.Runtime.Configuration;
using Orleans.Runtime.MultiClusterNetwork;
namespace Orleans.Runtime.GrainDirectory
{
internal class LocalGrainDirectory :
#if !NETSTANDARD
MarshalByRefObject,
#endif
ILocalGrainDirectory, ISiloStatusListener
{
/// <summary>
/// list of silo members sorted by the hash value of their address
/// </summary>
private readonly List<SiloAddress> membershipRingList;
private readonly HashSet<SiloAddress> membershipCache;
private readonly AsynchAgent maintainer;
private readonly Logger log;
private readonly SiloAddress seed;
private readonly RegistrarManager registrarManager;
private readonly ISiloStatusOracle siloStatusOracle;
private readonly IMultiClusterOracle multiClusterOracle;
private readonly IInternalGrainFactory grainFactory;
private Action<SiloAddress, SiloStatus> catalogOnSiloRemoved;
// Consider: move these constants into an apropriate place
internal const int HOP_LIMIT = 3; // forward a remote request no more than two times
public static readonly TimeSpan RETRY_DELAY = TimeSpan.FromSeconds(5); // Pause 5 seconds between forwards to let the membership directory settle down
protected SiloAddress Seed { get { return seed; } }
internal Logger Logger { get { return log; } } // logger is shared with classes that manage grain directory
internal bool Running;
internal SiloAddress MyAddress { get; private set; }
internal IGrainDirectoryCache<IReadOnlyList<Tuple<SiloAddress, ActivationId>>> DirectoryCache { get; private set; }
internal GrainDirectoryPartition DirectoryPartition { get; private set; }
public RemoteGrainDirectory RemoteGrainDirectory { get; private set; }
public RemoteGrainDirectory CacheValidator { get; private set; }
public ClusterGrainDirectory RemoteClusterGrainDirectory { get; private set; }
private readonly TaskCompletionSource<bool> stopPreparationResolver;
public Task StopPreparationCompletion { get { return stopPreparationResolver.Task; } }
internal OrleansTaskScheduler Scheduler { get; private set; }
internal GrainDirectoryHandoffManager HandoffManager { get; private set; }
public string ClusterId { get; }
internal GlobalSingleInstanceActivationMaintainer GsiActivationMaintainer { get; private set; }
private readonly CounterStatistic localLookups;
private readonly CounterStatistic localSuccesses;
private readonly CounterStatistic fullLookups;
private readonly CounterStatistic cacheLookups;
private readonly CounterStatistic cacheSuccesses;
private readonly CounterStatistic registrationsIssued;
private readonly CounterStatistic registrationsSingleActIssued;
private readonly CounterStatistic unregistrationsIssued;
private readonly CounterStatistic unregistrationsManyIssued;
private readonly IntValueStatistic directoryPartitionCount;
internal readonly CounterStatistic RemoteLookupsSent;
internal readonly CounterStatistic RemoteLookupsReceived;
internal readonly CounterStatistic LocalDirectoryLookups;
internal readonly CounterStatistic LocalDirectorySuccesses;
internal readonly CounterStatistic CacheValidationsSent;
internal readonly CounterStatistic CacheValidationsReceived;
internal readonly CounterStatistic RegistrationsLocal;
internal readonly CounterStatistic RegistrationsRemoteSent;
internal readonly CounterStatistic RegistrationsRemoteReceived;
internal readonly CounterStatistic RegistrationsSingleActLocal;
internal readonly CounterStatistic RegistrationsSingleActRemoteSent;
internal readonly CounterStatistic RegistrationsSingleActRemoteReceived;
internal readonly CounterStatistic UnregistrationsLocal;
internal readonly CounterStatistic UnregistrationsRemoteSent;
internal readonly CounterStatistic UnregistrationsRemoteReceived;
internal readonly CounterStatistic UnregistrationsManyRemoteSent;
internal readonly CounterStatistic UnregistrationsManyRemoteReceived;
public LocalGrainDirectory(
ClusterConfiguration clusterConfig,
ILocalSiloDetails siloDetails,
OrleansTaskScheduler scheduler,
ISiloStatusOracle siloStatusOracle,
IMultiClusterOracle multiClusterOracle,
IInternalGrainFactory grainFactory,
Factory<GrainDirectoryPartition> grainDirectoryPartitionFactory,
RegistrarManager registrarManager)
{
this.log = LogManager.GetLogger("Orleans.GrainDirectory.LocalGrainDirectory");
var globalConfig = clusterConfig.Globals;
var clusterId = globalConfig.HasMultiClusterNetwork ? globalConfig.ClusterId : null;
MyAddress = siloDetails.SiloAddress;
Scheduler = scheduler;
this.siloStatusOracle = siloStatusOracle;
this.multiClusterOracle = multiClusterOracle;
this.grainFactory = grainFactory;
membershipRingList = new List<SiloAddress>();
membershipCache = new HashSet<SiloAddress>();
ClusterId = clusterId;
clusterConfig.OnConfigChange("Globals/Caching", () =>
{
lock (membershipCache)
{
DirectoryCache = GrainDirectoryCacheFactory<IReadOnlyList<Tuple<SiloAddress, ActivationId>>>.CreateGrainDirectoryCache(globalConfig);
}
});
maintainer =
GrainDirectoryCacheFactory<IReadOnlyList<Tuple<SiloAddress, ActivationId>>>.CreateGrainDirectoryCacheMaintainer(
this,
this.DirectoryCache,
activations => activations.Select(a => Tuple.Create(a.Silo, a.Activation)).ToList().AsReadOnly(),
grainFactory);
GsiActivationMaintainer = new GlobalSingleInstanceActivationMaintainer(this, this.Logger, globalConfig, grainFactory, multiClusterOracle);
if (globalConfig.SeedNodes.Count > 0)
{
seed = globalConfig.SeedNodes.Contains(MyAddress.Endpoint) ? MyAddress : SiloAddress.New(globalConfig.SeedNodes[0], 0);
}
stopPreparationResolver = new TaskCompletionSource<bool>();
DirectoryPartition = grainDirectoryPartitionFactory();
HandoffManager = new GrainDirectoryHandoffManager(this, siloStatusOracle, grainFactory, grainDirectoryPartitionFactory);
RemoteGrainDirectory = new RemoteGrainDirectory(this, Constants.DirectoryServiceId);
CacheValidator = new RemoteGrainDirectory(this, Constants.DirectoryCacheValidatorId);
RemoteClusterGrainDirectory = new ClusterGrainDirectory(this, Constants.ClusterDirectoryServiceId, clusterId, grainFactory, multiClusterOracle);
// add myself to the list of members
AddServer(MyAddress);
Func<SiloAddress, string> siloAddressPrint = (SiloAddress addr) =>
String.Format("{0}/{1:X}", addr.ToLongString(), addr.GetConsistentHashCode());
localLookups = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_LOCAL_ISSUED);
localSuccesses = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_LOCAL_SUCCESSES);
fullLookups = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_FULL_ISSUED);
RemoteLookupsSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_REMOTE_SENT);
RemoteLookupsReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_REMOTE_RECEIVED);
LocalDirectoryLookups = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_LOCALDIRECTORY_ISSUED);
LocalDirectorySuccesses = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_LOCALDIRECTORY_SUCCESSES);
cacheLookups = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_CACHE_ISSUED);
cacheSuccesses = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_CACHE_SUCCESSES);
StringValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_CACHE_HITRATIO, () =>
{
long delta1, delta2;
long curr1 = cacheSuccesses.GetCurrentValueAndDelta(out delta1);
long curr2 = cacheLookups.GetCurrentValueAndDelta(out delta2);
return String.Format("{0}, Delta={1}",
(curr2 != 0 ? (float)curr1 / (float)curr2 : 0)
,(delta2 !=0 ? (float)delta1 / (float)delta2 : 0));
});
CacheValidationsSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_VALIDATIONS_CACHE_SENT);
CacheValidationsReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_VALIDATIONS_CACHE_RECEIVED);
registrationsIssued = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_ISSUED);
RegistrationsLocal = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_LOCAL);
RegistrationsRemoteSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_REMOTE_SENT);
RegistrationsRemoteReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_REMOTE_RECEIVED);
registrationsSingleActIssued = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_SINGLE_ACT_ISSUED);
RegistrationsSingleActLocal = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_SINGLE_ACT_LOCAL);
RegistrationsSingleActRemoteSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_SINGLE_ACT_REMOTE_SENT);
RegistrationsSingleActRemoteReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_SINGLE_ACT_REMOTE_RECEIVED);
unregistrationsIssued = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_ISSUED);
UnregistrationsLocal = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_LOCAL);
UnregistrationsRemoteSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_REMOTE_SENT);
UnregistrationsRemoteReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_REMOTE_RECEIVED);
unregistrationsManyIssued = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_MANY_ISSUED);
UnregistrationsManyRemoteSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_MANY_REMOTE_SENT);
UnregistrationsManyRemoteReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_MANY_REMOTE_RECEIVED);
directoryPartitionCount = IntValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_PARTITION_SIZE, () => DirectoryPartition.Count);
IntValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_MYPORTION_RINGDISTANCE, () => RingDistanceToSuccessor());
FloatValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_MYPORTION_RINGPERCENTAGE, () => (((float)this.RingDistanceToSuccessor()) / ((float)(int.MaxValue * 2L))) * 100);
FloatValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_MYPORTION_AVERAGERINGPERCENTAGE, () => this.membershipRingList.Count == 0 ? 0 : ((float)100 / (float)this.membershipRingList.Count));
IntValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_RINGSIZE, () => this.membershipRingList.Count);
StringValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING, () =>
{
lock (this.membershipCache)
{
return Utils.EnumerableToString(this.membershipRingList, siloAddressPrint);
}
});
StringValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_PREDECESSORS, () => Utils.EnumerableToString(this.FindPredecessors(this.MyAddress, 1), siloAddressPrint));
StringValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_SUCCESSORS, () => Utils.EnumerableToString(this.FindSuccessors(this.MyAddress, 1), siloAddressPrint));
this.registrarManager = registrarManager;
}
public void Start()
{
log.Info("Start (SeverityLevel={0})", log.SeverityLevel);
Running = true;
if (maintainer != null)
{
maintainer.Start();
}
if (GsiActivationMaintainer != null)
{
GsiActivationMaintainer.Start();
}
}
// Note that this implementation stops processing directory change requests (Register, Unregister, etc.) when the Stop event is raised.
// This means that there may be a short period during which no silo believes that it is the owner of directory information for a set of
// grains (for update purposes), which could cause application requests that require a new activation to be created to time out.
// The alternative would be to allow the silo to process requests after it has handed off its partition, in which case those changes
// would receive successful responses but would not be reflected in the eventual state of the directory.
// It's easy to change this, if we think the trade-off is better the other way.
public void Stop(bool doOnStopHandoff)
{
// This will cause remote write requests to be forwarded to the silo that will become the new owner.
// Requests might bounce back and forth for a while as membership stabilizes, but they will either be served by the
// new owner of the grain, or will wind up failing. In either case, we avoid requests succeeding at this silo after we've
// begun stopping, which could cause them to not get handed off to the new owner.
Running = false;
if (doOnStopHandoff)
{
HandoffManager.ProcessSiloStoppingEvent();
}
else
{
MarkStopPreparationCompleted();
}
if (maintainer != null)
{
maintainer.Stop();
}
DirectoryCache.Clear();
}
internal void MarkStopPreparationCompleted()
{
stopPreparationResolver.TrySetResult(true);
}
internal void MarkStopPreparationFailed(Exception ex)
{
stopPreparationResolver.TrySetException(ex);
}
/// <inheritdoc />
public void SetSiloRemovedCatalogCallback(Action<SiloAddress, SiloStatus> callback)
{
if (callback == null) throw new ArgumentNullException(nameof(callback));
lock (membershipCache)
{
this.catalogOnSiloRemoved = callback;
}
}
#region Handling membership events
protected void AddServer(SiloAddress silo)
{
lock (membershipCache)
{
if (membershipCache.Contains(silo))
{
// we have already cached this silo
return;
}
membershipCache.Add(silo);
// insert new silo in the sorted order
long hash = silo.GetConsistentHashCode();
// Find the last silo with hash smaller than the new silo, and insert the latter after (this is why we have +1 here) the former.
// Notice that FindLastIndex might return -1 if this should be the first silo in the list, but then
// 'index' will get 0, as needed.
int index = membershipRingList.FindLastIndex(siloAddr => siloAddr.GetConsistentHashCode() < hash) + 1;
membershipRingList.Insert(index, silo);
HandoffManager.ProcessSiloAddEvent(silo);
if (log.IsVerbose) log.Verbose("Silo {0} added silo {1}", MyAddress, silo);
}
}
protected void RemoveServer(SiloAddress silo, SiloStatus status)
{
lock (membershipCache)
{
if (!membershipCache.Contains(silo))
{
// we have already removed this silo
return;
}
if (this.catalogOnSiloRemoved != null)
{
try
{
// Only notify the catalog once. Order is important: call BEFORE updating membershipRingList.
this.catalogOnSiloRemoved(silo, status);
}
catch (Exception exc)
{
log.Error(ErrorCode.Directory_SiloStatusChangeNotification_Exception,
String.Format("CatalogSiloStatusListener.SiloStatusChangeNotification has thrown an exception when notified about removed silo {0}.", silo.ToStringWithHashCode()), exc);
}
}
// the call order is important
HandoffManager.ProcessSiloRemoveEvent(silo);
membershipCache.Remove(silo);
membershipRingList.Remove(silo);
AdjustLocalDirectory(silo);
AdjustLocalCache(silo);
if (log.IsVerbose) log.Verbose("Silo {0} removed silo {1}", MyAddress, silo);
}
}
/// <summary>
/// Adjust local directory following the removal of a silo by droping all activations located on the removed silo
/// </summary>
/// <param name="removedSilo"></param>
protected void AdjustLocalDirectory(SiloAddress removedSilo)
{
var activationsToRemove = (from pair in DirectoryPartition.GetItems()
from pair2 in pair.Value.Instances.Where(pair3 => pair3.Value.SiloAddress.Equals(removedSilo))
select new Tuple<GrainId, ActivationId>(pair.Key, pair2.Key)).ToList();
// drop all records of activations located on the removed silo
foreach (var activation in activationsToRemove)
{
DirectoryPartition.RemoveActivation(activation.Item1, activation.Item2);
}
}
/// Adjust local cache following the removal of a silo by droping:
/// 1) entries that point to activations located on the removed silo
/// 2) entries for grains that are now owned by this silo (me)
/// 3) entries for grains that were owned by this removed silo - we currently do NOT do that.
/// If we did 3, we need to do that BEFORE we change the membershipRingList (based on old Membership).
/// We don't do that since first cache refresh handles that.
/// Second, since Membership events are not guaranteed to be ordered, we may remove a cache entry that does not really point to a failed silo.
/// To do that properly, we need to store for each cache entry who was the directory owner that registered this activation (the original partition owner).
protected void AdjustLocalCache(SiloAddress removedSilo)
{
// remove all records of activations located on the removed silo
foreach (Tuple<GrainId, IReadOnlyList<Tuple<SiloAddress, ActivationId>>, int> tuple in DirectoryCache.KeyValues)
{
// 2) remove entries now owned by me (they should be retrieved from my directory partition)
if (MyAddress.Equals(CalculateTargetSilo(tuple.Item1)))
{
DirectoryCache.Remove(tuple.Item1);
}
// 1) remove entries that point to activations located on the removed silo
RemoveActivations(DirectoryCache, tuple.Item1, tuple.Item2, tuple.Item3, t => t.Item1.Equals(removedSilo));
}
}
internal List<SiloAddress> FindPredecessors(SiloAddress silo, int count)
{
lock (membershipCache)
{
int index = membershipRingList.FindIndex(elem => elem.Equals(silo));
if (index == -1)
{
log.Warn(ErrorCode.Runtime_Error_100201, "Got request to find predecessors of silo " + silo + ", which is not in the list of members");
return null;
}
var result = new List<SiloAddress>();
int numMembers = membershipRingList.Count;
for (int i = index - 1; ((i + numMembers) % numMembers) != index && result.Count < count; i--)
{
result.Add(membershipRingList[(i + numMembers) % numMembers]);
}
return result;
}
}
internal List<SiloAddress> FindSuccessors(SiloAddress silo, int count)
{
lock (membershipCache)
{
int index = membershipRingList.FindIndex(elem => elem.Equals(silo));
if (index == -1)
{
log.Warn(ErrorCode.Runtime_Error_100203, "Got request to find successors of silo " + silo + ", which is not in the list of members");
return null;
}
var result = new List<SiloAddress>();
int numMembers = membershipRingList.Count;
for (int i = index + 1; i % numMembers != index && result.Count < count; i++)
{
result.Add(membershipRingList[i % numMembers]);
}
return result;
}
}
public void SiloStatusChangeNotification(SiloAddress updatedSilo, SiloStatus status)
{
// This silo's status has changed
if (Equals(updatedSilo, MyAddress))
{
if (status == SiloStatus.Stopping || status == SiloStatus.ShuttingDown)
{
// QueueAction up the "Stop" to run on a system turn
Scheduler.QueueAction(() => Stop(true), CacheValidator.SchedulingContext).Ignore();
}
else if (status == SiloStatus.Dead)
{
// QueueAction up the "Stop" to run on a system turn
Scheduler.QueueAction(() => Stop(false), CacheValidator.SchedulingContext).Ignore();
}
}
else // Status change for some other silo
{
if (status.IsTerminating())
{
// QueueAction up the "Remove" to run on a system turn
Scheduler.QueueAction(() => RemoveServer(updatedSilo, status), CacheValidator.SchedulingContext).Ignore();
}
else if (status == SiloStatus.Active) // do not do anything with SiloStatus.Starting -- wait until it actually becomes active
{
// QueueAction up the "Remove" to run on a system turn
Scheduler.QueueAction(() => AddServer(updatedSilo), CacheValidator.SchedulingContext).Ignore();
}
}
}
private bool IsValidSilo(SiloAddress silo)
{
return this.siloStatusOracle.IsFunctionalDirectory(silo);
}
#endregion
/// <summary>
/// Finds the silo that owns the directory information for the given grain ID.
/// This routine will always return a non-null silo address unless the excludeThisSiloIfStopping parameter is true,
/// this is the only silo known, and this silo is stopping.
/// </summary>
/// <param name="grainId"></param>
/// <param name="excludeThisSiloIfStopping"></param>
/// <returns></returns>
public SiloAddress CalculateTargetSilo(GrainId grainId, bool excludeThisSiloIfStopping = true)
{
// give a special treatment for special grains
if (grainId.IsSystemTarget)
{
if (log.IsVerbose2) log.Verbose2("Silo {0} looked for a system target {1}, returned {2}", MyAddress, grainId, MyAddress);
// every silo owns its system targets
return MyAddress;
}
if (Constants.SystemMembershipTableId.Equals(grainId))
{
if (Seed == null)
{
string grainName;
if (!Constants.TryGetSystemGrainName(grainId, out grainName))
grainName = "MembershipTableGrain";
var errorMsg = grainName + " cannot run without Seed node - please check your silo configuration file and make sure it specifies a SeedNode element. " +
" Alternatively, you may want to use AzureTable for LivenessType.";
throw new ArgumentException(errorMsg, "grainId = " + grainId);
}
// Directory info for the membership table grain has to be located on the primary (seed) node, for bootstrapping
if (log.IsVerbose2) log.Verbose2("Silo {0} looked for a special grain {1}, returned {2}", MyAddress, grainId, Seed);
return Seed;
}
SiloAddress siloAddress = null;
int hash = unchecked((int)grainId.GetUniformHashCode());
// excludeMySelf from being a TargetSilo if we're not running and the excludeThisSIloIfStopping flag is true. see the comment in the Stop method.
bool excludeMySelf = !Running && excludeThisSiloIfStopping;
lock (membershipCache)
{
if (membershipRingList.Count == 0)
{
// If the membership ring is empty, then we're the owner by default unless we're stopping.
return excludeThisSiloIfStopping && !Running ? null : MyAddress;
}
// need to implement a binary search, but for now simply traverse the list of silos sorted by their hashes
for (var index = membershipRingList.Count - 1; index >= 0; --index)
{
var item = membershipRingList[index];
if (IsSiloNextInTheRing(item, hash, excludeMySelf))
{
siloAddress = item;
break;
}
}
if (siloAddress == null)
{
// If not found in the traversal, last silo will do (we are on a ring).
// We checked above to make sure that the list isn't empty, so this should always be safe.
siloAddress = membershipRingList[membershipRingList.Count - 1];
// Make sure it's not us...
if (siloAddress.Equals(MyAddress) && excludeMySelf)
{
siloAddress = membershipRingList.Count > 1 ? membershipRingList[membershipRingList.Count - 2] : null;
}
}
}
if (log.IsVerbose2) log.Verbose2("Silo {0} calculated directory partition owner silo {1} for grain {2}: {3} --> {4}", MyAddress, siloAddress, grainId, hash, siloAddress.GetConsistentHashCode());
return siloAddress;
}
#region Implementation of ILocalGrainDirectory
public SiloAddress CheckIfShouldForward(GrainId grainId, int hopCount, string operationDescription)
{
SiloAddress owner = CalculateTargetSilo(grainId);
if (owner == null)
{
// We don't know about any other silos, and we're stopping, so throw
throw new InvalidOperationException("Grain directory is stopping");
}
if (owner.Equals(MyAddress))
{
// if I am the owner, perform the operation locally
return null;
}
if (hopCount >= HOP_LIMIT)
{
// we are not forwarding because there were too many hops already
throw new OrleansException(string.Format("Silo {0} is not owner of {1}, cannot forward {2} to owner {3} because hop limit is reached", MyAddress, grainId, operationDescription, owner));
}
// forward to the silo that we think is the owner
return owner;
}
public async Task<AddressAndTag> RegisterAsync(ActivationAddress address, bool singleActivation, int hopCount)
{
var counterStatistic =
singleActivation
? (hopCount > 0 ? this.RegistrationsSingleActRemoteReceived : this.registrationsSingleActIssued)
: (hopCount > 0 ? this.RegistrationsRemoteReceived : this.registrationsIssued);
counterStatistic.Increment();
// see if the owner is somewhere else (returns null if we are owner)
var forwardAddress = this.CheckIfShouldForward(address.Grain, hopCount, "RegisterAsync");
// on all silos other than first, we insert a retry delay and recheck owner before forwarding
if (hopCount > 0 && forwardAddress != null)
{
await Task.Delay(RETRY_DELAY);
forwardAddress = this.CheckIfShouldForward(address.Grain, hopCount, "RegisterAsync(recheck)");
}
if (forwardAddress == null)
{
(singleActivation ? RegistrationsSingleActLocal : RegistrationsLocal).Increment();
// we are the owner
var registrar = this.registrarManager.GetRegistrarForGrain(address.Grain);
return registrar.IsSynchronous ? registrar.Register(address, singleActivation)
: await registrar.RegisterAsync(address, singleActivation);
}
else
{
(singleActivation ? RegistrationsSingleActRemoteSent : RegistrationsRemoteSent).Increment();
// otherwise, notify the owner
AddressAndTag result = await GetDirectoryReference(forwardAddress).RegisterAsync(address, singleActivation, hopCount + 1);
if (singleActivation)
{
// Caching optimization:
// cache the result of a successfull RegisterSingleActivation call, only if it is not a duplicate activation.
// this way next local lookup will find this ActivationAddress in the cache and we will save a full lookup!
if (result.Address == null) return result;
if (!address.Equals(result.Address) || !IsValidSilo(address.Silo)) return result;
var cached = new List<Tuple<SiloAddress, ActivationId>>(1) { Tuple.Create(address.Silo, address.Activation) };
// update the cache so next local lookup will find this ActivationAddress in the cache and we will save full lookup.
DirectoryCache.AddOrUpdate(address.Grain, cached, result.VersionTag);
}
else
{
if (IsValidSilo(address.Silo))
{
// Caching optimization:
// cache the result of a successfull RegisterActivation call, only if it is not a duplicate activation.
// this way next local lookup will find this ActivationAddress in the cache and we will save a full lookup!
IReadOnlyList<Tuple<SiloAddress, ActivationId>> cached;
if (!DirectoryCache.LookUp(address.Grain, out cached))
{
cached = new List<Tuple<SiloAddress, ActivationId>>(1)
{
Tuple.Create(address.Silo, address.Activation)
};
}
else
{
var newcached = new List<Tuple<SiloAddress, ActivationId>>(cached.Count + 1);
newcached.AddRange(cached);
newcached.Add(Tuple.Create(address.Silo, address.Activation));
cached = newcached;
}
// update the cache so next local lookup will find this ActivationAddress in the cache and we will save full lookup.
DirectoryCache.AddOrUpdate(address.Grain, cached, result.VersionTag);
}
}
return result;
}
}
public Task UnregisterAfterNonexistingActivation(ActivationAddress addr, SiloAddress origin)
{
log.Verbose2("UnregisterAfterNonexistingActivation addr={0} origin={1}", addr, origin);
if (origin == null || membershipCache.Contains(origin))
{
// the request originated in this cluster, call unregister here
return UnregisterAsync(addr, UnregistrationCause.NonexistentActivation, 0);
}
else
{
// the request originated in another cluster, call unregister there
var remoteDirectory = GetDirectoryReference(origin);
return remoteDirectory.UnregisterAsync(addr, UnregistrationCause.NonexistentActivation);
}
}
public async Task UnregisterAsync(ActivationAddress address, UnregistrationCause cause, int hopCount)
{
(hopCount > 0 ? UnregistrationsRemoteReceived : unregistrationsIssued).Increment();
if (hopCount == 0)
InvalidateCacheEntry(address);
// see if the owner is somewhere else (returns null if we are owner)
var forwardaddress = this.CheckIfShouldForward(address.Grain, hopCount, "UnregisterAsync");
// on all silos other than first, we insert a retry delay and recheck owner before forwarding
if (hopCount > 0 && forwardaddress != null)
{
await Task.Delay(RETRY_DELAY);
forwardaddress = this.CheckIfShouldForward(address.Grain, hopCount, "UnregisterAsync(recheck)");
}
if (forwardaddress == null)
{
// we are the owner
UnregistrationsLocal.Increment();
var registrar = this.registrarManager.GetRegistrarForGrain(address.Grain);
if (registrar.IsSynchronous)
registrar.Unregister(address, cause);
else
await registrar.UnregisterAsync(new List<ActivationAddress>() { address }, cause);
}
else
{
UnregistrationsRemoteSent.Increment();
// otherwise, notify the owner
await GetDirectoryReference(forwardaddress).UnregisterAsync(address, cause, hopCount + 1);
}
}
private void AddToDictionary<K,V>(ref Dictionary<K, List<V>> dictionary, K key, V value)
{
if (dictionary == null)
dictionary = new Dictionary<K,List<V>>();
List<V> list;
if (! dictionary.TryGetValue(key, out list))
dictionary[key] = list = new List<V>();
list.Add(value);
}
// helper method to avoid code duplication inside UnregisterManyAsync
private void UnregisterOrPutInForwardList(IEnumerable<ActivationAddress> addresses, UnregistrationCause cause, int hopCount,
ref Dictionary<SiloAddress, List<ActivationAddress>> forward, List<Task> tasks, string context)
{
Dictionary<IGrainRegistrar, List<ActivationAddress>> unregisterBatches = new Dictionary<IGrainRegistrar, List<ActivationAddress>>();
foreach (var address in addresses)
{
// see if the owner is somewhere else (returns null if we are owner)
var forwardAddress = this.CheckIfShouldForward(address.Grain, hopCount, context);
if (forwardAddress != null)
{
AddToDictionary(ref forward, forwardAddress, address);
}
else
{
// we are the owner
UnregistrationsLocal.Increment();
var registrar = this.registrarManager.GetRegistrarForGrain(address.Grain);
if (registrar.IsSynchronous)
{
registrar.Unregister(address, cause);
}
else
{
List<ActivationAddress> list;
if (!unregisterBatches.TryGetValue(registrar, out list))
unregisterBatches.Add(registrar, list = new List<ActivationAddress>());
list.Add(address);
}
}
}
// batch-unregister for each asynchronous registrar
foreach (var kvp in unregisterBatches)
{
tasks.Add(kvp.Key.UnregisterAsync(kvp.Value, cause));
}
}
public async Task UnregisterManyAsync(List<ActivationAddress> addresses, UnregistrationCause cause, int hopCount)
{
(hopCount > 0 ? UnregistrationsManyRemoteReceived : unregistrationsManyIssued).Increment();
Dictionary<SiloAddress, List<ActivationAddress>> forwardlist = null;
var tasks = new List<Task>();
UnregisterOrPutInForwardList(addresses, cause, hopCount, ref forwardlist, tasks, "UnregisterManyAsync");
// before forwarding to other silos, we insert a retry delay and re-check destination
if (hopCount > 0 && forwardlist != null)
{
await Task.Delay(RETRY_DELAY);
Dictionary<SiloAddress, List<ActivationAddress>> forwardlist2 = null;
UnregisterOrPutInForwardList(forwardlist.SelectMany(kvp => kvp.Value), cause, hopCount, ref forwardlist2, tasks, "UnregisterManyAsync(recheck)");
forwardlist = forwardlist2;
}
// forward the requests
if (forwardlist != null)
{
foreach (var kvp in forwardlist)
{
UnregistrationsManyRemoteSent.Increment();
tasks.Add(GetDirectoryReference(kvp.Key).UnregisterManyAsync(kvp.Value, cause, hopCount + 1));
}
}
// wait for all the requests to finish
await Task.WhenAll(tasks);
}
public bool LocalLookup(GrainId grain, out AddressesAndTag result)
{
localLookups.Increment();
SiloAddress silo = CalculateTargetSilo(grain, false);
// No need to check that silo != null since we're passing excludeThisSiloIfStopping = false
if (log.IsVerbose) log.Verbose("Silo {0} tries to lookup for {1}-->{2} ({3}-->{4})", MyAddress, grain, silo, grain.GetUniformHashCode(), silo.GetConsistentHashCode());
// check if we own the grain
if (silo.Equals(MyAddress))
{
LocalDirectoryLookups.Increment();
result = GetLocalDirectoryData(grain);
if (result.Addresses == null)
{
// it can happen that we cannot find the grain in our partition if there were
// some recent changes in the membership
if (log.IsVerbose2) log.Verbose2("LocalLookup mine {0}=null", grain);
return false;
}
if (log.IsVerbose2) log.Verbose2("LocalLookup mine {0}={1}", grain, result.Addresses.ToStrings());
LocalDirectorySuccesses.Increment();
localSuccesses.Increment();
return true;
}
// handle cache
result = new AddressesAndTag();
cacheLookups.Increment();
result.Addresses = GetLocalCacheData(grain);
if (result.Addresses == null)
{
if (log.IsVerbose2) log.Verbose2("TryFullLookup else {0}=null", grain);
return false;
}
if (log.IsVerbose2) log.Verbose2("LocalLookup cache {0}={1}", grain, result.Addresses.ToStrings());
cacheSuccesses.Increment();
localSuccesses.Increment();
return true;
}
public AddressesAndTag GetLocalDirectoryData(GrainId grain)
{
return DirectoryPartition.LookUpActivations(grain);
}
public List<ActivationAddress> GetLocalCacheData(GrainId grain)
{
IReadOnlyList<Tuple<SiloAddress, ActivationId>> cached;
return DirectoryCache.LookUp(grain, out cached) ?
cached.Select(elem => ActivationAddress.GetAddress(elem.Item1, grain, elem.Item2)).Where(addr => IsValidSilo(addr.Silo)).ToList() :
null;
}
public Task<AddressesAndTag> LookupInCluster(GrainId grainId, string clusterId)
{
if (clusterId == null)
throw new ArgumentNullException("clusterId");
if (clusterId == ClusterId)
{
return LookupAsync(grainId);
}
else
{
// find gateway
var gossipOracle = this.multiClusterOracle;
var clusterGatewayAddress = gossipOracle.GetRandomClusterGateway(clusterId);
if (clusterGatewayAddress != null)
{
// call remote grain directory
var remotedirectory = GetDirectoryReference(clusterGatewayAddress);
return remotedirectory.LookupAsync(grainId);
}
else
{
return Task.FromResult(default(AddressesAndTag));
}
}
}
public async Task<AddressesAndTag> LookupAsync(GrainId grainId, int hopCount = 0)
{
(hopCount > 0 ? RemoteLookupsReceived : fullLookups).Increment();
// see if the owner is somewhere else (returns null if we are owner)
var forwardAddress = this.CheckIfShouldForward(grainId, hopCount, "LookUpAsync");
// on all silos other than first, we insert a retry delay and recheck owner before forwarding
if (hopCount > 0 && forwardAddress != null)
{
await Task.Delay(RETRY_DELAY);
forwardAddress = this.CheckIfShouldForward(grainId, hopCount, "LookUpAsync(recheck)");
}
if (forwardAddress == null)
{
// we are the owner
LocalDirectoryLookups.Increment();
var localResult = DirectoryPartition.LookUpActivations(grainId);
if (localResult.Addresses == null)
{
// it can happen that we cannot find the grain in our partition if there were
// some recent changes in the membership
if (log.IsVerbose2) log.Verbose2("FullLookup mine {0}=none", grainId);
localResult.Addresses = new List<ActivationAddress>();
localResult.VersionTag = GrainInfo.NO_ETAG;
return localResult;
}
if (log.IsVerbose2) log.Verbose2("FullLookup mine {0}={1}", grainId, localResult.Addresses.ToStrings());
LocalDirectorySuccesses.Increment();
return localResult;
}
else
{
// Just a optimization. Why sending a message to someone we know is not valid.
if (!IsValidSilo(forwardAddress))
{
throw new OrleansException(String.Format("Current directory at {0} is not stable to perform the lookup for grainId {1} (it maps to {2}, which is not a valid silo). Retry later.", MyAddress, grainId, forwardAddress));
}
RemoteLookupsSent.Increment();
var result = await GetDirectoryReference(forwardAddress).LookupAsync(grainId, hopCount + 1);
// update the cache
result.Addresses = result.Addresses.Where(t => IsValidSilo(t.Silo)).ToList();
if (log.IsVerbose2) log.Verbose2("FullLookup remote {0}={1}", grainId, result.Addresses.ToStrings());
var entries = result.Addresses.Select(t => Tuple.Create(t.Silo, t.Activation)).ToList();
if (entries.Count > 0)
DirectoryCache.AddOrUpdate(grainId, entries, result.VersionTag);
return result;
}
}
public async Task DeleteGrainAsync(GrainId grainId, int hopCount)
{
// see if the owner is somewhere else (returns null if we are owner)
var forwardAddress = this.CheckIfShouldForward(grainId, hopCount, "DeleteGrainAsync");
// on all silos other than first, we insert a retry delay and recheck owner before forwarding
if (hopCount > 0 && forwardAddress != null)
{
await Task.Delay(RETRY_DELAY);
forwardAddress = this.CheckIfShouldForward(grainId, hopCount, "DeleteGrainAsync(recheck)");
}
if (forwardAddress == null)
{
// we are the owner
var registrar = this.registrarManager.GetRegistrarForGrain(grainId);
if (registrar.IsSynchronous)
registrar.Delete(grainId);
else
await registrar.DeleteAsync(grainId);
}
else
{
// otherwise, notify the owner
DirectoryCache.Remove(grainId);
await GetDirectoryReference(forwardAddress).DeleteGrainAsync(grainId, hopCount + 1);
}
}
public void InvalidateCacheEntry(ActivationAddress activationAddress, bool invalidateDirectoryAlso = false)
{
int version;
IReadOnlyList<Tuple<SiloAddress, ActivationId>> list;
var grainId = activationAddress.Grain;
var activationId = activationAddress.Activation;
// look up grainId activations
if (DirectoryCache.LookUp(grainId, out list, out version))
{
RemoveActivations(DirectoryCache, grainId, list, version, t => t.Item2.Equals(activationId));
}
// for multi-cluster registration, the local directory may cache remote activations
// and we need to remove them here, on the fast path, to avoid forwarding the message
// to the wrong destination again
if (invalidateDirectoryAlso && CalculateTargetSilo(grainId).Equals(MyAddress))
{
var registrar = this.registrarManager.GetRegistrarForGrain(grainId);
registrar.InvalidateCache(activationAddress);
}
}
/// <summary>
/// For testing purposes only.
/// Returns the silo that this silo thinks is the primary owner of directory information for
/// the provided grain ID.
/// </summary>
/// <param name="grain"></param>
/// <returns></returns>
public SiloAddress GetPrimaryForGrain(GrainId grain)
{
return CalculateTargetSilo(grain);
}
/// <summary>
/// For testing purposes only.
/// Returns the silos that this silo thinks hold copies of the directory information for
/// the provided grain ID.
/// </summary>
/// <param name="grain"></param>
/// <returns></returns>
public List<SiloAddress> GetSilosHoldingDirectoryInformationForGrain(GrainId grain)
{
var primary = CalculateTargetSilo(grain);
return FindPredecessors(primary, 1);
}
/// <summary>
/// For testing purposes only.
/// Returns the directory information held by the local silo for the provided grain ID.
/// The result will be null if no information is held.
/// </summary>
/// <param name="grain"></param>
/// <param name="isPrimary"></param>
/// <returns></returns>
public List<ActivationAddress> GetLocalDataForGrain(GrainId grain, out bool isPrimary)
{
var primary = CalculateTargetSilo(grain);
List<ActivationAddress> backupData = HandoffManager.GetHandedOffInfo(grain);
if (MyAddress.Equals(primary))
{
log.Assert(ErrorCode.DirectoryBothPrimaryAndBackupForGrain, backupData == null,
"Silo contains both primary and backup directory data for grain " + grain);
isPrimary = true;
return GetLocalDirectoryData(grain).Addresses;
}
isPrimary = false;
return backupData;
}
#endregion
public override string ToString()
{
var sb = new StringBuilder();
long localLookupsDelta;
long localLookupsCurrent = localLookups.GetCurrentValueAndDelta(out localLookupsDelta);
long localLookupsSucceededDelta;
long localLookupsSucceededCurrent = localSuccesses.GetCurrentValueAndDelta(out localLookupsSucceededDelta);
long fullLookupsDelta;
long fullLookupsCurrent = fullLookups.GetCurrentValueAndDelta(out fullLookupsDelta);
long directoryPartitionSize = directoryPartitionCount.GetCurrentValue();
sb.AppendLine("Local Grain Directory:");
sb.AppendFormat(" Local partition: {0} entries", directoryPartitionSize).AppendLine();
sb.AppendLine(" Since last call:");
sb.AppendFormat(" Local lookups: {0}", localLookupsDelta).AppendLine();
sb.AppendFormat(" Local found: {0}", localLookupsSucceededDelta).AppendLine();
if (localLookupsDelta > 0)
sb.AppendFormat(" Hit rate: {0:F1}%", (100.0 * localLookupsSucceededDelta) / localLookupsDelta).AppendLine();
sb.AppendFormat(" Full lookups: {0}", fullLookupsDelta).AppendLine();
sb.AppendLine(" Since start:");
sb.AppendFormat(" Local lookups: {0}", localLookupsCurrent).AppendLine();
sb.AppendFormat(" Local found: {0}", localLookupsSucceededCurrent).AppendLine();
if (localLookupsCurrent > 0)
sb.AppendFormat(" Hit rate: {0:F1}%", (100.0 * localLookupsSucceededCurrent) / localLookupsCurrent).AppendLine();
sb.AppendFormat(" Full lookups: {0}", fullLookupsCurrent).AppendLine();
sb.Append(DirectoryCache.ToString());
return sb.ToString();
}
private long RingDistanceToSuccessor()
{
long distance;
List<SiloAddress> successorList = FindSuccessors(MyAddress, 1);
if (successorList == null || successorList.Count == 0)
{
distance = 0;
}
else
{
SiloAddress successor = successorList.First();
distance = successor == null ? 0 : CalcRingDistance(MyAddress, successor);
}
return distance;
}
private string RingDistanceToSuccessor_2()
{
const long ringSize = int.MaxValue * 2L;
long distance;
List<SiloAddress> successorList = FindSuccessors(MyAddress, 1);
if (successorList == null || successorList.Count == 0)
{
distance = 0;
}
else
{
SiloAddress successor = successorList.First();
distance = successor == null ? 0 : CalcRingDistance(MyAddress, successor);
}
double averageRingSpace = membershipRingList.Count == 0 ? 0 : (1.0 / (double)membershipRingList.Count);
return string.Format("RingDistance={0:X}, %Ring Space {1:0.00000}%, Average %Ring Space {2:0.00000}%",
distance, ((double)distance / (double)ringSize) * 100.0, averageRingSpace * 100.0);
}
private static long CalcRingDistance(SiloAddress silo1, SiloAddress silo2)
{
const long ringSize = int.MaxValue * 2L;
long hash1 = silo1.GetConsistentHashCode();
long hash2 = silo2.GetConsistentHashCode();
if (hash2 > hash1) return hash2 - hash1;
if (hash2 < hash1) return ringSize - (hash1 - hash2);
return 0;
}
public string RingStatusToString()
{
var sb = new StringBuilder();
sb.AppendFormat("Silo address is {0}, silo consistent hash is {1:X}.", MyAddress, MyAddress.GetConsistentHashCode()).AppendLine();
sb.AppendLine("Ring is:");
lock (membershipCache)
{
foreach (var silo in membershipRingList)
sb.AppendFormat(" Silo {0}, consistent hash is {1:X}", silo, silo.GetConsistentHashCode()).AppendLine();
}
sb.AppendFormat("My predecessors: {0}", FindPredecessors(MyAddress, 1).ToStrings(addr => String.Format("{0}/{1:X}---", addr, addr.GetConsistentHashCode()), " -- ")).AppendLine();
sb.AppendFormat("My successors: {0}", FindSuccessors(MyAddress, 1).ToStrings(addr => String.Format("{0}/{1:X}---", addr, addr.GetConsistentHashCode()), " -- "));
return sb.ToString();
}
internal IRemoteGrainDirectory GetDirectoryReference(SiloAddress silo)
{
return this.grainFactory.GetSystemTarget<IRemoteGrainDirectory>(Constants.DirectoryServiceId, silo);
}
private bool IsSiloNextInTheRing(SiloAddress siloAddr, int hash, bool excludeMySelf)
{
return siloAddr.GetConsistentHashCode() <= hash && (!excludeMySelf || !siloAddr.Equals(MyAddress));
}
private static void RemoveActivations(IGrainDirectoryCache<IReadOnlyList<Tuple<SiloAddress, ActivationId>>> directoryCache, GrainId key, IReadOnlyList<Tuple<SiloAddress, ActivationId>> activations, int version, Func<Tuple<SiloAddress, ActivationId>, bool> doRemove)
{
int removeCount = activations.Count(doRemove);
if (removeCount == 0)
{
return; // nothing to remove, done here
}
if (activations.Count > removeCount) // still some left, update activation list. Note: Most of the time there should be only one activation
{
var newList = new List<Tuple<SiloAddress, ActivationId>>(activations.Count - removeCount);
newList.AddRange(activations.Where(t => !doRemove(t)));
directoryCache.AddOrUpdate(key, newList, version);
}
else // no activations left, remove from cache
{
directoryCache.Remove(key);
}
}
public bool IsSiloInCluster(SiloAddress silo)
{
lock (membershipCache)
{
return membershipCache.Contains(silo);
}
}
}
}
| |
using UnityEngine;
using System.Collections;
public class NotesIterator {
private IEnumerator enumerator;
private bool hasMore;
private float time;
private int column;
private int fraction;
private NotesScript.NotesType type;
public NotesIterator(int[] data) {
this.enumerator = data.GetEnumerator();
advance();
}
private void advance() {
hasMore = enumerator.MoveNext();
if (hasMore) {
time = (int)enumerator.Current / 1000f;
}
hasMore = enumerator.MoveNext();
if (hasMore) {
column = (int)enumerator.Current;
}
hasMore = enumerator.MoveNext();
if (hasMore) {
fraction = (int) enumerator.Current;
}
type = NotesScript.NotesType.TAP; // TODO - taps only
}
public bool hasNext() {
return hasMore;
}
public float nextTime() {
return time;
}
public void next(out float time, out int column, out int fraction, out NotesScript.NotesType type) {
time = this.time;
column = this.column;
fraction = this.fraction;
type = this.type;
advance();
}
public void next(NotesScript note) {
note.Setup(time, column, fraction, type);
advance();
}
}
public class NotesData : MonoBehaviour {
// TODO - this is just temporary until I write a .sm parser
// SMOOOCH_5_MOD is modified to remove 8th notes and a few high notes for Mode 5
public static int[] SMOOOOCH_5_MOD = {
1958, 0, 4,
2297, 1, 4,
4332, 0, 4,
4671, 0, 4,
5010, 1, 4,
7045, 0, 4,
7384, 3, 4,
7723, 1, 4,
9757, 0, 4,
10775, 3, 4,
11114, 0, 4,
11453, 0, 4,
12131, 2, 4,
12470, 3, 4,
12809, 0, 4,
13148, 3, 4,
13487, 2, 4,
13826, 1, 4,
14165, 0, 4,
14505, 3, 4,
14844, 1, 4,
15183, 2, 4,
15522, 0, 4,
15861, 3, 4,
16200, 2, 4,
16539, 1, 4,
16878, 0, 4,
17217, 3, 4,
17556, 2, 4,
17895, 1, 4,
18235, 0, 4,
18574, 3, 4,
18913, 1, 4,
19252, 2, 4,
19591, 3, 4,
19930, 0, 4,
20269, 2, 4,
20608, 1, 4,
20947, 3, 4,
21286, 0, 4,
21626, 2, 4,
21965, 1, 4,
22304, 0, 4,
22643, 1, 4,
22982, 0, 4,
23321, 1, 4,
23660, 0, 4,
23999, 3, 4,
24338, 2, 4,
24677, 1, 4,
25016, 3, 4,
25356, 0, 4,
25695, 2, 4,
26034, 1, 4,
26373, 0, 4,
26712, 3, 4,
27051, 2, 4,
27390, 1, 4,
27729, 0, 4,
28068, 3, 4,
28407, 2, 4,
28746, 1, 4,
29086, 0, 4,
29425, 3, 4,
29764, 2, 4,
30103, 1, 4,
30442, 0, 4,
30781, 1, 4,
31120, 2, 4,
31459, 1, 4,
31798, 2, 4,
32137, 0, 4,
33494, 2, 4,
33833, 1, 4,
34172, 3, 4,
34511, 0, 4,
34850, 3, 4,
35528, 1, 4,
35867, 0, 4,
36207, 3, 4,
36885, 1, 4,
37224, 0, 4,
37563, 3, 4,
38241, 1, 4,
38580, 0, 4,
38919, 3, 4,
39597, 1, 4,
39937, 0, 4,
40276, 3, 4,
40954, 1, 4,
41293, 0, 4,
41632, 3, 4,
42310, 1, 4,
42649, 3, 4,
42988, 0, 4,
43667, 1, 4,
44006, 3, 4,
45023, 2, 4,
45362, 1, 4,
45701, 0, 4,
46040, 2, 4,
46379, 1, 4,
46718, 3, 4,
47057, 3, 4,
47397, 3, 4,
47736, 2, 4,
48075, 1, 4,
48414, 0, 4,
48753, 2, 4,
49092, 1, 4,
49431, 0, 4,
49770, 2, 4,
50109, 1, 4,
50448, 0, 4,
50787, 1, 4,
51127, 0, 4,
51466, 2, 4,
51805, 1, 4,
52144, 0, 4,
52483, 2, 4,
52822, 1, 4,
53161, 0, 4,
53500, 3, 4,
53839, 1, 4,
54857, 3, 4,
55874, 2, 4,
56213, 3, 4,
56552, 1, 4,
58587, 0, 4,
59943, 0, 4,
61299, 0, 4,
62656, 0, 4,
64012, 3, 4,
65368, 3, 4,
65708, 3, 4,
66386, 0, 4,
66725, 2, 4,
67064, 0, 4,
67403, 0, 4,
67742, 3, 4,
69099, 3, 4,
69438, 0, 4,
70455, 3, 4,
70794, 0, 4,
71811, 0, 4,
72150, 3, 4,
73168, 0, 4,
73507, 3, 4,
74524, 3, 4,
74863, 0, 4,
75202, 0, 4,
75541, 2, 4,
75880, 1, 4,
76219, 1, 4,
76559, 0, 4,
76898, 1, 4,
77576, 1, 4,
77915, 0, 4,
78254, 3, 4,
78932, 1, 4,
79271, 3, 4,
79610, 0, 4,
80289, 2, 4,
80628, 0, 4,
80967, 3, 4,
81645, 2, 4,
81984, 3, 4,
82323, 0, 4,
83001, 2, 4,
83340, 0, 4,
83680, 3, 4,
84358, 1, 4,
84697, 0, 4,
85036, 3, 4,
85714, 2, 4,
86053, 0, 4,
86392, 1, 4,
87070, 1, 4,
87410, 0, 4,
87749, 0, 4,
88427, 2, 4,
88766, 1, 4,
89105, 0, 4,
89783, 1, 4,
90122, 0, 4,
90461, 3, 4,
91140, 1, 4,
91479, 1, 4,
91818, 0, 4,
92496, 1, 4,
92835, 1, 4,
93174, 3, 4,
93852, 2, 4,
94191, 0, 4,
94531, 0, 4,
95209, 0, 4,
95887, 2, 4,
96565, 3, 4,
96904, 0, 4,
97243, 0, 4,
97921, 0, 4,
98261, 2, 4,
98600, 3, 4,
99278, 2, 4
};
public static int[] SMOOOOCH_5 = {
1958, 0, 4,
2128, 3, 8,
2297, 1, 4,
4332, 0, 4,
4671, 0, 4,
4840, 3, 8,
5010, 1, 4,
7045, 0, 4,
7384, 3, 4,
7723, 1, 4,
9757, 0, 4,
10775, 3, 4,
11114, 0, 4,
11453, 0, 4,
12131, 2, 4,
12470, 3, 4,
12809, 0, 4,
13148, 3, 4,
13487, 2, 4,
13826, 1, 4,
14165, 0, 4,
14505, 3, 4,
14844, 1, 4,
15183, 2, 4,
15522, 0, 4,
15861, 3, 4,
16200, 2, 4,
16539, 1, 4,
16878, 0, 4,
17217, 3, 4,
17556, 2, 4,
17895, 1, 4,
18235, 0, 4,
18574, 3, 4,
18913, 1, 4,
19252, 2, 4,
19591, 3, 4,
19930, 0, 4,
20269, 2, 4,
20608, 1, 4,
20947, 3, 4,
21286, 0, 4,
21626, 2, 4,
21965, 1, 4,
22304, 0, 4,
22643, 1, 4,
22982, 0, 4,
23321, 1, 4,
23660, 0, 4,
23999, 3, 4,
24338, 2, 4,
24677, 1, 4,
25016, 3, 4,
25356, 0, 4,
25695, 2, 4,
26034, 1, 4,
26373, 0, 4,
26712, 3, 4,
27051, 2, 4,
27390, 1, 4,
27729, 0, 4,
28068, 3, 4,
28407, 2, 4,
28746, 1, 4,
29086, 0, 4,
29425, 3, 4,
29764, 2, 4,
30103, 1, 4,
30442, 0, 4,
30781, 1, 4,
31120, 2, 4,
31459, 1, 4,
31798, 2, 4,
32137, 0, 4,
32646, 1, 8,
32985, 2, 8,
33324, 3, 8,
33494, 2, 4,
33833, 1, 4,
34172, 3, 4,
34511, 0, 4,
34850, 3, 4,
35528, 1, 4,
35867, 0, 4,
36207, 3, 4,
36885, 1, 4,
37224, 0, 4,
37563, 3, 4,
38241, 1, 4,
38580, 0, 4,
38919, 3, 4,
39597, 1, 4,
39937, 0, 4,
40276, 3, 4,
40954, 1, 4,
41293, 0, 4,
41632, 3, 4,
42310, 1, 4,
42649, 3, 4,
42988, 0, 4,
43667, 1, 4,
44006, 3, 4,
45023, 2, 4,
45362, 1, 4,
45701, 0, 4,
46040, 2, 4,
46379, 1, 4,
46718, 3, 4,
47057, 3, 4,
47397, 3, 4,
47736, 2, 4,
48075, 1, 4,
48414, 0, 4,
48753, 2, 4,
49092, 1, 4,
49431, 0, 4,
49770, 2, 4,
49940, 0, 8,
50109, 1, 4,
50448, 0, 4,
50787, 1, 4,
51127, 0, 4,
51466, 2, 4,
51805, 1, 4,
52144, 0, 4,
52483, 2, 4,
52653, 0, 8,
52822, 1, 4,
53161, 0, 4,
53500, 3, 4,
53839, 1, 4,
54857, 3, 4,
55874, 2, 4,
56213, 3, 4,
56552, 1, 4,
58587, 0, 4,
59943, 0, 4,
61299, 0, 4,
62656, 0, 4,
64012, 3, 4,
65368, 3, 4,
65708, 3, 4,
66386, 0, 4,
66725, 2, 4,
67064, 0, 4,
67403, 0, 4,
67742, 3, 4,
69099, 3, 4,
69438, 0, 4,
70455, 3, 4,
70794, 0, 4,
71811, 0, 4,
72150, 3, 4,
73168, 0, 4,
73507, 3, 4,
74524, 3, 4,
74863, 0, 4,
75202, 0, 4,
75541, 2, 4,
75880, 1, 4,
76219, 1, 4,
76559, 0, 4,
76898, 1, 4,
77237, 2, 4,
77576, 1, 4,
77745, 0, 8,
77915, 0, 4,
78254, 3, 4,
78593, 2, 4,
78932, 1, 4,
79271, 3, 4,
79610, 0, 4,
79950, 1, 4,
80289, 2, 4,
80628, 0, 4,
80967, 3, 4,
81306, 1, 4,
81645, 2, 4,
81984, 3, 4,
82323, 0, 4,
82662, 1, 4,
83001, 2, 4,
83340, 0, 4,
83680, 3, 4,
84019, 2, 4,
84358, 1, 4,
84697, 0, 4,
85036, 3, 4,
85375, 1, 4,
85714, 2, 4,
86053, 0, 4,
86392, 1, 4,
86731, 2, 4,
87070, 1, 4,
87410, 0, 4,
87749, 0, 4,
87918, 0, 8,
88088, 0, 4,
88427, 2, 4,
88766, 1, 4,
89105, 0, 4,
89444, 2, 4,
89783, 1, 4,
90122, 0, 4,
90461, 3, 4,
90801, 2, 4,
91140, 1, 4,
91479, 1, 4,
91818, 0, 4,
92157, 2, 4,
92496, 1, 4,
92835, 1, 4,
93174, 3, 4,
93513, 1, 4,
93852, 2, 4,
94191, 0, 4,
94531, 0, 4,
94870, 1, 4,
95209, 0, 4,
95717, 3, 8,
95887, 2, 4,
96226, 1, 4,
96565, 3, 4,
96904, 0, 4,
97243, 0, 4,
97582, 1, 4,
97921, 0, 4,
98261, 2, 4,
98600, 3, 4,
98939, 0, 4,
99278, 2, 4
};
public static int[] SMOOOOCH_7 = {
1958, 0, 4,
2128, 3, 8,
2297, 2, 4,
2636, 3, 4,
3314, 0, 4,
4332, 0, 4,
4671, 0, 4,
4840, 3, 8,
5010, 2, 4,
5349, 3, 4,
6027, 0, 4,
7045, 0, 4,
7384, 3, 4,
7723, 2, 4,
8062, 2, 4,
8740, 0, 4,
9757, 0, 4,
10435, 3, 4,
10775, 3, 4,
11114, 0, 4,
11453, 0, 4,
12131, 2, 4,
12470, 3, 4,
12640, 1, 8,
12809, 3, 4,
12979, 1, 8,
13148, 2, 4,
13487, 0, 4,
13826, 1, 4,
14165, 0, 4,
14335, 2, 8,
14505, 1, 4,
14844, 3, 4,
15183, 2, 4,
15522, 0, 4,
15691, 2, 8,
15861, 1, 4,
16200, 3, 4,
16539, 2, 4,
16878, 3, 4,
17048, 1, 8,
17217, 2, 4,
17556, 0, 4,
17895, 1, 4,
18235, 0, 4,
18404, 1, 8,
18574, 2, 4,
18913, 3, 4,
19252, 1, 4,
19591, 3, 4,
19760, 1, 8,
19930, 2, 4,
20269, 0, 4,
20608, 1, 4,
20947, 0, 4,
21117, 1, 8,
21286, 2, 4,
21626, 3, 4,
21965, 1, 4,
22304, 0, 4,
22643, 3, 4,
22982, 1, 4,
23151, 3, 8,
23491, 0, 8,
23660, 3, 4,
23830, 1, 8,
23999, 2, 4,
24338, 0, 4,
24677, 1, 4,
25016, 0, 4,
25186, 1, 8,
25356, 2, 4,
25695, 3, 4,
26034, 1, 4,
26373, 3, 4,
26542, 1, 8,
26712, 2, 4,
27051, 0, 4,
27390, 1, 4,
27729, 0, 4,
27899, 1, 8,
28068, 2, 4,
28407, 3, 4,
28746, 1, 4,
29086, 3, 4,
29255, 2, 8,
29425, 1, 4,
29764, 0, 4,
30103, 2, 4,
30442, 3, 4,
30781, 1, 4,
31120, 3, 4,
31459, 2, 4,
31798, 1, 4,
32137, 0, 4,
32307, 3, 8,
32646, 0, 8,
32816, 1, 4,
32985, 0, 8,
33324, 0, 8,
33494, 3, 4,
33833, 0, 4,
34172, 1, 4,
34341, 2, 8,
34511, 0, 4,
34850, 2, 4,
35189, 0, 4,
35528, 3, 4,
35867, 3, 4,
36207, 1, 4,
36546, 3, 4,
36885, 0, 4,
37224, 0, 4,
37563, 2, 4,
37902, 0, 4,
38241, 3, 4,
38580, 0, 4,
38919, 1, 4,
39258, 0, 4,
39597, 3, 4,
39937, 3, 4,
40276, 2, 4,
40615, 3, 4,
40954, 0, 4,
41293, 3, 4,
41632, 2, 4,
41971, 3, 4,
42310, 0, 4,
42649, 0, 4,
42988, 2, 4,
43327, 0, 4,
43667, 3, 4,
44006, 0, 4,
45023, 3, 4,
45362, 0, 4,
45701, 1, 4,
46040, 2, 4,
46210, 1, 8,
46379, 2, 4,
46718, 3, 4,
47057, 3, 4,
47227, 1, 8,
47397, 1, 4,
47736, 3, 4,
48075, 0, 4,
48414, 1, 4,
48753, 2, 4,
48922, 1, 8,
49092, 2, 4,
49431, 0, 4,
49770, 1, 4,
49940, 0, 8,
50109, 2, 4,
50279, 0, 8,
50448, 1, 4,
50787, 0, 4,
51127, 1, 4,
51466, 2, 4,
51635, 1, 8,
51805, 2, 4,
52144, 0, 4,
52483, 1, 4,
52653, 0, 8,
52822, 2, 4,
52992, 0, 8,
53161, 1, 4,
53500, 3, 4,
53839, 2, 4,
54178, 2, 4,
54857, 3, 4,
55874, 1, 4,
56043, 2, 8,
56213, 3, 4,
56552, 2, 4,
56891, 2, 4,
57569, 0, 4,
58587, 0, 4,
58926, 0, 4,
59943, 0, 4,
60282, 0, 4,
61299, 0, 4,
61638, 0, 4,
62656, 0, 4,
62995, 3, 4,
64012, 3, 4,
64351, 3, 4,
65368, 3, 4,
65708, 3, 4,
66386, 1, 4,
66725, 3, 4,
67064, 0, 4,
67403, 2, 4,
67742, 3, 4,
68759, 3, 4,
69099, 3, 4,
69438, 0, 4,
70116, 3, 4,
70455, 3, 4,
70794, 0, 4,
71472, 0, 4,
71811, 0, 4,
72150, 3, 4,
72829, 3, 4,
73168, 3, 4,
73507, 0, 4,
74185, 3, 4,
74524, 3, 4,
74863, 0, 4,
75202, 3, 4,
75541, 2, 4,
75880, 1, 4,
76050, 2, 8,
76219, 2, 4,
76559, 0, 4,
76898, 0, 4,
77237, 1, 4,
77406, 2, 8,
77576, 1, 4,
77745, 0, 8,
77915, 3, 4,
78084, 1, 8,
78254, 2, 4,
78593, 0, 4,
78932, 1, 4,
79271, 0, 4,
79441, 2, 8,
79610, 1, 4,
79950, 3, 4,
80289, 2, 4,
80628, 3, 4,
80797, 1, 8,
80967, 2, 4,
81306, 0, 4,
81645, 1, 4,
81984, 0, 4,
82154, 1, 8,
82323, 2, 4,
82662, 3, 4,
83001, 1, 4,
83340, 3, 4,
83510, 2, 8,
83680, 1, 4,
84019, 0, 4,
84358, 2, 4,
84697, 0, 4,
84866, 1, 8,
85036, 2, 4,
85375, 3, 4,
85714, 1, 4,
86053, 0, 4,
86392, 2, 4,
86731, 1, 4,
86901, 1, 8,
87070, 2, 4,
87410, 1, 4,
87749, 0, 4,
87918, 0, 8,
88088, 0, 4,
88427, 2, 4,
88766, 0, 4,
89105, 1, 4,
89444, 2, 4,
89614, 1, 8,
89783, 2, 4,
90122, 3, 4,
90292, 1, 8,
90461, 2, 4,
90801, 0, 4,
91140, 1, 4,
91479, 0, 4,
91818, 1, 4,
92157, 2, 4,
92326, 1, 8,
92496, 2, 4,
92835, 1, 4,
93174, 1, 4,
93513, 2, 4,
93683, 1, 8,
93852, 2, 4,
94191, 0, 4,
94531, 3, 4,
94700, 2, 8,
94870, 3, 4,
95209, 2, 4,
95717, 0, 8,
95887, 3, 4,
96226, 0, 4,
96565, 1, 4,
96904, 0, 4,
97243, 3, 4,
97413, 2, 8,
97582, 3, 4,
97921, 2, 4,
98261, 0, 4,
98600, 3, 4,
98939, 0, 4,
99278, 2, 4
};
public static int[] SMOOOOCH_9 = {
1789, 0, 8,
3314, 0, 4,
3654, 3, 4,
3823, 2, 8,
3993, 3, 4,
4501, 0, 8,
4671, 3, 4,
5688, 3, 4,
6027, 0, 4,
6366, 3, 4,
6536, 2, 8,
6705, 3, 4,
7214, 0, 8,
7384, 3, 4,
8401, 3, 4,
8570, 3, 8,
8740, 3, 4,
8910, 1, 8,
9079, 2, 4,
9418, 2, 4,
10096, 3, 4,
11114, 3, 4,
11283, 3, 8,
11622, 0, 8,
12131, 0, 4,
12300, 2, 8,
12470, 0, 4,
12809, 0, 4,
13148, 2, 4,
13487, 0, 4,
13826, 1, 4,
13996, 2, 8,
14165, 3, 4,
14335, 2, 8,
14505, 1, 4,
14844, 0, 4,
15013, 1, 8,
15183, 0, 4,
15352, 2, 8,
15522, 3, 4,
15691, 1, 8,
15861, 2, 4,
16200, 0, 4,
16370, 2, 8,
16539, 0, 4,
16709, 1, 8,
16878, 3, 4,
17048, 2, 8,
17217, 1, 4,
17556, 0, 4,
17726, 1, 8,
17895, 0, 4,
18065, 2, 8,
18235, 3, 4,
18404, 2, 8,
18574, 1, 4,
18913, 0, 4,
19082, 1, 8,
19252, 0, 4,
19421, 2, 8,
19591, 0, 4,
19760, 2, 8,
19930, 1, 4,
20269, 3, 4,
20439, 1, 8,
20608, 3, 4,
20778, 2, 8,
20947, 0, 4,
21117, 1, 8,
21286, 2, 4,
21626, 3, 4,
21795, 2, 8,
21965, 3, 4,
22134, 1, 8,
22304, 0, 4,
22473, 2, 8,
22643, 1, 4,
22982, 3, 4,
23151, 1, 8,
23321, 3, 4,
23660, 1, 4,
23999, 1, 4,
24169, 3, 8,
24338, 1, 4,
24508, 3, 8,
24847, 2, 8,
25016, 3, 4,
25186, 2, 8,
25356, 1, 4,
25695, 0, 4,
25864, 1, 8,
26034, 0, 4,
26203, 2, 8,
26373, 0, 4,
26542, 1, 8,
26712, 2, 4,
27051, 3, 4,
27221, 2, 8,
27390, 3, 4,
27560, 1, 8,
27729, 3, 4,
27899, 2, 8,
28068, 1, 4,
28407, 0, 4,
28577, 1, 8,
28746, 0, 4,
28916, 2, 8,
29086, 3, 4,
29255, 1, 8,
29425, 2, 4,
29764, 0, 4,
29933, 2, 8,
30103, 0, 4,
30272, 1, 8,
30442, 0, 4,
30611, 2, 8,
30781, 1, 4,
31120, 3, 4,
31290, 1, 8,
31459, 3, 4,
31798, 0, 4,
32137, 1, 4,
32307, 3, 8,
32476, 2, 4,
32646, 1, 8,
32816, 0, 4,
33155, 1, 4,
33494, 1, 4,
33663, 2, 8,
34002, 3, 8,
34341, 1, 8,
34681, 3, 8,
34850, 1, 4,
35189, 0, 4,
35528, 2, 4,
35698, 0, 8,
35867, 0, 4,
36037, 1, 8,
36207, 2, 4,
36546, 1, 4,
36715, 2, 8,
36885, 3, 4,
37054, 0, 8,
37224, 3, 4,
37393, 2, 8,
37563, 1, 4,
37902, 2, 4,
38072, 1, 8,
38241, 0, 4,
38411, 3, 8,
38580, 3, 4,
38750, 2, 8,
38919, 1, 4,
39258, 2, 4,
39428, 1, 8,
39597, 0, 4,
39767, 3, 8,
39937, 0, 4,
40106, 1, 8,
40276, 2, 4,
40615, 1, 4,
40784, 2, 8,
40954, 3, 4,
41123, 0, 8,
41293, 0, 4,
41462, 1, 8,
41632, 2, 4,
41971, 1, 4,
42141, 2, 8,
42310, 3, 4,
42480, 0, 8,
42649, 0, 4,
42819, 1, 8,
42988, 2, 4,
43327, 1, 4,
43497, 2, 8,
43667, 3, 4,
43836, 0, 8,
44006, 0, 4,
44175, 2, 8,
44345, 1, 4,
44684, 2, 4,
44853, 1, 8,
45023, 3, 4,
45362, 1, 4,
46210, 2, 8,
46379, 0, 4,
46718, 0, 4,
47057, 1, 4,
47227, 3, 8,
47397, 1, 4,
47566, 2, 8,
47736, 0, 4,
48075, 0, 4,
48414, 0, 4,
48753, 2, 4,
49092, 1, 4,
49431, 0, 4,
49770, 1, 4,
49940, 3, 8,
50109, 1, 4,
50279, 2, 8,
50448, 0, 4,
50787, 0, 4,
51127, 1, 4,
51296, 0, 8,
51466, 2, 4,
51635, 1, 8,
51805, 2, 4,
52144, 0, 4,
52483, 1, 4,
52653, 3, 8,
52822, 1, 4,
52992, 2, 8,
53161, 0, 4,
53500, 0, 4,
53839, 1, 4,
54009, 0, 8,
54178, 2, 4,
54348, 1, 8,
54518, 2, 4,
54857, 3, 4,
55026, 1, 8,
55196, 2, 4,
55535, 2, 4,
56213, 3, 4,
56891, 1, 4,
57230, 0, 4,
57400, 1, 8,
57569, 3, 4,
57739, 1, 8,
57908, 2, 4,
58248, 2, 4,
58926, 3, 4,
59943, 3, 4,
60113, 3, 8,
60282, 0, 4,
61299, 0, 4,
61469, 0, 8,
61638, 0, 4,
62656, 0, 4,
62825, 0, 8,
62995, 3, 4,
64012, 3, 4,
64182, 3, 8,
64351, 0, 4,
65368, 0, 4,
65538, 0, 8,
65708, 3, 4,
66725, 3, 4,
66894, 3, 8,
67064, 3, 4,
67403, 2, 4,
67573, 3, 8,
67742, 2, 4,
68081, 3, 4,
68420, 2, 4,
68759, 0, 4,
69099, 2, 4,
69438, 0, 4,
69607, 1, 8,
69946, 0, 8,
70455, 0, 4,
70624, 2, 8,
70794, 0, 4,
70964, 0, 8,
71303, 0, 8,
71811, 0, 4,
71981, 2, 8,
72150, 0, 4,
72320, 0, 8,
72659, 3, 8,
73168, 3, 4,
73337, 2, 8,
73507, 3, 4,
73676, 3, 8,
74015, 0, 8,
74524, 0, 4,
74694, 2, 8,
74863, 0, 4,
75033, 0, 8,
75372, 0, 8,
75880, 0, 4,
76050, 2, 8,
76219, 0, 4,
76389, 0, 8,
76559, 0, 4,
76728, 3, 8,
76898, 0, 4,
77237, 0, 4,
77576, 3, 4,
77915, 1, 4,
78254, 2, 4,
78424, 1, 8,
78593, 2, 4,
78763, 1, 8,
78932, 3, 4,
79102, 2, 8,
79271, 3, 4,
79441, 2, 8,
79610, 1, 4,
79950, 0, 4,
80119, 1, 8,
80289, 0, 4,
80458, 2, 8,
80628, 0, 4,
80797, 2, 8,
80967, 1, 4,
81306, 3, 4,
81475, 1, 8,
81645, 3, 4,
81815, 2, 8,
81984, 0, 4,
82154, 1, 8,
82323, 2, 4,
82662, 3, 4,
82832, 2, 8,
83001, 3, 4,
83171, 1, 8,
83340, 0, 4,
83510, 2, 8,
83680, 1, 4,
84019, 3, 4,
84188, 1, 8,
84358, 3, 4,
84527, 2, 8,
84697, 3, 4,
84866, 1, 8,
85036, 2, 4,
85375, 0, 4,
85545, 2, 8,
85714, 0, 4,
85884, 1, 8,
86053, 3, 4,
86223, 2, 8,
86392, 1, 4,
86731, 0, 4,
86901, 1, 8,
87070, 0, 4,
87410, 0, 4,
87749, 0, 4,
88088, 1, 4,
88427, 0, 4,
88766, 0, 4,
89105, 0, 4,
89275, 0, 8,
89444, 0, 4,
89783, 2, 4,
90122, 0, 4,
90461, 1, 4,
90631, 3, 8,
90801, 1, 4,
90970, 2, 8,
91140, 0, 4,
91479, 3, 4,
91648, 2, 8,
91818, 1, 4,
92157, 0, 4,
92326, 1, 8,
92496, 0, 4,
92835, 0, 4,
93174, 1, 4,
93344, 3, 8,
93513, 1, 4,
93683, 2, 8,
93852, 0, 4,
94191, 0, 4,
94531, 1, 4,
94700, 0, 8,
94870, 1, 4,
95039, 2, 8,
95209, 3, 4,
95548, 0, 4,
95887, 1, 4,
96056, 3, 8,
96226, 0, 4,
96565, 2, 4,
97074, 3, 8,
97243, 1, 4,
97582, 0, 4,
97921, 2, 4,
98261, 0, 4,
98600, 1, 4,
98769, 3, 8,
98939, 0, 4,
99278, 2, 4,
99617, 0, 4,
99956, 2, 4,
100126, 2, 8,
100295, 0, 4,
100465, 2, 8,
100634, 0, 4,
100804, 0, 8,
102160, 0, 8,
103517, 3, 8
};
public static int[] SMOOOOCH_DATA = NotesData.SMOOOOCH_5_MOD;
public static string DIFFICULTY_EASY = "Easy";
public static string DIFFICULTY_MEDIUM = "Medium";
public static string DIFFICULTY_HARD = "Hard";
public static string DIFFICULTY_LEVEL = DIFFICULTY_EASY;
}
| |
// 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.
#nullable enable
using System.Buffers;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Text
{
internal ref partial struct ValueStringBuilder
{
private char[]? _arrayToReturnToPool;
private Span<char> _chars;
private int _pos;
public ValueStringBuilder(Span<char> initialBuffer)
{
_arrayToReturnToPool = null;
_chars = initialBuffer;
_pos = 0;
}
public ValueStringBuilder(int initialCapacity)
{
_arrayToReturnToPool = ArrayPool<char>.Shared.Rent(initialCapacity);
_chars = _arrayToReturnToPool;
_pos = 0;
}
public int Length
{
get => _pos;
set
{
Debug.Assert(value >= 0);
Debug.Assert(value <= _chars.Length);
_pos = value;
}
}
public int Capacity => _chars.Length;
public void EnsureCapacity(int capacity)
{
if (capacity > _chars.Length)
Grow(capacity - _pos);
}
/// <summary>
/// Get a pinnable reference to the builder.
/// Does not ensure there is a null char after <see cref="Length"/>
/// This overload is pattern matched in the C# 7.3+ compiler so you can omit
/// the explicit method call, and write eg "fixed (char* c = builder)"
/// </summary>
public ref char GetPinnableReference()
{
return ref MemoryMarshal.GetReference(_chars);
}
/// <summary>
/// Get a pinnable reference to the builder.
/// </summary>
/// <param name="terminate">Ensures that the builder has a null char after <see cref="Length"/></param>
public ref char GetPinnableReference(bool terminate)
{
if (terminate)
{
EnsureCapacity(Length + 1);
_chars[Length] = '\0';
}
return ref MemoryMarshal.GetReference(_chars);
}
public ref char this[int index]
{
get
{
Debug.Assert(index < _pos);
return ref _chars[index];
}
}
public override string ToString()
{
string s = _chars.Slice(0, _pos).ToString();
Dispose();
return s;
}
/// <summary>Returns the underlying storage of the builder.</summary>
public Span<char> RawChars => _chars;
/// <summary>
/// Returns a span around the contents of the builder.
/// </summary>
/// <param name="terminate">Ensures that the builder has a null char after <see cref="Length"/></param>
public ReadOnlySpan<char> AsSpan(bool terminate)
{
if (terminate)
{
EnsureCapacity(Length + 1);
_chars[Length] = '\0';
}
return _chars.Slice(0, _pos);
}
public ReadOnlySpan<char> AsSpan() => _chars.Slice(0, _pos);
public ReadOnlySpan<char> AsSpan(int start) => _chars.Slice(start, _pos - start);
public ReadOnlySpan<char> AsSpan(int start, int length) => _chars.Slice(start, length);
public bool TryCopyTo(Span<char> destination, out int charsWritten)
{
if (_chars.Slice(0, _pos).TryCopyTo(destination))
{
charsWritten = _pos;
Dispose();
return true;
}
else
{
charsWritten = 0;
Dispose();
return false;
}
}
public void Insert(int index, char value, int count)
{
if (_pos > _chars.Length - count)
{
Grow(count);
}
int remaining = _pos - index;
_chars.Slice(index, remaining).CopyTo(_chars.Slice(index + count));
_chars.Slice(index, count).Fill(value);
_pos += count;
}
public void Insert(int index, string s)
{
int count = s.Length;
if (_pos > (_chars.Length - count))
{
Grow(count);
}
int remaining = _pos - index;
_chars.Slice(index, remaining).CopyTo(_chars.Slice(index + count));
s.AsSpan().CopyTo(_chars.Slice(index));
_pos += count;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Append(char c)
{
int pos = _pos;
if ((uint)pos < (uint)_chars.Length)
{
_chars[pos] = c;
_pos = pos + 1;
}
else
{
GrowAndAppend(c);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Append(string s)
{
int pos = _pos;
if (s.Length == 1 && (uint)pos < (uint)_chars.Length) // very common case, e.g. appending strings from NumberFormatInfo like separators, percent symbols, etc.
{
_chars[pos] = s[0];
_pos = pos + 1;
}
else
{
AppendSlow(s);
}
}
private void AppendSlow(string s)
{
int pos = _pos;
if (pos > _chars.Length - s.Length)
{
Grow(s.Length);
}
s.AsSpan().CopyTo(_chars.Slice(pos));
_pos += s.Length;
}
public void Append(char c, int count)
{
if (_pos > _chars.Length - count)
{
Grow(count);
}
Span<char> dst = _chars.Slice(_pos, count);
for (int i = 0; i < dst.Length; i++)
{
dst[i] = c;
}
_pos += count;
}
public unsafe void Append(char* value, int length)
{
int pos = _pos;
if (pos > _chars.Length - length)
{
Grow(length);
}
Span<char> dst = _chars.Slice(_pos, length);
for (int i = 0; i < dst.Length; i++)
{
dst[i] = *value++;
}
_pos += length;
}
public void Append(ReadOnlySpan<char> value)
{
int pos = _pos;
if (pos > _chars.Length - value.Length)
{
Grow(value.Length);
}
value.CopyTo(_chars.Slice(_pos));
_pos += value.Length;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span<char> AppendSpan(int length)
{
int origPos = _pos;
if (origPos > _chars.Length - length)
{
Grow(length);
}
_pos = origPos + length;
return _chars.Slice(origPos, length);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void GrowAndAppend(char c)
{
Grow(1);
Append(c);
}
/// <summary>
/// Resize the internal buffer either by doubling current buffer size or
/// by adding <paramref name="additionalCapacityBeyondPos"/> to
/// <see cref="_pos"/> whichever is greater.
/// </summary>
/// <param name="additionalCapacityBeyondPos">
/// Number of chars requested beyond current position.
/// </param>
[MethodImpl(MethodImplOptions.NoInlining)]
private void Grow(int additionalCapacityBeyondPos)
{
Debug.Assert(additionalCapacityBeyondPos > 0);
Debug.Assert(_pos > _chars.Length - additionalCapacityBeyondPos, "Grow called incorrectly, no resize is needed.");
char[] poolArray = ArrayPool<char>.Shared.Rent(Math.Max(_pos + additionalCapacityBeyondPos, _chars.Length * 2));
_chars.CopyTo(poolArray);
char[]? toReturn = _arrayToReturnToPool;
_chars = _arrayToReturnToPool = poolArray;
if (toReturn != null)
{
ArrayPool<char>.Shared.Return(toReturn);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Dispose()
{
char[]? toReturn = _arrayToReturnToPool;
this = default; // for safety, to avoid using pooled array if this instance is erroneously appended to again
if (toReturn != null)
{
ArrayPool<char>.Shared.Return(toReturn);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using KotoriCore.Domains;
using KotoriCore.Exceptions;
using Newtonsoft.Json.Linq;
using Shushu;
namespace KotoriCore.Helpers.MetaAnalyzer
{
// TODO
public class DefaultMetaAnalyzer : IMetaAnalyzer
{
Enums.MetaType GetMetaType(object o)
{
if (o == null)
return Enums.MetaType.Null;
var type = o.GetType();
if (type == typeof(string))
return Enums.MetaType.String;
if (type == typeof(int?) ||
type == typeof(int) ||
type == typeof(Int64?) ||
type == typeof(Int64))
return Enums.MetaType.Integer;
if (type == typeof(bool?) ||
type == typeof(bool))
return Enums.MetaType.Boolean;
if (type == typeof(double?) ||
type == typeof(double) ||
type == typeof(float?) ||
type == typeof(float))
return Enums.MetaType.Number;
if (type == typeof(JArray))
{
if (o is JArray ar)
{
if (ar.Any())
{
if (ar.First().Type == JTokenType.String)
return Enums.MetaType.Tags;
}
}
else
{
return Enums.MetaType.Array;
}
}
if (type == typeof(DateTime?) ||
type == typeof(DateTime))
return Enums.MetaType.Date;
return Enums.MetaType.Object;
}
bool AreTypesCompatible(Enums.MetaType from, Enums.MetaType to)
{
if (from == to)
return true;
if (from == Enums.MetaType.Null ||
to == Enums.MetaType.Null)
return true;
if (from == Enums.MetaType.Integer ||
to == Enums.MetaType.Number)
return true;
return false;
}
/// <summary>
/// Gets the updated document type indexes.
/// </summary>
/// <returns>The updated document type indexes.</returns>
/// <param name="indexes">Indexes.</param>
/// <param name="meta">Meta.</param>
public IList<DocumentTypeIndex> GetUpdatedDocumentTypeIndexes(IList<DocumentTypeIndex> indexes, dynamic meta)
{
var indexes2 = indexes.ToList();
var result = new List<DocumentTypeIndex>(indexes);
var metaObj = JObject.FromObject(meta);
Dictionary<string, object> meta2 = metaObj.ToObject<Dictionary<string, object>>();
if (meta2 != null)
{
foreach (var key in meta2.Keys)
{
var v = meta2[key];
var t = v.GetType();
var availables = GetAvailableFieldsForType(t, v);
// we cannot index this type
if (!availables.Any())
continue;
// key's been indexed already - check type compatibility
var ex = indexes2.FirstOrDefault(x => x.From.Equals(key, StringComparison.OrdinalIgnoreCase));
var mt = GetMetaType(v);
if (ex != null)
{
if (!AreTypesCompatible(ex.Type, mt))
throw new KotoriValidationException($"Meta property '{key}' is not acceptable because type '{mt} cannot be converted to {ex.Type}.");
if (availables.All(x => x != ex.To))
throw new KotoriValidationException($"Meta property '{key}' cannot be mapped because it has been alreade mapped to '{ex.To}'.");
continue;
}
var aidx = availables.Where(x => indexes2.All(xx => xx.To != x) && result.All(xx => xx.To != x));
if (!aidx.Any())
aidx = null;
result.Add(new DocumentTypeIndex(key, aidx?.First(), mt));
}
}
else
{
return indexes2;
}
return result;
}
/// <summary>
/// Gets the available fields for the given type.
/// </summary>
/// <returns>The available fields for given type.</returns>
/// <param name="type">Type.</param>
/// <param name="val">Value.</param>
public IList<Shushu.Enums.IndexField> GetAvailableFieldsForType(Type type, object val)
{
if (type == typeof(string))
return new List<Shushu.Enums.IndexField>
{
Shushu.Enums.IndexField.Text7,
Shushu.Enums.IndexField.Text8,
Shushu.Enums.IndexField.Text9,
Shushu.Enums.IndexField.Text10,
Shushu.Enums.IndexField.Text11,
Shushu.Enums.IndexField.Text12,
Shushu.Enums.IndexField.Text13,
Shushu.Enums.IndexField.Text14,
Shushu.Enums.IndexField.Text15,
Shushu.Enums.IndexField.Text16,
Shushu.Enums.IndexField.Text17,
Shushu.Enums.IndexField.Text18,
Shushu.Enums.IndexField.Text19
};
if (type == typeof(int?) ||
type == typeof(int) ||
type == typeof(Int64?) ||
type == typeof(Int64))
return new List<Shushu.Enums.IndexField>
{
Shushu.Enums.IndexField.Number0,
Shushu.Enums.IndexField.Number1,
Shushu.Enums.IndexField.Number2,
Shushu.Enums.IndexField.Number3,
Shushu.Enums.IndexField.Number4,
Shushu.Enums.IndexField.Number5,
Shushu.Enums.IndexField.Number6,
Shushu.Enums.IndexField.Number7,
Shushu.Enums.IndexField.Number8,
Shushu.Enums.IndexField.Number9
};
if (type == typeof(bool?) ||
type == typeof(bool))
return new List<Shushu.Enums.IndexField>
{
Shushu.Enums.IndexField.Flag1,
Shushu.Enums.IndexField.Flag2,
Shushu.Enums.IndexField.Flag3,
Shushu.Enums.IndexField.Flag4,
Shushu.Enums.IndexField.Flag5,
Shushu.Enums.IndexField.Flag6,
Shushu.Enums.IndexField.Flag7,
Shushu.Enums.IndexField.Flag8,
Shushu.Enums.IndexField.Flag9
};
if (type == typeof(double?) ||
type == typeof(double) ||
type == typeof(float?) ||
type == typeof(float))
return new List<Shushu.Enums.IndexField>
{
Shushu.Enums.IndexField.Double0,
Shushu.Enums.IndexField.Double1,
Shushu.Enums.IndexField.Double2,
Shushu.Enums.IndexField.Double3,
Shushu.Enums.IndexField.Double4,
Shushu.Enums.IndexField.Double5,
Shushu.Enums.IndexField.Double6,
Shushu.Enums.IndexField.Double7,
Shushu.Enums.IndexField.Double8,
Shushu.Enums.IndexField.Double9
};
if (type == typeof(JArray))
{
if (val is JArray ar)
{
if (ar.Any())
{
if (ar.First().Type == JTokenType.String)
{
return new List<Shushu.Enums.IndexField>
{
Shushu.Enums.IndexField.Tags0,
Shushu.Enums.IndexField.Tags1,
Shushu.Enums.IndexField.Tags2,
Shushu.Enums.IndexField.Tags3,
Shushu.Enums.IndexField.Tags4,
Shushu.Enums.IndexField.Tags5,
Shushu.Enums.IndexField.Tags6,
Shushu.Enums.IndexField.Tags7,
Shushu.Enums.IndexField.Tags8,
Shushu.Enums.IndexField.Tags9
};
}
}
}
}
if (type == typeof(DateTime?) ||
type == typeof(DateTime))
return new List<Shushu.Enums.IndexField>
{
Shushu.Enums.IndexField.Date2,
Shushu.Enums.IndexField.Date3,
Shushu.Enums.IndexField.Date4
};
// no suitable fields
return new List<Shushu.Enums.IndexField>();
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Input;
using osu.Framework.Input.Events;
using osu.Framework.Logging;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Configuration;
using osu.Game.Rulesets.Edit.Tools;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.UI;
using osu.Game.Rulesets.UI.Scrolling;
using osu.Game.Screens.Edit;
using osu.Game.Screens.Edit.Components.RadioButtons;
using osu.Game.Screens.Edit.Components.TernaryButtons;
using osu.Game.Screens.Edit.Compose;
using osu.Game.Screens.Edit.Compose.Components;
using osuTK;
using osuTK.Input;
namespace osu.Game.Rulesets.Edit
{
/// <summary>
/// Top level container for editor compose mode.
/// Responsible for providing snapping and generally gluing components together.
/// </summary>
/// <typeparam name="TObject">The base type of supported objects.</typeparam>
[Cached(Type = typeof(IPlacementHandler))]
public abstract class HitObjectComposer<TObject> : HitObjectComposer, IPlacementHandler
where TObject : HitObject
{
protected IRulesetConfigManager Config { get; private set; }
protected readonly Ruleset Ruleset;
// Provides `Playfield`
private DependencyContainer dependencies;
[Resolved]
protected EditorClock EditorClock { get; private set; }
[Resolved]
protected EditorBeatmap EditorBeatmap { get; private set; }
[Resolved]
protected IBeatSnapProvider BeatSnapProvider { get; private set; }
protected ComposeBlueprintContainer BlueprintContainer { get; private set; }
private DrawableEditorRulesetWrapper<TObject> drawableRulesetWrapper;
protected readonly Container LayerBelowRuleset = new Container { RelativeSizeAxes = Axes.Both };
private InputManager inputManager;
private EditorRadioButtonCollection toolboxCollection;
private FillFlowContainer togglesCollection;
private IBindable<bool> hasTiming;
protected HitObjectComposer(Ruleset ruleset)
{
Ruleset = ruleset;
}
protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent) =>
dependencies = new DependencyContainer(base.CreateChildDependencies(parent));
[BackgroundDependencyLoader]
private void load()
{
Config = Dependencies.Get<RulesetConfigCache>().GetConfigFor(Ruleset);
try
{
drawableRulesetWrapper = new DrawableEditorRulesetWrapper<TObject>(CreateDrawableRuleset(Ruleset, EditorBeatmap.PlayableBeatmap, new[] { Ruleset.GetAutoplayMod() }))
{
Clock = EditorClock,
ProcessCustomClock = false
};
}
catch (Exception e)
{
Logger.Error(e, "Could not load beatmap successfully!");
return;
}
dependencies.CacheAs(Playfield);
const float toolbar_width = 200;
InternalChildren = new Drawable[]
{
new Container
{
Name = "Content",
Padding = new MarginPadding { Left = toolbar_width },
RelativeSizeAxes = Axes.Both,
Children = new Drawable[]
{
// layers below playfield
drawableRulesetWrapper.CreatePlayfieldAdjustmentContainer().WithChild(LayerBelowRuleset),
drawableRulesetWrapper,
// layers above playfield
drawableRulesetWrapper.CreatePlayfieldAdjustmentContainer()
.WithChild(BlueprintContainer = CreateBlueprintContainer())
}
},
new FillFlowContainer
{
Name = "Sidebar",
RelativeSizeAxes = Axes.Y,
Width = toolbar_width,
Padding = new MarginPadding { Right = 10 },
Spacing = new Vector2(10),
Children = new Drawable[]
{
new ToolboxGroup("toolbox (1-9)")
{
Child = toolboxCollection = new EditorRadioButtonCollection { RelativeSizeAxes = Axes.X }
},
new ToolboxGroup("toggles (Q~P)")
{
Child = togglesCollection = new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Direction = FillDirection.Vertical,
Spacing = new Vector2(0, 5),
},
}
}
},
};
toolboxCollection.Items = CompositionTools
.Prepend(new SelectTool())
.Select(t => new RadioButton(t.Name, () => toolSelected(t), t.CreateIcon))
.ToList();
TernaryStates = CreateTernaryButtons().ToArray();
togglesCollection.AddRange(TernaryStates.Select(b => new DrawableTernaryButton(b)));
setSelectTool();
EditorBeatmap.SelectedHitObjects.CollectionChanged += selectionChanged;
}
protected override void LoadComplete()
{
base.LoadComplete();
inputManager = GetContainingInputManager();
hasTiming = EditorBeatmap.HasTiming.GetBoundCopy();
hasTiming.BindValueChanged(timing =>
{
// it's important this is performed before the similar code in EditorRadioButton disables the button.
if (!timing.NewValue)
setSelectTool();
});
}
public override Playfield Playfield => drawableRulesetWrapper.Playfield;
public override IEnumerable<DrawableHitObject> HitObjects => drawableRulesetWrapper.Playfield.AllHitObjects;
public override bool CursorInPlacementArea => drawableRulesetWrapper.Playfield.ReceivePositionalInputAt(inputManager.CurrentState.Mouse.Position);
/// <summary>
/// Defines all available composition tools, listed on the left side of the editor screen as button controls.
/// This should usually define one tool for each <see cref="HitObject"/> type used in the target ruleset.
/// </summary>
/// <remarks>
/// A "select" tool is automatically added as the first tool.
/// </remarks>
protected abstract IReadOnlyList<HitObjectCompositionTool> CompositionTools { get; }
/// <summary>
/// A collection of states which will be displayed to the user in the toolbox.
/// </summary>
public TernaryButton[] TernaryStates { get; private set; }
/// <summary>
/// Create all ternary states required to be displayed to the user.
/// </summary>
protected virtual IEnumerable<TernaryButton> CreateTernaryButtons() => BlueprintContainer.TernaryStates;
/// <summary>
/// Construct a relevant blueprint container. This will manage hitobject selection/placement input handling and display logic.
/// </summary>
protected virtual ComposeBlueprintContainer CreateBlueprintContainer() => new ComposeBlueprintContainer(this);
/// <summary>
/// Construct a drawable ruleset for the provided ruleset.
/// </summary>
/// <remarks>
/// Can be overridden to add editor-specific logical changes to a <see cref="Ruleset"/>'s standard <see cref="DrawableRuleset{TObject}"/>.
/// For example, hit animations or judgement logic may be changed to give a better editor user experience.
/// </remarks>
/// <param name="ruleset">The ruleset used to construct its drawable counterpart.</param>
/// <param name="beatmap">The loaded beatmap.</param>
/// <param name="mods">The mods to be applied.</param>
/// <returns>An editor-relevant <see cref="DrawableRuleset{TObject}"/>.</returns>
protected virtual DrawableRuleset<TObject> CreateDrawableRuleset(Ruleset ruleset, IBeatmap beatmap, IReadOnlyList<Mod> mods = null)
=> (DrawableRuleset<TObject>)ruleset.CreateDrawableRulesetWith(beatmap, mods);
#region Tool selection logic
protected override bool OnKeyDown(KeyDownEvent e)
{
if (e.ControlPressed || e.AltPressed || e.SuperPressed)
return false;
if (checkLeftToggleFromKey(e.Key, out var leftIndex))
{
var item = toolboxCollection.Items.ElementAtOrDefault(leftIndex);
if (item != null)
{
if (!item.Selected.Disabled)
item.Select();
return true;
}
}
if (checkRightToggleFromKey(e.Key, out var rightIndex))
{
var item = togglesCollection.ElementAtOrDefault(rightIndex);
if (item is DrawableTernaryButton button)
{
button.Button.Toggle();
return true;
}
}
return base.OnKeyDown(e);
}
private bool checkLeftToggleFromKey(Key key, out int index)
{
if (key < Key.Number1 || key > Key.Number9)
{
index = -1;
return false;
}
index = key - Key.Number1;
return true;
}
private bool checkRightToggleFromKey(Key key, out int index)
{
switch (key)
{
case Key.Q:
index = 0;
break;
case Key.W:
index = 1;
break;
case Key.E:
index = 2;
break;
case Key.R:
index = 3;
break;
case Key.T:
index = 4;
break;
case Key.Y:
index = 5;
break;
case Key.U:
index = 6;
break;
case Key.I:
index = 7;
break;
case Key.O:
index = 8;
break;
case Key.P:
index = 9;
break;
default:
index = -1;
break;
}
return index >= 0;
}
private void selectionChanged(object sender, NotifyCollectionChangedEventArgs changedArgs)
{
if (EditorBeatmap.SelectedHitObjects.Any())
{
// ensure in selection mode if a selection is made.
setSelectTool();
}
}
private void setSelectTool() => toolboxCollection.Items.First().Select();
private void toolSelected(HitObjectCompositionTool tool)
{
BlueprintContainer.CurrentTool = tool;
if (!(tool is SelectTool))
EditorBeatmap.SelectedHitObjects.Clear();
}
#endregion
#region IPlacementHandler
public void BeginPlacement(HitObject hitObject)
{
EditorBeatmap.PlacementObject.Value = hitObject;
}
public void EndPlacement(HitObject hitObject, bool commit)
{
EditorBeatmap.PlacementObject.Value = null;
if (commit)
{
EditorBeatmap.Add(hitObject);
if (EditorClock.CurrentTime < hitObject.StartTime)
EditorClock.SeekSmoothlyTo(hitObject.StartTime);
}
}
public void Delete(HitObject hitObject) => EditorBeatmap.Remove(hitObject);
#endregion
#region IPositionSnapProvider
/// <summary>
/// Retrieve the relevant <see cref="Playfield"/> at a specified screen-space position.
/// In cases where a ruleset doesn't require custom logic (due to nested playfields, for example)
/// this will return the ruleset's main playfield.
/// </summary>
/// <param name="screenSpacePosition">The screen-space position to query.</param>
/// <returns>The most relevant <see cref="Playfield"/>.</returns>
protected virtual Playfield PlayfieldAtScreenSpacePosition(Vector2 screenSpacePosition) => drawableRulesetWrapper.Playfield;
public override SnapResult SnapScreenSpacePositionToValidTime(Vector2 screenSpacePosition)
{
var playfield = PlayfieldAtScreenSpacePosition(screenSpacePosition);
double? targetTime = null;
if (playfield is ScrollingPlayfield scrollingPlayfield)
{
targetTime = scrollingPlayfield.TimeAtScreenSpacePosition(screenSpacePosition);
// apply beat snapping
targetTime = BeatSnapProvider.SnapTime(targetTime.Value);
// convert back to screen space
screenSpacePosition = scrollingPlayfield.ScreenSpacePositionAtTime(targetTime.Value);
}
return new SnapResult(screenSpacePosition, targetTime, playfield);
}
public override float GetBeatSnapDistanceAt(HitObject referenceObject)
{
return (float)(100 * EditorBeatmap.Difficulty.SliderMultiplier * referenceObject.DifficultyControlPoint.SliderVelocity / BeatSnapProvider.BeatDivisor);
}
public override float DurationToDistance(HitObject referenceObject, double duration)
{
double beatLength = BeatSnapProvider.GetBeatLengthAtTime(referenceObject.StartTime);
return (float)(duration / beatLength * GetBeatSnapDistanceAt(referenceObject));
}
public override double DistanceToDuration(HitObject referenceObject, float distance)
{
double beatLength = BeatSnapProvider.GetBeatLengthAtTime(referenceObject.StartTime);
return distance / GetBeatSnapDistanceAt(referenceObject) * beatLength;
}
public override double GetSnappedDurationFromDistance(HitObject referenceObject, float distance)
=> BeatSnapProvider.SnapTime(referenceObject.StartTime + DistanceToDuration(referenceObject, distance), referenceObject.StartTime) - referenceObject.StartTime;
public override float GetSnappedDistanceFromDistance(HitObject referenceObject, float distance)
{
double startTime = referenceObject.StartTime;
double actualDuration = startTime + DistanceToDuration(referenceObject, distance);
double snappedEndTime = BeatSnapProvider.SnapTime(actualDuration, startTime);
double beatLength = BeatSnapProvider.GetBeatLengthAtTime(startTime);
// we don't want to exceed the actual duration and snap to a point in the future.
// as we are snapping to beat length via SnapTime (which will round-to-nearest), check for snapping in the forward direction and reverse it.
if (snappedEndTime > actualDuration + 1)
snappedEndTime -= beatLength;
return DurationToDistance(referenceObject, snappedEndTime - startTime);
}
#endregion
}
/// <summary>
/// A non-generic definition of a HitObject composer class.
/// Generally used to access certain methods without requiring a generic type for <see cref="HitObjectComposer{T}" />.
/// </summary>
[Cached(typeof(HitObjectComposer))]
[Cached(typeof(IPositionSnapProvider))]
public abstract class HitObjectComposer : CompositeDrawable, IPositionSnapProvider
{
protected HitObjectComposer()
{
RelativeSizeAxes = Axes.Both;
}
/// <summary>
/// The target ruleset's playfield.
/// </summary>
public abstract Playfield Playfield { get; }
/// <summary>
/// All <see cref="DrawableHitObject"/>s in currently loaded beatmap.
/// </summary>
public abstract IEnumerable<DrawableHitObject> HitObjects { get; }
/// <summary>
/// Whether the user's cursor is currently in an area of the <see cref="HitObjectComposer"/> that is valid for placement.
/// </summary>
public abstract bool CursorInPlacementArea { get; }
public virtual string ConvertSelectionToString() => string.Empty;
#region IPositionSnapProvider
public abstract SnapResult SnapScreenSpacePositionToValidTime(Vector2 screenSpacePosition);
public virtual SnapResult SnapScreenSpacePositionToValidPosition(Vector2 screenSpacePosition) =>
new SnapResult(screenSpacePosition, null);
public abstract float GetBeatSnapDistanceAt(HitObject referenceObject);
public abstract float DurationToDistance(HitObject referenceObject, double duration);
public abstract double DistanceToDuration(HitObject referenceObject, float distance);
public abstract double GetSnappedDurationFromDistance(HitObject referenceObject, float distance);
public abstract float GetSnappedDistanceFromDistance(HitObject referenceObject, float distance);
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
#if (WINDOWS && !NETFX_CORE)
using BitMiracle.LibTiff.Classic;
#endif
namespace CocosSharp
{
#region Enums and structs
public enum CCImageFormat
{
Jpg = 0,
Png,
Tiff,
Webp,
Gif,
RawData,
UnKnown
}
public enum CCSurfaceFormat
{
Color = 0,
Bgr565 = 1,
Bgra5551 = 2,
Bgra4444 = 3,
Dxt1 = 4,
Dxt3 = 5,
Dxt5 = 6,
NormalizedByte2 = 7,
NormalizedByte4 = 8,
Rgba1010102 = 9,
Rg32 = 10,
Rgba64 = 11,
Alpha8 = 12,
Single = 13,
CCVector2 = 14,
Vector4 = 15,
HalfSingle = 16,
HalfCCVector2 = 17,
HalfVector4 = 18,
HdrBlendable = 19,
// BGRA formats are required for compatibility with WPF D3DImage.
Bgr32 = 20, // B8G8R8X8
Bgra32 = 21, // B8G8R8A8
// Good explanation of compressed formats for mobile devices (aimed at Android, but describes PVRTC)
// http://developer.motorola.com/docstools/library/understanding-texture-compression/
// PowerVR texture compression (iOS and Android)
RgbPvrtc2Bpp = 50,
RgbPvrtc4Bpp = 51,
RgbaPvrtc2Bpp = 52,
RgbaPvrtc4Bpp = 53,
// Ericcson Texture Compression (Android)
RgbEtc1 = 60,
// DXT1 also has a 1-bit alpha form
Dxt1a = 70,
}
internal enum CCTextureCacheType
{
None,
AssetFile,
Data,
RawData,
String
}
internal struct CCStringCache
{
public String Text;
public CCSize Dimensions;
public CCTextAlignment HAlignment;
public CCVerticalTextAlignment VAlignment;
public String FontName;
public float FontSize;
}
internal struct CCTextureCacheInfo
{
public CCTextureCacheType CacheType;
public Object Data;
}
#endregion Enums and structs
public class CCTexture2D : CCGraphicsResource
{
public static CCSurfaceFormat DefaultAlphaPixelFormat = CCSurfaceFormat.Color;
public static bool OptimizeForPremultipliedAlpha = true;
public static bool DefaultIsAntialiased = true;
bool hasMipmaps;
bool managed;
bool antialiased;
CCTextureCacheInfo cacheInfo;
Texture2D texture2D;
private readonly int textureId = Interlocked.Increment(ref lastTextureId);
private static int lastTextureId;
#region Properties
/// <summary>
/// Gets a unique identifier of this texture for batch rendering purposes.
/// </summary>
/// <remarks>
/// <para>For example, this value is used by <see cref="CCRenderer"/> when determining batch rendering.</para>
/// <para>The value is an implementation detail and may change between application launches or CocosSharp versions.
/// It is only guaranteed to stay consistent during application lifetime.</para>
/// </remarks>
internal int TextureId { get { return textureId; } }
public bool HasPremultipliedAlpha { get; private set; }
public int PixelsWide { get; private set; }
public int PixelsHigh { get; private set; }
public CCSize ContentSizeInPixels { get; private set; }
public CCSurfaceFormat PixelFormat { get; set; }
public SamplerState SamplerState { get; set; }
public bool IsTextureDefined
{
get { return (texture2D != null && !texture2D.IsDisposed); }
}
public bool IsAntialiased
{
get { return antialiased; }
set
{
if (antialiased != value)
{
antialiased = value;
RefreshAntialiasSetting();
}
}
}
public uint BitsPerPixelForFormat
{
//from MG: Microsoft.Xna.Framework.Graphics.GraphicsExtensions
get
{
switch (PixelFormat)
{
case CCSurfaceFormat.Dxt1:
#if !WINDOWS && !WINDOWS_PHONE
case CCSurfaceFormat.Dxt1a:
case CCSurfaceFormat.RgbPvrtc2Bpp:
case CCSurfaceFormat.RgbaPvrtc2Bpp:
case CCSurfaceFormat.RgbEtc1:
#endif
// One texel in DXT1, PVRTC 2bpp and ETC1 is a minimum 4x4 block, which is 8 bytes
return 8;
case CCSurfaceFormat.Dxt3:
case CCSurfaceFormat.Dxt5:
#if !WINDOWS && !WINDOWS_PHONE
case CCSurfaceFormat.RgbPvrtc4Bpp:
case CCSurfaceFormat.RgbaPvrtc4Bpp:
#endif
// One texel in DXT3, DXT5 and PVRTC 4bpp is a minimum 4x4 block, which is 16 bytes
return 16;
case CCSurfaceFormat.Alpha8:
return 1;
case CCSurfaceFormat.Bgr565:
case CCSurfaceFormat.Bgra4444:
case CCSurfaceFormat.Bgra5551:
case CCSurfaceFormat.HalfSingle:
case CCSurfaceFormat.NormalizedByte2:
return 2;
case CCSurfaceFormat.Color:
case CCSurfaceFormat.Single:
case CCSurfaceFormat.Rg32:
case CCSurfaceFormat.HalfCCVector2:
case CCSurfaceFormat.NormalizedByte4:
case CCSurfaceFormat.Rgba1010102:
return 4;
case CCSurfaceFormat.HalfVector4:
case CCSurfaceFormat.Rgba64:
case CCSurfaceFormat.CCVector2:
return 8;
case CCSurfaceFormat.Vector4:
return 16;
default:
throw new NotImplementedException();
}
}
}
public Texture2D Name
{
get { return XNATexture; }
}
public Texture2D XNATexture
{
get
{
if (texture2D != null && texture2D.IsDisposed)
{
ReinitResource();
}
return texture2D;
}
}
#endregion Properties
#region Constructors and initialization
public CCTexture2D()
{
SamplerState = SamplerState.LinearClamp;
IsAntialiased = DefaultIsAntialiased;
RefreshAntialiasSetting();
}
public CCTexture2D (int pixelsWide, int pixelsHigh, CCSurfaceFormat pixelFormat=CCSurfaceFormat.Color, bool premultipliedAlpha=true, bool mipMap=false)
: this(new Texture2D(CCDrawManager.SharedDrawManager.XnaGraphicsDevice, pixelsWide, pixelsHigh, mipMap, (SurfaceFormat)pixelFormat), pixelFormat, premultipliedAlpha)
{
cacheInfo.CacheType = CCTextureCacheType.None;
cacheInfo.Data = null;
}
public CCTexture2D(byte[] data, CCSurfaceFormat pixelFormat=CCSurfaceFormat.Color, bool mipMap=false)
: this()
{
InitWithData(data, pixelFormat, mipMap);
}
public CCTexture2D(Stream stream, CCSurfaceFormat pixelFormat=CCSurfaceFormat.Color)
: this()
{
InitWithStream(stream, pixelFormat);
}
public CCTexture2D(string text, CCSize dimensions, CCTextAlignment hAlignment,
CCVerticalTextAlignment vAlignment, string fontName, float fontSize)
: this()
{
InitWithString(text, dimensions, hAlignment, vAlignment, fontName, fontSize);
}
public CCTexture2D(string text, string fontName, float fontSize)
: this(text, CCSize.Zero, CCTextAlignment.Center, CCVerticalTextAlignment.Top, fontName, fontSize)
{
}
public CCTexture2D(string file)
: this()
{
InitWithFile(file);
}
public CCTexture2D(Texture2D texture, CCSurfaceFormat format, bool premultipliedAlpha=true, bool managed=false)
: this()
{
InitWithTexture(texture, format, premultipliedAlpha, managed);
}
public CCTexture2D(Texture2D texture)
: this(texture, (CCSurfaceFormat)texture.Format)
{
}
internal void InitWithRawData<T>(T[] data, CCSurfaceFormat pixelFormat, int pixelsWide, int pixelsHigh, bool premultipliedAlpha, bool mipMap)
where T : struct
{
InitWithRawData(data, pixelFormat, pixelsWide, pixelsHigh, premultipliedAlpha, mipMap, new CCSize(pixelsWide, pixelsHigh));
}
internal void InitWithRawData<T>(T[] data, CCSurfaceFormat pixelFormat, int pixelsWide, int pixelsHigh,
bool premultipliedAlpha, bool mipMap, CCSize ContentSizeInPixelsIn) where T : struct
{
var texture = LoadRawData(data, pixelsWide, pixelsHigh, (SurfaceFormat)pixelFormat, mipMap);
InitWithTexture(texture, pixelFormat, premultipliedAlpha, false);
ContentSizeInPixels = ContentSizeInPixelsIn;
cacheInfo.CacheType = CCTextureCacheType.RawData;
cacheInfo.Data = data;
}
void InitWithData(byte[] data, CCSurfaceFormat pixelFormat, bool mipMap)
{
if (data == null)
{
return;
}
#if WINDOWS_PHONE8
/*
byte[] cloneOfData = new byte[data.Length];
data.CopyTo(cloneOfData, 0);
data = cloneOfData;
*/
#endif
var texture = LoadTexture(new MemoryStream(data, false));
if (texture != null)
{
InitWithTexture(texture, pixelFormat, true, false);
cacheInfo.CacheType = CCTextureCacheType.Data;
cacheInfo.Data = data;
if (mipMap)
{
GenerateMipmap();
}
}
}
void InitWithStream(Stream stream, CCSurfaceFormat pixelFormat)
{
Texture2D texture;
try
{
texture = LoadTexture(stream);
InitWithTexture(texture, pixelFormat, false, false);
return;
}
catch (Exception)
{
}
}
void InitWithFile(string file)
{
managed = false;
Texture2D texture = null;
cacheInfo.CacheType = CCTextureCacheType.AssetFile;
cacheInfo.Data = file;
//TODO: may be move this functional to CCContentManager?
var contentManager = CCContentManager.SharedContentManager;
var loadedFile = file;
// first try to download xnb
if (Path.HasExtension(loadedFile))
{
loadedFile = Path.Combine(Path.GetDirectoryName(file), Path.GetFileNameWithoutExtension(file));
}
// use WeakReference. Link for regular textures are stored in CCTextureCache
texture = contentManager.TryLoad<Texture2D>(loadedFile, true);
if (texture != null)
{
// usually xnb texture prepared as PremultipliedAlpha
InitWithTexture(texture, DefaultAlphaPixelFormat, true, true);
return;
}
// try load raw image
if (loadedFile != file)
{
texture = contentManager.TryLoad<Texture2D>(file, true);
if (texture != null)
{
// not premultiplied alpha
InitWithTexture(texture, DefaultAlphaPixelFormat, false, true);
return;
}
}
// try load not supported format (for example tga)
try
{
using (var stream = contentManager.GetAssetStream(file))
{
InitWithStream(stream, DefaultAlphaPixelFormat);
}
}
catch (Exception)
{
}
CCLog.Log("Texture {0} was not found.", file);
}
void InitWithString(string text, CCSize dimensions, CCTextAlignment hAlignment, CCVerticalTextAlignment vAlignment, string fontName, float fontSize)
{
try
{
Debug.Assert(dimensions.Width >= 0 || dimensions.Height >= 0);
if (string.IsNullOrEmpty(text))
{
return;
}
float loadedSize = fontSize;
SpriteFont font = CCSpriteFontCache.SharedInstance.TryLoadFont(fontName, fontSize, out loadedSize);
if (font == null)
{
CCLog.Log("Failed to load default font. No font supported.");
return;
}
float scale = 1f;
if (loadedSize != 0)
{
scale = fontSize / loadedSize * CCSpriteFontCache.FontScale;
}
if (dimensions.Equals(CCSize.Zero))
{
CCVector2 temp = font.MeasureString(text).ToCCVector2();
dimensions.Width = temp.X * scale;
dimensions.Height = temp.Y * scale;
}
var textList = new List<String>();
var nextText = new StringBuilder();
string[] lineList = text.Split('\n');
float spaceWidth = font.MeasureString(" ").X * scale;
for (int j = 0; j < lineList.Length; ++j)
{
string[] wordList = lineList[j].Split(' ');
float lineWidth = 0;
bool firstWord = true;
for (int i = 0; i < wordList.Length; ++i)
{
float wordWidth = font.MeasureString(wordList[i]).X * scale;
if ((lineWidth + wordWidth) > dimensions.Width)
{
lineWidth = wordWidth;
if (nextText.Length > 0)
{
firstWord = true;
textList.Add(nextText.ToString());
nextText.Length = 0;
}
else
{
lineWidth += wordWidth;
firstWord = false;
textList.Add(wordList[i]);
continue;
}
}
else
{
lineWidth += wordWidth;
}
if (!firstWord)
{
nextText.Append(' ');
lineWidth += spaceWidth;
}
nextText.Append(wordList[i]);
firstWord = false;
}
textList.Add(nextText.ToString());
nextText.Clear();
}
if (dimensions.Height == 0)
{
dimensions.Height = textList.Count * font.LineSpacing * scale;
}
//* for render to texture
RenderTarget2D renderTarget = CCDrawManager.SharedDrawManager.CreateRenderTarget(
(int)dimensions.Width, (int)dimensions.Height,
DefaultAlphaPixelFormat, CCRenderTargetUsage.DiscardContents
);
CCDrawManager.SharedDrawManager.CurrentRenderTarget = renderTarget;
CCDrawManager.SharedDrawManager.Clear(CCColor4B.Transparent);
SpriteBatch sb = CCDrawManager.SharedDrawManager.SpriteBatch;
sb.Begin();
float textHeight = textList.Count * font.LineSpacing * scale;
float nextY = 0;
if (vAlignment == CCVerticalTextAlignment.Bottom)
{
nextY = dimensions.Height - textHeight;
}
else if (vAlignment == CCVerticalTextAlignment.Center)
{
nextY = (dimensions.Height - textHeight) / 2.0f;
}
for (int j = 0; j < textList.Count; ++j)
{
string line = textList[j];
var position = new CCVector2(0, nextY);
if (hAlignment == CCTextAlignment.Right)
{
position.X = dimensions.Width - font.MeasureString(line).X * scale;
}
else if (hAlignment == CCTextAlignment.Center)
{
position.X = (dimensions.Width - font.MeasureString(line).X * scale) / 2.0f;
}
sb.DrawString(font, line, position.ToVector2(), Color.White, 0f, Vector2.Zero, scale, SpriteEffects.None, 0);
nextY += font.LineSpacing * scale;
}
sb.End();
CCDrawManager.SharedDrawManager.XnaGraphicsDevice.RasterizerState = RasterizerState.CullNone;
CCDrawManager.SharedDrawManager.DepthStencilState = DepthStencilState.Default;
CCDrawManager.SharedDrawManager.CurrentRenderTarget = (RenderTarget2D)null;
InitWithTexture(renderTarget, (CCSurfaceFormat)renderTarget.Format, true, false);
cacheInfo.CacheType = CCTextureCacheType.String;
cacheInfo.Data = new CCStringCache()
{
Dimensions = dimensions,
Text = text,
FontName = fontName,
FontSize = fontSize,
HAlignment = hAlignment,
VAlignment = vAlignment
};
}
catch (Exception ex)
{
CCLog.Log(ex.ToString());
}
}
// Method called externally by CCDrawManager
internal void InitWithTexture(Texture2D texture, CCSurfaceFormat format, bool premultipliedAlpha, bool managedIn)
{
managed = managedIn;
if (null == texture)
{
return;
}
if (OptimizeForPremultipliedAlpha && !premultipliedAlpha)
{
texture2D = ConvertToPremultiplied(texture, (SurfaceFormat)format);
if (!managed)
{
texture.Dispose();
managed = false;
}
}
else
{
if (texture.Format != (SurfaceFormat)format)
{
texture2D = ConvertSurfaceFormat(texture, (SurfaceFormat)format);
if (!managed)
{
texture.Dispose();
managed = false;
}
}
else
{
texture2D = texture;
}
}
PixelFormat = (CCSurfaceFormat)texture.Format;
PixelsWide = texture.Width;
PixelsHigh = texture.Height;
ContentSizeInPixels = new CCSize(texture.Width, texture.Height);
hasMipmaps = texture.LevelCount > 1;
HasPremultipliedAlpha = premultipliedAlpha;
}
public override void ReinitResource()
{
//CCLog.Log("reinit called on texture '{0}' {1}x{2}", Name, ContentSizeInPixels.Width, ContentSizeInPixels.Height);
Texture2D textureToDispose = null;
if (texture2D != null && !texture2D.IsDisposed && !managed)
{
textureToDispose = texture2D;
// texture2D.Dispose();
}
managed = false;
texture2D = null;
switch (cacheInfo.CacheType)
{
case CCTextureCacheType.None:
return;
case CCTextureCacheType.AssetFile:
InitWithFile((string)cacheInfo.Data);
break;
case CCTextureCacheType.Data:
InitWithData((byte[])cacheInfo.Data, (CCSurfaceFormat)PixelFormat, hasMipmaps);
break;
case CCTextureCacheType.RawData:
#if NETFX_CORE
var methodInfo = typeof(CCTexture2D).GetType().GetTypeInfo().GetDeclaredMethod("InitWithRawData");
#else
var methodInfo = typeof(CCTexture2D).GetMethod("InitWithRawData", BindingFlags.Public | BindingFlags.Instance);
#endif
var genericMethod = methodInfo.MakeGenericMethod(cacheInfo.Data.GetType());
genericMethod.Invoke(this, new object[]
{
Convert.ChangeType(cacheInfo.Data, cacheInfo.Data.GetType(),System.Globalization.CultureInfo.InvariantCulture),
PixelFormat, PixelsWide, PixelsHigh,
HasPremultipliedAlpha, hasMipmaps, ContentSizeInPixels
});
// InitWithRawData((byte[])cacheInfo.Data, PixelFormat, PixelsWide, PixelsHigh,
// HasPremultipliedAlpha, hasMipmaps, ContentSizeInPixels);
break;
case CCTextureCacheType.String:
var si = (CCStringCache)cacheInfo.Data;
InitWithString(si.Text, si.Dimensions, si.HAlignment, si.VAlignment, si.FontName, si.FontSize);
if (hasMipmaps)
{
hasMipmaps = false;
GenerateMipmap();
}
break;
default:
throw new ArgumentOutOfRangeException();
}
if (textureToDispose != null && !textureToDispose.IsDisposed)
{
textureToDispose.Dispose();
}
}
#endregion Constructors and initialization
public override string ToString()
{
return String.Format("<CCTexture2D | Dimensions = {0} x {1})>", PixelsWide, PixelsHigh);
}
#region Cleanup
void RefreshAntialiasSetting()
{
var saveState = SamplerState;
if (antialiased && SamplerState.Filter != TextureFilter.Linear)
{
if (SamplerState == SamplerState.PointClamp)
{
SamplerState = SamplerState.LinearClamp;
return;
}
SamplerState = new SamplerState
{
Filter = TextureFilter.Linear
};
}
else if (!antialiased && SamplerState.Filter != TextureFilter.Point)
{
if (SamplerState == SamplerState.LinearClamp)
{
SamplerState = SamplerState.PointClamp;
return;
}
SamplerState = new SamplerState
{
Filter = TextureFilter.Point
};
}
else
{
return;
}
SamplerState.AddressU = saveState.AddressU;
SamplerState.AddressV = saveState.AddressV;
SamplerState.AddressW = saveState.AddressW;
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing && texture2D != null && !texture2D.IsDisposed && !managed)
{
texture2D.Dispose();
}
texture2D = null;
}
#endregion Cleanup
#region Saving texture
public void SaveAsJpeg(Stream stream, int width, int height)
{
if (texture2D != null)
{
texture2D.SaveAsJpeg(stream, width, height);
}
}
public void SaveAsPng(Stream stream, int width, int height)
{
if (texture2D != null)
{
texture2D.SaveAsPng(stream, width, height);
}
}
#endregion Saving texture
#region Conversion
public void GenerateMipmap()
{
if (!hasMipmaps)
{
var target = new RenderTarget2D(CCDrawManager.SharedDrawManager.XnaGraphicsDevice, PixelsWide, PixelsHigh, true, (SurfaceFormat)PixelFormat,
DepthFormat.None, 0, RenderTargetUsage.DiscardContents);
CCDrawManager.SharedDrawManager.CurrentRenderTarget = target;
SpriteBatch sb = CCDrawManager.SharedDrawManager.SpriteBatch;
sb.Begin();
sb.Draw(texture2D, Vector2.Zero, Color.White);
sb.End();
if (!managed)
{
texture2D.Dispose();
}
managed = false;
texture2D = target;
hasMipmaps = true;
}
}
Texture2D ConvertSurfaceFormat(Texture2D texture, SurfaceFormat format)
{
if (texture.Format == format)
{
return texture;
}
var renderTarget = new RenderTarget2D(
CCDrawManager.SharedDrawManager.XnaGraphicsDevice,
texture.Width, texture.Height, hasMipmaps, format,
DepthFormat.None, 0, RenderTargetUsage.DiscardContents
);
CCDrawManager.SharedDrawManager.CurrentRenderTarget = renderTarget;
CCDrawManager.SharedDrawManager.SpriteBatch.Begin();
CCDrawManager.SharedDrawManager.SpriteBatch.Draw(texture, Vector2.Zero, Color.White);
CCDrawManager.SharedDrawManager.SpriteBatch.End();
CCDrawManager.SharedDrawManager.SetRenderTarget((CCTexture2D)null);
return renderTarget;
}
Texture2D ConvertToPremultiplied(Texture2D texture, SurfaceFormat format)
{
//Jake Poznanski - Speeding up XNA Content Load
//http://jakepoz.com/jake_poznanski__speeding_up_xna.html
//Setup a render target to hold our final texture which will have premulitplied alpha values
var result = new RenderTarget2D(
CCDrawManager.SharedDrawManager.XnaGraphicsDevice,
texture.Width, texture.Height, hasMipmaps, format,
DepthFormat.None, 0, RenderTargetUsage.DiscardContents
);
CCDrawManager.SharedDrawManager.CurrentRenderTarget = result;
CCDrawManager.SharedDrawManager.Clear(CCColor4B.Transparent);
var spriteBatch = CCDrawManager.SharedDrawManager.SpriteBatch;
if (format != SurfaceFormat.Alpha8)
{
//Multiply each color by the source alpha, and write in just the color values into the final texture
var blendColor = new BlendState();
blendColor.ColorWriteChannels = ColorWriteChannels.Red | ColorWriteChannels.Green |
ColorWriteChannels.Blue;
blendColor.AlphaDestinationBlend = Blend.Zero;
blendColor.ColorDestinationBlend = Blend.Zero;
blendColor.AlphaSourceBlend = Blend.SourceAlpha;
blendColor.ColorSourceBlend = Blend.SourceAlpha;
spriteBatch.Begin(SpriteSortMode.Immediate, blendColor);
spriteBatch.Draw(texture, texture.Bounds, Color.White);
spriteBatch.End();
}
//Now copy over the alpha values from the PNG source texture to the final one, without multiplying them
var blendAlpha = new BlendState();
blendAlpha.ColorWriteChannels = ColorWriteChannels.Alpha;
blendAlpha.AlphaDestinationBlend = Blend.Zero;
blendAlpha.ColorDestinationBlend = Blend.Zero;
blendAlpha.AlphaSourceBlend = Blend.One;
blendAlpha.ColorSourceBlend = Blend.One;
spriteBatch.Begin(SpriteSortMode.Immediate, blendAlpha);
spriteBatch.Draw(texture, texture.Bounds, Color.White);
spriteBatch.End();
//Release the GPU back to drawing to the screen
CCDrawManager.SharedDrawManager.SetRenderTarget((CCTexture2D) null);
return result;
}
#endregion Conversion
#region Loading Texture
public static CCImageFormat DetectImageFormat(Stream stream)
{
var data = new byte[8];
var pos = stream.Position;
var dataLen = stream.Read(data, 0, 8);
stream.Position = pos;
if (dataLen >= 8)
{
if (data[0] == 0x89 && data[1] == 0x50 && data[2] == 0x4E && data[3] == 0x47
&& data[4] == 0x0D && data[5] == 0x0A && data[6] == 0x1A && data[7] == 0x0A)
{
return CCImageFormat.Png;
}
}
if (dataLen >= 3)
{
if (data[0] == 0x47 && data[1] == 0x49 && data[1] == 0x46)
{
return CCImageFormat.Gif;
}
}
if (dataLen >= 2)
{
if ((data[0] == 0x49 && data[1] == 0x49) || (data[0] == 0x4d && data[1] == 0x4d))
{
return CCImageFormat.Tiff;
}
}
if (dataLen >= 2)
{
if (data[0] == 0xff && data[1] == 0xd8)
{
return CCImageFormat.Jpg;
}
}
return CCImageFormat.UnKnown;
}
Texture2D LoadTexture(Stream stream)
{
return LoadTexture(stream, CCImageFormat.UnKnown);
}
Texture2D LoadRawData<T>(T[] data, int width, int height, SurfaceFormat pixelFormat, bool mipMap) where T : struct
{
var result = new Texture2D(CCDrawManager.SharedDrawManager.XnaGraphicsDevice, width, height, mipMap, pixelFormat);
result.SetData(data);
return result;
}
Texture2D LoadTexture(Stream stream, CCImageFormat imageFormat)
{
Texture2D result = null;
if (imageFormat == CCImageFormat.UnKnown)
{
imageFormat = DetectImageFormat(stream);
}
if (imageFormat == CCImageFormat.Tiff)
{
result = LoadTextureFromTiff(stream);
}
if (imageFormat == CCImageFormat.Jpg || imageFormat == CCImageFormat.Png || imageFormat == CCImageFormat.Gif)
{
try
{
result = Texture2D.FromStream(CCDrawManager.SharedDrawManager.XnaGraphicsDevice, stream);
}
catch (Exception)
{
// Some platforms do not implement FromStream or do not support the format that may be passed.
CCLog.Log("CocosSharp: unable to load texture from stream.");
}
}
return result;
}
Texture2D LoadTextureFromTiff(Stream stream)
{
#if (WINDOWS && !NETFX_CORE)
using (var tiff = Tiff.ClientOpen("file.tif", "r", stream, new TiffStream()))
{
var w = tiff.GetField(TiffTag.IMAGEWIDTH)[0].ToInt();
var h = tiff.GetField(TiffTag.IMAGELENGTH)[0].ToInt();
var raster = new int[w * h];
if (tiff.ReadRGBAImageOriented(w, h, raster, Orientation.LEFTTOP))
{
var result = new Texture2D(CCDrawManager.SharedDrawManager.XnaGraphicsDevice, w, h, false, SurfaceFormat.Color);
result.SetData(raster);
return result;
}
else
{
return null;
}
}
#elif MACOS || IOS
return Texture2D.FromStream(CCDrawManager.SharedDrawManager.XnaGraphicsDevice, stream);
#else
return null;
#endif
}
#endregion Loading Texture
}
}
| |
// 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.IO;
using System.Linq;
using System.Text;
using EnvDTE;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Feedback.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Extensions;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.TextManager.Interop;
using Roslyn.Utilities;
using Roslyn.VisualStudio.ProjectSystem;
using VSLangProj;
using VSLangProj140;
using OLEServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
{
/// <summary>
/// The Workspace for running inside Visual Studio.
/// </summary>
internal abstract class VisualStudioWorkspaceImpl : VisualStudioWorkspace
{
private static readonly IntPtr s_docDataExisting_Unknown = new IntPtr(-1);
private const string AppCodeFolderName = "App_Code";
protected readonly IServiceProvider ServiceProvider;
private readonly IVsUIShellOpenDocument _shellOpenDocument;
private readonly IVsTextManager _textManager;
// Not readonly because it needs to be set in the derived class' constructor.
private VisualStudioProjectTracker _projectTracker;
// document worker coordinator
private ISolutionCrawlerRegistrationService _registrationService;
private readonly ForegroundThreadAffinitizedObject _foregroundObject = new ForegroundThreadAffinitizedObject();
public VisualStudioWorkspaceImpl(
SVsServiceProvider serviceProvider,
WorkspaceBackgroundWork backgroundWork)
: base(
CreateHostServices(serviceProvider),
backgroundWork)
{
this.ServiceProvider = serviceProvider;
_textManager = serviceProvider.GetService(typeof(SVsTextManager)) as IVsTextManager;
_shellOpenDocument = serviceProvider.GetService(typeof(SVsUIShellOpenDocument)) as IVsUIShellOpenDocument;
// Ensure the options factory services are initialized on the UI thread
this.Services.GetService<IOptionService>();
var session = serviceProvider.GetService(typeof(SVsLog)) as IVsSqmMulti;
var profileService = serviceProvider.GetService(typeof(SVsFeedbackProfile)) as IVsFeedbackProfile;
// We have Watson hits where this came back null, so guard against it
if (profileService != null)
{
Sqm.LogSession(session, profileService.IsMicrosoftInternal);
}
}
internal static HostServices CreateHostServices(SVsServiceProvider serviceProvider)
{
var composition = (IComponentModel)serviceProvider.GetService(typeof(SComponentModel));
return MefV1HostServices.Create(composition.DefaultExportProvider);
}
protected void InitializeStandardVisualStudioWorkspace(SVsServiceProvider serviceProvider, SaveEventsService saveEventsService)
{
var projectTracker = new VisualStudioProjectTracker(serviceProvider);
// Ensure the document tracking service is initialized on the UI thread
var documentTrackingService = this.Services.GetService<IDocumentTrackingService>();
var documentProvider = new RoslynDocumentProvider(projectTracker, serviceProvider, documentTrackingService);
projectTracker.DocumentProvider = documentProvider;
projectTracker.MetadataReferenceProvider = this.Services.GetService<VisualStudioMetadataReferenceManager>();
projectTracker.RuleSetFileProvider = this.Services.GetService<VisualStudioRuleSetManager>();
this.SetProjectTracker(projectTracker);
var workspaceHost = new VisualStudioWorkspaceHost(this);
projectTracker.RegisterWorkspaceHost(workspaceHost);
projectTracker.StartSendingEventsToWorkspaceHost(workspaceHost);
saveEventsService.StartSendingSaveEvents();
// Ensure the options factory services are initialized on the UI thread
this.Services.GetService<IOptionService>();
}
/// <summary>NOTE: Call only from derived class constructor</summary>
protected void SetProjectTracker(VisualStudioProjectTracker projectTracker)
{
_projectTracker = projectTracker;
}
internal VisualStudioProjectTracker ProjectTracker
{
get
{
return _projectTracker;
}
}
internal void ClearReferenceCache()
{
_projectTracker.MetadataReferenceProvider.ClearCache();
}
internal IVisualStudioHostDocument GetHostDocument(DocumentId documentId)
{
var project = GetHostProject(documentId.ProjectId);
if (project != null)
{
return project.GetDocumentOrAdditionalDocument(documentId);
}
return null;
}
internal IVisualStudioHostProject GetHostProject(ProjectId projectId)
{
return this.ProjectTracker.GetProject(projectId);
}
private bool TryGetHostProject(ProjectId projectId, out IVisualStudioHostProject project)
{
project = GetHostProject(projectId);
return project != null;
}
public override bool TryApplyChanges(Microsoft.CodeAnalysis.Solution newSolution)
{
// first make sure we can edit the document we will be updating (check them out from source control, etc)
var changedDocs = newSolution.GetChanges(this.CurrentSolution).GetProjectChanges().SelectMany(pd => pd.GetChangedDocuments()).ToList();
if (changedDocs.Count > 0)
{
this.EnsureEditableDocuments(changedDocs);
}
return base.TryApplyChanges(newSolution);
}
public override bool CanOpenDocuments
{
get
{
return true;
}
}
internal override bool CanChangeActiveContextDocument
{
get
{
return true;
}
}
public override bool CanApplyChange(ApplyChangesKind feature)
{
switch (feature)
{
case ApplyChangesKind.AddDocument:
case ApplyChangesKind.RemoveDocument:
case ApplyChangesKind.ChangeDocument:
case ApplyChangesKind.AddMetadataReference:
case ApplyChangesKind.RemoveMetadataReference:
case ApplyChangesKind.AddProjectReference:
case ApplyChangesKind.RemoveProjectReference:
case ApplyChangesKind.AddAnalyzerReference:
case ApplyChangesKind.RemoveAnalyzerReference:
case ApplyChangesKind.AddAdditionalDocument:
case ApplyChangesKind.RemoveAdditionalDocument:
case ApplyChangesKind.ChangeAdditionalDocument:
return true;
default:
return false;
}
}
private bool TryGetProjectData(ProjectId projectId, out IVisualStudioHostProject hostProject, out IVsHierarchy hierarchy, out EnvDTE.Project project)
{
hierarchy = null;
project = null;
return this.TryGetHostProject(projectId, out hostProject)
&& this.TryGetHierarchy(projectId, out hierarchy)
&& hierarchy.TryGetProject(out project);
}
internal void GetProjectData(ProjectId projectId, out IVisualStudioHostProject hostProject, out IVsHierarchy hierarchy, out EnvDTE.Project project)
{
if (!TryGetProjectData(projectId, out hostProject, out hierarchy, out project))
{
throw new ArgumentException(string.Format(ServicesVSResources.CouldNotFindProject, projectId));
}
}
internal bool TryAddReferenceToProject(ProjectId projectId, string assemblyName)
{
IVisualStudioHostProject hostProject;
IVsHierarchy hierarchy;
EnvDTE.Project project;
try
{
GetProjectData(projectId, out hostProject, out hierarchy, out project);
}
catch (ArgumentException)
{
return false;
}
var vsProject = (VSProject)project.Object;
try
{
vsProject.References.Add(assemblyName);
}
catch (Exception)
{
return false;
}
return true;
}
private string GetAnalyzerPath(AnalyzerReference analyzerReference)
{
return analyzerReference.FullPath;
}
protected override void ApplyAnalyzerReferenceAdded(ProjectId projectId, AnalyzerReference analyzerReference)
{
if (projectId == null)
{
throw new ArgumentNullException(nameof(projectId));
}
if (analyzerReference == null)
{
throw new ArgumentNullException(nameof(analyzerReference));
}
IVisualStudioHostProject hostProject;
IVsHierarchy hierarchy;
EnvDTE.Project project;
GetProjectData(projectId, out hostProject, out hierarchy, out project);
string filePath = GetAnalyzerPath(analyzerReference);
if (filePath != null)
{
VSProject3 vsProject = (VSProject3)project.Object;
vsProject.AnalyzerReferences.Add(filePath);
}
}
protected override void ApplyAnalyzerReferenceRemoved(ProjectId projectId, AnalyzerReference analyzerReference)
{
if (projectId == null)
{
throw new ArgumentNullException(nameof(projectId));
}
if (analyzerReference == null)
{
throw new ArgumentNullException(nameof(analyzerReference));
}
IVisualStudioHostProject hostProject;
IVsHierarchy hierarchy;
EnvDTE.Project project;
GetProjectData(projectId, out hostProject, out hierarchy, out project);
string filePath = GetAnalyzerPath(analyzerReference);
if (filePath != null)
{
VSProject3 vsProject = (VSProject3)project.Object;
vsProject.AnalyzerReferences.Remove(filePath);
}
}
private string GetMetadataPath(MetadataReference metadataReference)
{
var fileMetadata = metadataReference as PortableExecutableReference;
if (fileMetadata != null)
{
return fileMetadata.FilePath;
}
return null;
}
protected override void ApplyMetadataReferenceAdded(ProjectId projectId, MetadataReference metadataReference)
{
if (projectId == null)
{
throw new ArgumentNullException(nameof(projectId));
}
if (metadataReference == null)
{
throw new ArgumentNullException(nameof(metadataReference));
}
IVisualStudioHostProject hostProject;
IVsHierarchy hierarchy;
EnvDTE.Project project;
GetProjectData(projectId, out hostProject, out hierarchy, out project);
string filePath = GetMetadataPath(metadataReference);
if (filePath != null)
{
VSProject vsProject = (VSProject)project.Object;
vsProject.References.Add(filePath);
}
}
protected override void ApplyMetadataReferenceRemoved(ProjectId projectId, MetadataReference metadataReference)
{
if (projectId == null)
{
throw new ArgumentNullException(nameof(projectId));
}
if (metadataReference == null)
{
throw new ArgumentNullException(nameof(metadataReference));
}
IVisualStudioHostProject hostProject;
IVsHierarchy hierarchy;
EnvDTE.Project project;
GetProjectData(projectId, out hostProject, out hierarchy, out project);
string filePath = GetMetadataPath(metadataReference);
if (filePath != null)
{
VSLangProj.VSProject vsProject = (VSLangProj.VSProject)project.Object;
VSLangProj.Reference reference = vsProject.References.Find(filePath);
if (reference != null)
{
reference.Remove();
}
}
}
protected override void ApplyProjectReferenceAdded(ProjectId projectId, ProjectReference projectReference)
{
if (projectId == null)
{
throw new ArgumentNullException(nameof(projectId));
}
if (projectReference == null)
{
throw new ArgumentNullException(nameof(projectReference));
}
IVisualStudioHostProject hostProject;
IVsHierarchy hierarchy;
EnvDTE.Project project;
GetProjectData(projectId, out hostProject, out hierarchy, out project);
IVisualStudioHostProject refHostProject;
IVsHierarchy refHierarchy;
EnvDTE.Project refProject;
GetProjectData(projectReference.ProjectId, out refHostProject, out refHierarchy, out refProject);
VSLangProj.VSProject vsProject = (VSLangProj.VSProject)project.Object;
vsProject.References.AddProject(refProject);
}
protected override void ApplyProjectReferenceRemoved(ProjectId projectId, ProjectReference projectReference)
{
if (projectId == null)
{
throw new ArgumentNullException(nameof(projectId));
}
if (projectReference == null)
{
throw new ArgumentNullException(nameof(projectReference));
}
IVisualStudioHostProject hostProject;
IVsHierarchy hierarchy;
EnvDTE.Project project;
GetProjectData(projectId, out hostProject, out hierarchy, out project);
IVisualStudioHostProject refHostProject;
IVsHierarchy refHierarchy;
EnvDTE.Project refProject;
GetProjectData(projectReference.ProjectId, out refHostProject, out refHierarchy, out refProject);
VSLangProj.VSProject vsProject = (VSLangProj.VSProject)project.Object;
foreach (VSLangProj.Reference reference in vsProject.References)
{
if (reference.SourceProject == refProject)
{
reference.Remove();
}
}
}
protected override void ApplyDocumentAdded(DocumentInfo info, SourceText text)
{
AddDocumentCore(info, text, isAdditionalDocument: false);
}
protected override void ApplyAdditionalDocumentAdded(DocumentInfo info, SourceText text)
{
AddDocumentCore(info, text, isAdditionalDocument: true);
}
private void AddDocumentCore(DocumentInfo info, SourceText initialText, bool isAdditionalDocument)
{
IVsHierarchy hierarchy;
EnvDTE.Project project;
IVisualStudioHostProject hostProject;
GetProjectData(info.Id.ProjectId, out hostProject, out hierarchy, out project);
// If the first namespace name matches the name of the project, then we don't want to
// generate a folder for that. The project is implicitly a folder with that name.
var folders = info.Folders.AsEnumerable();
if (folders.FirstOrDefault() == project.Name)
{
folders = folders.Skip(1);
}
folders = FilterFolderForProjectType(project, folders);
if (IsWebsite(project))
{
AddDocumentToFolder(hostProject, project, info.Id, SpecializedCollections.SingletonEnumerable(AppCodeFolderName), info.Name, info.SourceCodeKind, initialText, isAdditionalDocument: isAdditionalDocument);
}
else if (folders.Any())
{
AddDocumentToFolder(hostProject, project, info.Id, folders, info.Name, info.SourceCodeKind, initialText, isAdditionalDocument: isAdditionalDocument);
}
else
{
AddDocumentToProject(hostProject, project, info.Id, info.Name, info.SourceCodeKind, initialText, isAdditionalDocument: isAdditionalDocument);
}
}
private bool IsWebsite(EnvDTE.Project project)
{
return project.Kind == VsWebSite.PrjKind.prjKindVenusProject;
}
private IEnumerable<string> FilterFolderForProjectType(EnvDTE.Project project, IEnumerable<string> folders)
{
foreach (var folder in folders)
{
var items = GetAllItems(project.ProjectItems);
var folderItem = items.FirstOrDefault(p => StringComparer.OrdinalIgnoreCase.Compare(p.Name, folder) == 0);
if (folderItem == null || folderItem.Kind != EnvDTE.Constants.vsProjectItemKindPhysicalFile)
{
yield return folder;
}
}
}
private IEnumerable<ProjectItem> GetAllItems(ProjectItems projectItems)
{
if (projectItems == null)
{
return SpecializedCollections.EmptyEnumerable<ProjectItem>();
}
var items = projectItems.OfType<ProjectItem>();
return items.Concat(items.SelectMany(i => GetAllItems(i.ProjectItems)));
}
#if false
protected override void AddExistingDocument(DocumentId documentId, string filePath, IEnumerable<string> folders)
{
IVsHierarchy hierarchy;
EnvDTE.Project project;
IVisualStudioHostProject hostProject;
GetProjectData(documentId.ProjectId, out hostProject, out hierarchy, out project);
// If the first namespace name matches the name of the project, then we don't want to
// generate a folder for that. The project is implicitly a folder with that name.
if (folders.FirstOrDefault() == project.Name)
{
folders = folders.Skip(1);
}
var name = Path.GetFileName(filePath);
if (folders.Any())
{
AddDocumentToFolder(hostProject, project, documentId, folders, name, SourceCodeKind.Regular, initialText: null, filePath: filePath);
}
else
{
AddDocumentToProject(hostProject, project, documentId, name, SourceCodeKind.Regular, initialText: null, filePath: filePath);
}
}
#endif
private ProjectItem AddDocumentToProject(
IVisualStudioHostProject hostProject,
EnvDTE.Project project,
DocumentId documentId,
string documentName,
SourceCodeKind sourceCodeKind,
SourceText initialText = null,
string filePath = null,
bool isAdditionalDocument = false)
{
string folderPath;
if (!project.TryGetFullPath(out folderPath))
{
// TODO(cyrusn): Throw an appropriate exception here.
throw new Exception(ServicesVSResources.CouldNotFindLocationOfFol);
}
return AddDocumentToProjectItems(hostProject, project.ProjectItems, documentId, folderPath, documentName, sourceCodeKind, initialText, filePath, isAdditionalDocument);
}
private ProjectItem AddDocumentToFolder(
IVisualStudioHostProject hostProject,
EnvDTE.Project project,
DocumentId documentId,
IEnumerable<string> folders,
string documentName,
SourceCodeKind sourceCodeKind,
SourceText initialText = null,
string filePath = null,
bool isAdditionalDocument = false)
{
var folder = project.FindOrCreateFolder(folders);
string folderPath;
if (!folder.TryGetFullPath(out folderPath))
{
// TODO(cyrusn): Throw an appropriate exception here.
throw new Exception(ServicesVSResources.CouldNotFindLocationOfFol);
}
return AddDocumentToProjectItems(hostProject, folder.ProjectItems, documentId, folderPath, documentName, sourceCodeKind, initialText, filePath, isAdditionalDocument);
}
private ProjectItem AddDocumentToProjectItems(
IVisualStudioHostProject hostProject,
ProjectItems projectItems,
DocumentId documentId,
string folderPath,
string documentName,
SourceCodeKind sourceCodeKind,
SourceText initialText,
string filePath,
bool isAdditionalDocument)
{
if (filePath == null)
{
var baseName = Path.GetFileNameWithoutExtension(documentName);
var extension = isAdditionalDocument ? Path.GetExtension(documentName) : GetPreferredExtension(hostProject, sourceCodeKind);
var uniqueName = projectItems.GetUniqueName(baseName, extension);
filePath = Path.Combine(folderPath, uniqueName);
}
if (initialText != null)
{
using (var writer = new StreamWriter(filePath, append: false, encoding: initialText.Encoding ?? Encoding.UTF8))
{
initialText.Write(writer);
}
}
using (var documentIdHint = _projectTracker.DocumentProvider.ProvideDocumentIdHint(filePath, documentId))
{
return projectItems.AddFromFile(filePath);
}
}
protected void RemoveDocumentCore(DocumentId documentId)
{
if (documentId == null)
{
throw new ArgumentNullException(nameof(documentId));
}
var document = this.GetHostDocument(documentId);
if (document != null)
{
var project = document.Project.Hierarchy as IVsProject3;
var itemId = document.GetItemId();
if (itemId == (uint)VSConstants.VSITEMID.Nil)
{
// it is no longer part of the solution
return;
}
int result;
project.RemoveItem(0, itemId, out result);
}
}
protected override void ApplyDocumentRemoved(DocumentId documentId)
{
RemoveDocumentCore(documentId);
}
protected override void ApplyAdditionalDocumentRemoved(DocumentId documentId)
{
RemoveDocumentCore(documentId);
}
public override void OpenDocument(DocumentId documentId, bool activate = true)
{
OpenDocumentCore(documentId, activate);
}
public override void OpenAdditionalDocument(DocumentId documentId, bool activate = true)
{
OpenDocumentCore(documentId, activate);
}
public override void CloseDocument(DocumentId documentId)
{
CloseDocumentCore(documentId);
}
public override void CloseAdditionalDocument(DocumentId documentId)
{
CloseDocumentCore(documentId);
}
public bool TryGetInfoBarData(out IVsWindowFrame frame, out IVsInfoBarUIFactory factory)
{
frame = null;
factory = null;
var monitorSelectionService = ServiceProvider.GetService(typeof(SVsShellMonitorSelection)) as IVsMonitorSelection;
object value = null;
// We want to get whichever window is currently in focus (including toolbars) as we could have had an exception thrown from the error list or interactive window
if (monitorSelectionService != null &&
ErrorHandler.Succeeded(monitorSelectionService.GetCurrentElementValue((uint)VSConstants.VSSELELEMID.SEID_WindowFrame, out value)))
{
frame = value as IVsWindowFrame;
}
else
{
return false;
}
factory = ServiceProvider.GetService(typeof(SVsInfoBarUIFactory)) as IVsInfoBarUIFactory;
return frame != null && factory != null;
}
public void OpenDocumentCore(DocumentId documentId, bool activate = true)
{
if (documentId == null)
{
throw new ArgumentNullException(nameof(documentId));
}
if (!_foregroundObject.IsForeground())
{
throw new InvalidOperationException(ServicesVSResources.ThisWorkspaceOnlySupportsOpeningDocumentsOnTheUIThread);
}
var document = this.GetHostDocument(documentId);
if (document != null && document.Project != null)
{
IVsWindowFrame frame;
if (TryGetFrame(document, out frame))
{
if (activate)
{
frame.Show();
}
else
{
frame.ShowNoActivate();
}
}
}
}
private bool TryGetFrame(IVisualStudioHostDocument document, out IVsWindowFrame frame)
{
frame = null;
var itemId = document.GetItemId();
if (itemId == (uint)VSConstants.VSITEMID.Nil)
{
// If the ItemId is Nil, then IVsProject would not be able to open the
// document using its ItemId. Thus, we must use OpenDocumentViaProject, which only
// depends on the file path.
uint itemid;
IVsUIHierarchy uiHierarchy;
OLEServiceProvider oleServiceProvider;
return ErrorHandler.Succeeded(_shellOpenDocument.OpenDocumentViaProject(
document.FilePath,
VSConstants.LOGVIEWID.TextView_guid,
out oleServiceProvider,
out uiHierarchy,
out itemid,
out frame));
}
else
{
// If the ItemId is not Nil, then we should not call IVsUIShellDocument
// .OpenDocumentViaProject here because that simply takes a file path and opens the
// file within the context of the first project it finds. That would cause problems
// if the document we're trying to open is actually a linked file in another
// project. So, we get the project's hierarchy and open the document using its item
// ID.
// It's conceivable that IVsHierarchy might not implement IVsProject. However,
// OpenDocumentViaProject itself relies upon this QI working, so it should be OK to
// use here.
var vsProject = document.Project.Hierarchy as IVsProject;
return vsProject != null &&
ErrorHandler.Succeeded(vsProject.OpenItem(itemId, VSConstants.LOGVIEWID.TextView_guid, s_docDataExisting_Unknown, out frame));
}
}
public void CloseDocumentCore(DocumentId documentId)
{
if (documentId == null)
{
throw new ArgumentNullException(nameof(documentId));
}
if (this.IsDocumentOpen(documentId))
{
var document = this.GetHostDocument(documentId);
if (document != null)
{
IVsUIHierarchy uiHierarchy;
IVsWindowFrame frame;
int isOpen;
if (ErrorHandler.Succeeded(_shellOpenDocument.IsDocumentOpen(null, 0, document.FilePath, Guid.Empty, 0, out uiHierarchy, null, out frame, out isOpen)))
{
// TODO: do we need save argument for CloseDocument?
frame.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_NoSave);
}
}
}
}
protected override void ApplyDocumentTextChanged(DocumentId documentId, SourceText newText)
{
EnsureEditableDocuments(documentId);
var hostDocument = GetHostDocument(documentId);
hostDocument.UpdateText(newText);
}
protected override void ApplyAdditionalDocumentTextChanged(DocumentId documentId, SourceText newText)
{
EnsureEditableDocuments(documentId);
var hostDocument = GetHostDocument(documentId);
hostDocument.UpdateText(newText);
}
private static string GetPreferredExtension(IVisualStudioHostProject hostProject, SourceCodeKind sourceCodeKind)
{
// No extension was provided. Pick a good one based on the type of host project.
switch (hostProject.Language)
{
case LanguageNames.CSharp:
// TODO: uncomment when fixing https://github.com/dotnet/roslyn/issues/5325
//return sourceCodeKind == SourceCodeKind.Regular ? ".cs" : ".csx";
return ".cs";
case LanguageNames.VisualBasic:
// TODO: uncomment when fixing https://github.com/dotnet/roslyn/issues/5325
//return sourceCodeKind == SourceCodeKind.Regular ? ".vb" : ".vbx";
return ".vb";
default:
throw new InvalidOperationException();
}
}
public override IVsHierarchy GetHierarchy(ProjectId projectId)
{
var project = this.GetHostProject(projectId);
if (project == null)
{
return null;
}
return project.Hierarchy;
}
internal override void SetDocumentContext(DocumentId documentId)
{
var hostDocument = GetHostDocument(documentId);
var itemId = hostDocument.GetItemId();
if (itemId == (uint)VSConstants.VSITEMID.Nil)
{
// the document has been removed from the solution
return;
}
var hierarchy = hostDocument.Project.Hierarchy;
var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hierarchy, itemId);
if (sharedHierarchy != null)
{
if (sharedHierarchy.SetProperty(
(uint)VSConstants.VSITEMID.Root,
(int)__VSHPROPID8.VSHPROPID_ActiveIntellisenseProjectContext,
ProjectTracker.GetProject(documentId.ProjectId).ProjectSystemName) == VSConstants.S_OK)
{
// The ASP.NET 5 intellisense project is now updated.
return;
}
else
{
// Universal Project shared files
// Change the SharedItemContextHierarchy of the project's parent hierarchy, then
// hierarchy events will trigger the workspace to update.
var hr = sharedHierarchy.SetProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID7.VSHPROPID_SharedItemContextHierarchy, hierarchy);
}
}
else
{
// Regular linked files
// Transfer the item (open buffer) to the new hierarchy, and then hierarchy events
// will trigger the workspace to update.
var vsproj = hierarchy as IVsProject3;
var hr = vsproj.TransferItem(hostDocument.FilePath, hostDocument.FilePath, punkWindowFrame: null);
}
}
internal void UpdateDocumentContextIfContainsDocument(IVsHierarchy sharedHierarchy, DocumentId documentId)
{
// TODO: This is a very roundabout way to update the context
// The sharedHierarchy passed in has a new context, but we don't know what it is.
// The documentId passed in is associated with this sharedHierarchy, and this method
// will be called once for each such documentId. During this process, one of these
// documentIds will actually belong to the new SharedItemContextHierarchy. Once we
// find that one, we can map back to the open buffer and set its active context to
// the appropriate project.
var hostProject = LinkedFileUtilities.GetContextHostProject(sharedHierarchy, ProjectTracker);
if (hostProject.Hierarchy == sharedHierarchy)
{
// How?
return;
}
if (hostProject.Id != documentId.ProjectId)
{
// While this documentId is associated with one of the head projects for this
// sharedHierarchy, it is not associated with the new context hierarchy. Another
// documentId will be passed to this method and update the context.
return;
}
// This documentId belongs to the new SharedItemContextHierarchy. Update the associated
// buffer.
OnDocumentContextUpdated(documentId);
}
/// <summary>
/// Finds the <see cref="DocumentId"/> related to the given <see cref="DocumentId"/> that
/// is in the current context. For regular files (non-shared and non-linked) and closed
/// linked files, this is always the provided <see cref="DocumentId"/>. For open linked
/// files and open shared files, the active context is already tracked by the
/// <see cref="Workspace"/> and can be looked up directly. For closed shared files, the
/// document in the shared project's <see cref="__VSHPROPID7.VSHPROPID_SharedItemContextHierarchy"/>
/// is preferred.
/// </summary>
internal override DocumentId GetDocumentIdInCurrentContext(DocumentId documentId)
{
// If the document is open, then the Workspace knows the current context for both
// linked and shared files
if (IsDocumentOpen(documentId))
{
return base.GetDocumentIdInCurrentContext(documentId);
}
var hostDocument = GetHostDocument(documentId);
var itemId = hostDocument.GetItemId();
if (itemId == (uint)VSConstants.VSITEMID.Nil)
{
// An itemid is required to determine whether the file belongs to a Shared Project
return base.GetDocumentIdInCurrentContext(documentId);
}
// If this is a regular document or a closed linked (non-shared) document, then use the
// default logic for determining current context.
var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hostDocument.Project.Hierarchy, itemId);
if (sharedHierarchy == null)
{
return base.GetDocumentIdInCurrentContext(documentId);
}
// This is a closed shared document, so we must determine the correct context.
var hostProject = LinkedFileUtilities.GetContextHostProject(sharedHierarchy, ProjectTracker);
var matchingProject = CurrentSolution.GetProject(hostProject.Id);
if (matchingProject == null || hostProject.Hierarchy == sharedHierarchy)
{
return base.GetDocumentIdInCurrentContext(documentId);
}
if (matchingProject.ContainsDocument(documentId))
{
// The provided documentId is in the current context project
return documentId;
}
// The current context document is from another project.
var linkedDocumentIds = CurrentSolution.GetDocument(documentId).GetLinkedDocumentIds();
var matchingDocumentId = linkedDocumentIds.FirstOrDefault(id => id.ProjectId == matchingProject.Id);
return matchingDocumentId ?? base.GetDocumentIdInCurrentContext(documentId);
}
internal bool TryGetHierarchy(ProjectId projectId, out IVsHierarchy hierarchy)
{
hierarchy = this.GetHierarchy(projectId);
return hierarchy != null;
}
public override string GetFilePath(DocumentId documentId)
{
var document = this.GetHostDocument(documentId);
if (document == null)
{
return null;
}
else
{
return document.FilePath;
}
}
internal void StartSolutionCrawler()
{
if (_registrationService == null)
{
lock (this)
{
if (_registrationService == null)
{
_registrationService = this.Services.GetService<ISolutionCrawlerRegistrationService>();
_registrationService.Register(this);
}
}
}
}
internal void StopSolutionCrawler()
{
if (_registrationService != null)
{
lock (this)
{
if (_registrationService != null)
{
_registrationService.Unregister(this, blockingShutdown: true);
_registrationService = null;
}
}
}
}
protected override void Dispose(bool finalize)
{
// workspace is going away. unregister this workspace from work coordinator
StopSolutionCrawler();
base.Dispose(finalize);
}
public void EnsureEditableDocuments(IEnumerable<DocumentId> documents)
{
var queryEdit = (IVsQueryEditQuerySave2)ServiceProvider.GetService(typeof(SVsQueryEditQuerySave));
var fileNames = documents.Select(GetFilePath).ToArray();
uint editVerdict;
uint editResultFlags;
// TODO: meditate about the flags we can pass to this and decide what is most appropriate for Roslyn
int result = queryEdit.QueryEditFiles(
rgfQueryEdit: 0,
cFiles: fileNames.Length,
rgpszMkDocuments: fileNames,
rgrgf: new uint[fileNames.Length],
rgFileInfo: new VSQEQS_FILE_ATTRIBUTE_DATA[fileNames.Length],
pfEditVerdict: out editVerdict,
prgfMoreInfo: out editResultFlags);
if (ErrorHandler.Failed(result) ||
editVerdict != (uint)tagVSQueryEditResult.QER_EditOK)
{
throw new Exception("Unable to check out the files from source control.");
}
if ((editResultFlags & (uint)(tagVSQueryEditResultFlags2.QER_Changed | tagVSQueryEditResultFlags2.QER_Reloaded)) != 0)
{
throw new Exception("A file was reloaded during the source control checkout.");
}
}
public void EnsureEditableDocuments(params DocumentId[] documents)
{
this.EnsureEditableDocuments((IEnumerable<DocumentId>)documents);
}
internal void OnDocumentTextUpdatedOnDisk(DocumentId documentId)
{
var vsDoc = this.GetHostDocument(documentId);
this.OnDocumentTextLoaderChanged(documentId, vsDoc.Loader);
}
internal void OnAdditionalDocumentTextUpdatedOnDisk(DocumentId documentId)
{
var vsDoc = this.GetHostDocument(documentId);
this.OnAdditionalDocumentTextLoaderChanged(documentId, vsDoc.Loader);
}
public TInterface GetVsService<TService, TInterface>()
where TService : class
where TInterface : class
{
return this.ServiceProvider.GetService(typeof(TService)) as TInterface;
}
internal override bool CanAddProjectReference(ProjectId referencingProject, ProjectId referencedProject)
{
_foregroundObject.AssertIsForeground();
IVsHierarchy referencingHierarchy;
IVsHierarchy referencedHierarchy;
if (!TryGetHierarchy(referencingProject, out referencingHierarchy) ||
!TryGetHierarchy(referencedProject, out referencedHierarchy))
{
// Couldn't even get a hierarchy for this project. So we have to assume
// that adding a reference is disallowed.
return false;
}
// First we have to see if either project disallows the reference being added.
const int ContextFlags = (int)__VSQUERYFLAVORREFERENCESCONTEXT.VSQUERYFLAVORREFERENCESCONTEXT_RefreshReference;
uint canAddProjectReference = (uint)__VSREFERENCEQUERYRESULT.REFERENCE_UNKNOWN;
uint canBeReferenced = (uint)__VSREFERENCEQUERYRESULT.REFERENCE_UNKNOWN;
var referencingProjectFlavor3 = referencingHierarchy as IVsProjectFlavorReferences3;
if (referencingProjectFlavor3 != null)
{
string unused;
if (ErrorHandler.Failed(referencingProjectFlavor3.QueryAddProjectReferenceEx(referencedHierarchy, ContextFlags, out canAddProjectReference, out unused)))
{
// Something went wrong even trying to see if the reference would be allowed.
// Assume it won't be allowed.
return false;
}
if (canAddProjectReference == (uint)__VSREFERENCEQUERYRESULT.REFERENCE_DENY)
{
// Adding this project reference is not allowed.
return false;
}
}
var referencedProjectFlavor3 = referencedHierarchy as IVsProjectFlavorReferences3;
if (referencedProjectFlavor3 != null)
{
string unused;
if (ErrorHandler.Failed(referencedProjectFlavor3.QueryCanBeReferencedEx(referencingHierarchy, ContextFlags, out canBeReferenced, out unused)))
{
// Something went wrong even trying to see if the reference would be allowed.
// Assume it won't be allowed.
return false;
}
if (canBeReferenced == (uint)__VSREFERENCEQUERYRESULT.REFERENCE_DENY)
{
// Adding this project reference is not allowed.
return false;
}
}
// Neither project denied the reference being added. At this point, if either project
// allows the reference to be added, and the other doesn't block it, then we can add
// the reference.
if (canAddProjectReference == (int)__VSREFERENCEQUERYRESULT.REFERENCE_ALLOW ||
canBeReferenced == (int)__VSREFERENCEQUERYRESULT.REFERENCE_ALLOW)
{
return true;
}
// In both directions things are still unknown. Fallback to the reference manager
// to make the determination here.
var referenceManager = GetVsService<SVsReferenceManager, IVsReferenceManager>();
if (referenceManager == null)
{
// Couldn't get the reference manager. Have to assume it's not allowed.
return false;
}
// As long as the reference manager does not deny things, then we allow the
// reference to be added.
var result = referenceManager.QueryCanReferenceProject(referencingHierarchy, referencedHierarchy);
return result != (uint)__VSREFERENCEQUERYRESULT.REFERENCE_DENY;
}
/// <summary>
/// A trivial implementation of <see cref="IVisualStudioWorkspaceHost" /> that just
/// forwards the calls down to the underlying Workspace.
/// </summary>
protected class VisualStudioWorkspaceHost : IVisualStudioWorkspaceHost, IVisualStudioWorkingFolder
{
private readonly VisualStudioWorkspaceImpl _workspace;
private Dictionary<DocumentId, uint> _documentIdToHierarchyEventsCookieMap = new Dictionary<DocumentId, uint>();
public VisualStudioWorkspaceHost(VisualStudioWorkspaceImpl workspace)
{
_workspace = workspace;
}
void IVisualStudioWorkspaceHost.OnOptionsChanged(ProjectId projectId, CompilationOptions compilationOptions, ParseOptions parseOptions)
{
_workspace.OnCompilationOptionsChanged(projectId, compilationOptions);
_workspace.OnParseOptionsChanged(projectId, parseOptions);
}
void IVisualStudioWorkspaceHost.OnDocumentAdded(DocumentInfo documentInfo)
{
_workspace.OnDocumentAdded(documentInfo);
}
void IVisualStudioWorkspaceHost.OnDocumentClosed(DocumentId documentId, ITextBuffer textBuffer, TextLoader loader, bool updateActiveContext)
{
// TODO: Move this out to DocumentProvider. As is, this depends on being able to
// access the host document which will already be deleted in some cases, causing
// a crash. Until this is fixed, we will leak a HierarchyEventsSink every time a
// Mercury shared document is closed.
// UnsubscribeFromSharedHierarchyEvents(documentId);
using (_workspace.Services.GetService<IGlobalOperationNotificationService>().Start("Document Closed"))
{
_workspace.OnDocumentClosed(documentId, loader, updateActiveContext);
}
}
void IVisualStudioWorkspaceHost.OnDocumentOpened(DocumentId documentId, ITextBuffer textBuffer, bool currentContext)
{
SubscribeToSharedHierarchyEvents(documentId);
_workspace.OnDocumentOpened(documentId, textBuffer.AsTextContainer(), currentContext);
}
private void SubscribeToSharedHierarchyEvents(DocumentId documentId)
{
// Todo: maybe avoid double alerts.
var hostDocument = _workspace.GetHostDocument(documentId);
if (hostDocument == null)
{
return;
}
var hierarchy = hostDocument.Project.Hierarchy;
var itemId = hostDocument.GetItemId();
if (itemId == (uint)VSConstants.VSITEMID.Nil)
{
// the document has been removed from the solution
return;
}
var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hierarchy, itemId);
if (sharedHierarchy != null)
{
uint cookie;
var eventSink = new HierarchyEventsSink(_workspace, sharedHierarchy, documentId);
var hr = sharedHierarchy.AdviseHierarchyEvents(eventSink, out cookie);
if (hr == VSConstants.S_OK && !_documentIdToHierarchyEventsCookieMap.ContainsKey(documentId))
{
_documentIdToHierarchyEventsCookieMap.Add(documentId, cookie);
}
}
}
private void UnsubscribeFromSharedHierarchyEvents(DocumentId documentId)
{
var hostDocument = _workspace.GetHostDocument(documentId);
var itemId = hostDocument.GetItemId();
if (itemId == (uint)VSConstants.VSITEMID.Nil)
{
// the document has been removed from the solution
return;
}
var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hostDocument.Project.Hierarchy, itemId);
if (sharedHierarchy != null)
{
uint cookie;
if (_documentIdToHierarchyEventsCookieMap.TryGetValue(documentId, out cookie))
{
var hr = sharedHierarchy.UnadviseHierarchyEvents(cookie);
_documentIdToHierarchyEventsCookieMap.Remove(documentId);
}
}
}
private void RegisterPrimarySolutionForPersistentStorage(SolutionId solutionId)
{
var service = _workspace.Services.GetService<IPersistentStorageService>() as PersistentStorageService;
if (service == null)
{
return;
}
service.RegisterPrimarySolution(solutionId);
}
private void UnregisterPrimarySolutionForPersistentStorage(SolutionId solutionId, bool synchronousShutdown)
{
var service = _workspace.Services.GetService<IPersistentStorageService>() as PersistentStorageService;
if (service == null)
{
return;
}
service.UnregisterPrimarySolution(solutionId, synchronousShutdown);
}
void IVisualStudioWorkspaceHost.OnDocumentRemoved(DocumentId documentId)
{
_workspace.OnDocumentRemoved(documentId);
}
void IVisualStudioWorkspaceHost.OnMetadataReferenceAdded(ProjectId projectId, PortableExecutableReference metadataReference)
{
_workspace.OnMetadataReferenceAdded(projectId, metadataReference);
}
void IVisualStudioWorkspaceHost.OnMetadataReferenceRemoved(ProjectId projectId, PortableExecutableReference metadataReference)
{
_workspace.OnMetadataReferenceRemoved(projectId, metadataReference);
}
void IVisualStudioWorkspaceHost.OnProjectAdded(ProjectInfo projectInfo)
{
using (_workspace.Services.GetService<IGlobalOperationNotificationService>()?.Start("Add Project"))
{
_workspace.OnProjectAdded(projectInfo);
}
}
void IVisualStudioWorkspaceHost.OnProjectReferenceAdded(ProjectId projectId, ProjectReference projectReference)
{
_workspace.OnProjectReferenceAdded(projectId, projectReference);
}
void IVisualStudioWorkspaceHost.OnProjectReferenceRemoved(ProjectId projectId, ProjectReference projectReference)
{
_workspace.OnProjectReferenceRemoved(projectId, projectReference);
}
void IVisualStudioWorkspaceHost.OnProjectRemoved(ProjectId projectId)
{
using (_workspace.Services.GetService<IGlobalOperationNotificationService>()?.Start("Remove Project"))
{
_workspace.OnProjectRemoved(projectId);
}
}
void IVisualStudioWorkspaceHost.OnSolutionAdded(SolutionInfo solutionInfo)
{
RegisterPrimarySolutionForPersistentStorage(solutionInfo.Id);
_workspace.OnSolutionAdded(solutionInfo);
}
void IVisualStudioWorkspaceHost.OnSolutionRemoved()
{
var solutionId = _workspace.CurrentSolution.Id;
_workspace.OnSolutionRemoved();
_workspace.ClearReferenceCache();
UnregisterPrimarySolutionForPersistentStorage(solutionId, synchronousShutdown: false);
}
void IVisualStudioWorkspaceHost.ClearSolution()
{
_workspace.ClearSolution();
_workspace.ClearReferenceCache();
}
void IVisualStudioWorkspaceHost.OnDocumentTextUpdatedOnDisk(DocumentId id)
{
_workspace.OnDocumentTextUpdatedOnDisk(id);
}
void IVisualStudioWorkspaceHost.OnAssemblyNameChanged(ProjectId id, string assemblyName)
{
_workspace.OnAssemblyNameChanged(id, assemblyName);
}
void IVisualStudioWorkspaceHost.OnOutputFilePathChanged(ProjectId id, string outputFilePath)
{
_workspace.OnOutputFilePathChanged(id, outputFilePath);
}
void IVisualStudioWorkspaceHost.OnProjectNameChanged(ProjectId projectId, string name, string filePath)
{
_workspace.OnProjectNameChanged(projectId, name, filePath);
}
void IVisualStudioWorkspaceHost.OnAnalyzerReferenceAdded(ProjectId projectId, AnalyzerReference analyzerReference)
{
_workspace.OnAnalyzerReferenceAdded(projectId, analyzerReference);
}
void IVisualStudioWorkspaceHost.OnAnalyzerReferenceRemoved(ProjectId projectId, AnalyzerReference analyzerReference)
{
_workspace.OnAnalyzerReferenceRemoved(projectId, analyzerReference);
}
void IVisualStudioWorkspaceHost.OnAdditionalDocumentAdded(DocumentInfo additionalDocumentInfo)
{
_workspace.OnAdditionalDocumentAdded(additionalDocumentInfo);
}
void IVisualStudioWorkspaceHost.OnAdditionalDocumentRemoved(DocumentId additionalDocumentId)
{
_workspace.OnAdditionalDocumentRemoved(additionalDocumentId);
}
void IVisualStudioWorkspaceHost.OnAdditionalDocumentOpened(DocumentId documentId, ITextBuffer textBuffer, bool isCurrentContext)
{
_workspace.OnAdditionalDocumentOpened(documentId, textBuffer.AsTextContainer(), isCurrentContext);
}
void IVisualStudioWorkspaceHost.OnAdditionalDocumentClosed(DocumentId documentId, ITextBuffer textBuffer, TextLoader loader)
{
_workspace.OnAdditionalDocumentClosed(documentId, loader);
}
void IVisualStudioWorkspaceHost.OnAdditionalDocumentTextUpdatedOnDisk(DocumentId id)
{
_workspace.OnAdditionalDocumentTextUpdatedOnDisk(id);
}
void IVisualStudioWorkingFolder.OnBeforeWorkingFolderChange()
{
UnregisterPrimarySolutionForPersistentStorage(_workspace.CurrentSolution.Id, synchronousShutdown: true);
}
void IVisualStudioWorkingFolder.OnAfterWorkingFolderChange()
{
var solutionId = _workspace.CurrentSolution.Id;
_workspace.ProjectTracker.UpdateSolutionProperties(solutionId);
RegisterPrimarySolutionForPersistentStorage(solutionId);
}
}
}
}
| |
// 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.Reflection;
using Xunit;
public static class ActivatorTests
{
[Fact]
public static void TestCreateInstance()
{
// Passing null args is equivilent to an empty array of args.
Choice1 c = (Choice1)(Activator.CreateInstance(typeof(Choice1), null));
Assert.Equal(1, c.I);
c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { }));
Assert.Equal(1, c.I);
c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { 42 }));
Assert.Equal(2, c.I);
c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { "Hello" }));
Assert.Equal(3, c.I);
c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { 5.1, "Hello" }));
Assert.Equal(4, c.I);
Activator.CreateInstance(typeof(StructTypeWithoutReflectionMetadata));
}
[Fact]
public static void TestCreateInstance_ConstructorWithPrimitive_PerformsPrimitiveWidening()
{
// Primitive widening is allowed by the binder, but not by Dynamic.DelegateInvoke().
Choice1 c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { (short)-2 }));
Assert.Equal(2, c.I);
}
[Fact]
public static void TestCreateInstance_ConstructorWithParamsParameter()
{
// C# params arguments are honored by Activator.CreateInstance()
Choice1 c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { new VarArgs() }));
Assert.Equal(5, c.I);
c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { new VarArgs(), "P1" }));
Assert.Equal(5, c.I);
c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { new VarArgs(), "P1", "P2" }));
Assert.Equal(5, c.I);
c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { new VarStringArgs() }));
Assert.Equal(6, c.I);
c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { new VarStringArgs(), "P1" }));
Assert.Equal(6, c.I);
c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { new VarStringArgs(), "P1", "P2" }));
Assert.Equal(6, c.I);
}
[Fact]
public static void TestCreateInstance_Invalid()
{
Assert.Throws<ArgumentNullException>("type", () => Activator.CreateInstance(null)); // Type is null
Assert.Throws<ArgumentNullException>("type", () => Activator.CreateInstance(null, new object[0])); // Type is null
Assert.Throws<AmbiguousMatchException>(() => Activator.CreateInstance(typeof(Choice1), new object[] { null }));
// C# designated optional parameters are not optional as far as Activator.CreateInstance() is concerned.
Assert.ThrowsAny<MissingMemberException>(() => Activator.CreateInstance(typeof(Choice1), new object[] { 5.1 }));
Assert.ThrowsAny<MissingMemberException>(() => Activator.CreateInstance(typeof(Choice1), new object[] { 5.1, Type.Missing }));
// Invalid params args
Assert.ThrowsAny<MissingMemberException>(() => Activator.CreateInstance(typeof(Choice1), new object[] { new VarStringArgs(), 5, 6 }));
// Primitive widening not supported for "params" arguments.
//
// (This is probably an accidental behavior on the desktop as the default binder specifically checks to see if the params arguments are widenable to the
// params array element type and gives it the go-ahead if it is. Unfortunately, the binder then bollixes itself by using Array.Copy() to copy
// the params arguments. Since Array.Copy() doesn't tolerate this sort of type mismatch, it throws an InvalidCastException which bubbles out
// out of Activator.CreateInstance. Accidental or not, we'll inherit that behavior on .NET Native.)
Assert.Throws<InvalidCastException>(() => Activator.CreateInstance(typeof(Choice1), new object[] { new VarIntArgs(), 1, (short)2 }));
Assert.ThrowsAny<MissingMemberException>(() => Activator.CreateInstance<TypeWithoutDefaultCtor>()); // Type has no default constructor
Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance<TypeWithDefaultCtorThatThrows>()); // Type has a default constructor throws an exception
}
[Fact]
public static void TestCreateInstance_Generic()
{
Choice1 c = Activator.CreateInstance<Choice1>();
Assert.Equal(1, c.I);
Activator.CreateInstance<DateTime>();
Activator.CreateInstance<StructTypeWithoutReflectionMetadata>();
}
[Fact]
public static void TestCreateInstance_Generic_Invalid()
{
Assert.ThrowsAny<MissingMemberException>(() => Activator.CreateInstance<int[]>()); // Cannot create array type
Assert.ThrowsAny<MissingMemberException>(() => Activator.CreateInstance<TypeWithoutDefaultCtor>()); // Type has no default constructor
Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance<TypeWithDefaultCtorThatThrows>()); // Type has a default constructor that throws
}
class PrivateType
{
public PrivateType() { }
}
class PrivateTypeWithDefaultCtor
{
private PrivateTypeWithDefaultCtor() { }
}
class PrivateTypeWithoutDefaultCtor
{
private PrivateTypeWithoutDefaultCtor(int x) { }
}
class PrivateTypeWithDefaultCtorThatThrows
{
public PrivateTypeWithDefaultCtorThatThrows() { throw new Exception(); }
}
[Fact]
public static void TestCreateInstance_Type_Bool()
{
Assert.Equal(typeof(PrivateType), Activator.CreateInstance(typeof(PrivateType), true).GetType());
Assert.Equal(typeof(PrivateType), Activator.CreateInstance(typeof(PrivateType), false).GetType());
Assert.Equal(typeof(PrivateTypeWithDefaultCtor), Activator.CreateInstance(typeof(PrivateTypeWithDefaultCtor), true).GetType());
Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(typeof(PrivateTypeWithDefaultCtor), false).GetType());
Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(typeof(PrivateTypeWithDefaultCtorThatThrows), true).GetType());
Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(typeof(PrivateTypeWithDefaultCtorThatThrows), false).GetType());
Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(typeof(PrivateTypeWithoutDefaultCtor), true).GetType());
Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(typeof(PrivateTypeWithoutDefaultCtor), false).GetType());
}
public class Choice1 : Attribute
{
public Choice1()
{
I = 1;
}
public Choice1(int i)
{
I = 2;
}
public Choice1(string s)
{
I = 3;
}
public Choice1(double d, string optionalS = "Hey")
{
I = 4;
}
public Choice1(VarArgs varArgs, params object[] parameters)
{
I = 5;
}
public Choice1(VarStringArgs varArgs, params string[] parameters)
{
I = 6;
}
public Choice1(VarIntArgs varArgs, params int[] parameters)
{
I = 7;
}
public int I;
}
public class VarArgs
{
}
public class VarStringArgs
{
}
public class VarIntArgs
{
}
public struct StructTypeWithoutReflectionMetadata
{
}
public class TypeWithoutDefaultCtor
{
private TypeWithoutDefaultCtor(int x) { }
}
public class TypeWithDefaultCtorThatThrows
{
public TypeWithDefaultCtorThatThrows() { throw new Exception(); }
}
}
| |
// This file was generated by CSLA Object Generator - CslaGenFork v4.5
//
// Filename: DocStatusEditDyna
// ObjectType: DocStatusEditDyna
// CSLAType: DynamicEditableRoot
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using DocStore.Business.Util;
using DocStore.Business.Security;
using UsingLibrary;
namespace DocStore.Business
{
/// <summary>
/// DocStatusEditDyna (dynamic root object).<br/>
/// This is a generated <see cref="DocStatusEditDyna"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="DocStatusEditDynaColl"/> collection.
/// </remarks>
[Serializable]
public partial class DocStatusEditDyna : BusinessBase<DocStatusEditDyna>, IHaveInterface, IHaveGenericInterface<DocStatusEditDyna>
{
#region Static Fields
private static int _lastId;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="DocStatusID"/> property.
/// </summary>
[NotUndoable]
public static readonly PropertyInfo<int> DocStatusIDProperty = RegisterProperty<int>(p => p.DocStatusID, "Doc Status ID");
/// <summary>
/// Row version counter for concurrency control
/// </summary>
/// <value>The Doc Status ID.</value>
public int DocStatusID
{
get { return GetProperty(DocStatusIDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="DocStatusName"/> property.
/// </summary>
public static readonly PropertyInfo<string> DocStatusNameProperty = RegisterProperty<string>(p => p.DocStatusName, "Doc Status Name");
/// <summary>
/// Gets or sets the Doc Status Name.
/// </summary>
/// <value>The Doc Status Name.</value>
public string DocStatusName
{
get { return GetProperty(DocStatusNameProperty); }
set { SetProperty(DocStatusNameProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="CreateDate"/> property.
/// </summary>
public static readonly PropertyInfo<SmartDate> CreateDateProperty = RegisterProperty<SmartDate>(p => p.CreateDate, "Create Date");
/// <summary>
/// Gets the Create Date.
/// </summary>
/// <value>The Create Date.</value>
public SmartDate CreateDate
{
get { return GetProperty(CreateDateProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="CreateUserID"/> property.
/// </summary>
public static readonly PropertyInfo<int> CreateUserIDProperty = RegisterProperty<int>(p => p.CreateUserID, "Create User ID");
/// <summary>
/// Gets the Create User ID.
/// </summary>
/// <value>The Create User ID.</value>
public int CreateUserID
{
get { return GetProperty(CreateUserIDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="ChangeDate"/> property.
/// </summary>
public static readonly PropertyInfo<SmartDate> ChangeDateProperty = RegisterProperty<SmartDate>(p => p.ChangeDate, "Change Date");
/// <summary>
/// Gets the Change Date.
/// </summary>
/// <value>The Change Date.</value>
public SmartDate ChangeDate
{
get { return GetProperty(ChangeDateProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="ChangeUserID"/> property.
/// </summary>
public static readonly PropertyInfo<int> ChangeUserIDProperty = RegisterProperty<int>(p => p.ChangeUserID, "Change User ID");
/// <summary>
/// Gets the Change User ID.
/// </summary>
/// <value>The Change User ID.</value>
public int ChangeUserID
{
get { return GetProperty(ChangeUserIDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="RowVersion"/> property.
/// </summary>
[NotUndoable]
public static readonly PropertyInfo<byte[]> RowVersionProperty = RegisterProperty<byte[]>(p => p.RowVersion, "Row Version");
/// <summary>
/// Gets the Row Version.
/// </summary>
/// <value>The Row Version.</value>
public byte[] RowVersion
{
get { return GetProperty(RowVersionProperty); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="DocStatusEditDyna"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="DocStatusEditDyna"/> object.</returns>
internal static DocStatusEditDyna NewDocStatusEditDyna()
{
return DataPortal.Create<DocStatusEditDyna>();
}
/// <summary>
/// Factory method. Loads a <see cref="DocStatusEditDyna"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="DocStatusEditDyna"/> object.</returns>
internal static DocStatusEditDyna GetDocStatusEditDyna(SafeDataReader dr)
{
DocStatusEditDyna obj = new DocStatusEditDyna();
obj.Fetch(dr);
obj.MarkOld();
// check all object rules and property rules
obj.BusinessRules.CheckRules();
return obj;
}
/// <summary>
/// Factory method. Deletes a <see cref="DocStatusEditDyna"/> object, based on given parameters.
/// </summary>
/// <param name="docStatusID">The DocStatusID of the DocStatusEditDyna to delete.</param>
internal static void DeleteDocStatusEditDyna(int docStatusID)
{
DataPortal.Delete<DocStatusEditDyna>(docStatusID);
}
/// <summary>
/// Factory method. Asynchronously creates a new <see cref="DocStatusEditDyna"/> object.
/// </summary>
/// <param name="callback">The completion callback method.</param>
internal static void NewDocStatusEditDyna(EventHandler<DataPortalResult<DocStatusEditDyna>> callback)
{
DataPortal.BeginCreate<DocStatusEditDyna>(callback);
}
/// <summary>
/// Factory method. Asynchronously deletes a <see cref="DocStatusEditDyna"/> object, based on given parameters.
/// </summary>
/// <param name="docStatusID">The DocStatusID of the DocStatusEditDyna to delete.</param>
/// <param name="callback">The completion callback method.</param>
internal static void DeleteDocStatusEditDyna(int docStatusID, EventHandler<DataPortalResult<DocStatusEditDyna>> callback)
{
DataPortal.BeginDelete<DocStatusEditDyna>(docStatusID, callback);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="DocStatusEditDyna"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public DocStatusEditDyna()
{
// Use factory methods and do not use direct creation.
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="DocStatusEditDyna"/> object properties.
/// </summary>
[RunLocal]
protected override void DataPortal_Create()
{
LoadProperty(DocStatusIDProperty, System.Threading.Interlocked.Decrement(ref _lastId));
LoadProperty(CreateDateProperty, new SmartDate(DateTime.Now));
LoadProperty(CreateUserIDProperty, UserInformation.UserId);
LoadProperty(ChangeDateProperty, ReadProperty(CreateDateProperty));
LoadProperty(ChangeUserIDProperty, ReadProperty(CreateUserIDProperty));
var args = new DataPortalHookArgs();
OnCreate(args);
base.DataPortal_Create();
}
/// <summary>
/// Loads a <see cref="DocStatusEditDyna"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(DocStatusIDProperty, dr.GetInt32("DocStatusID"));
LoadProperty(DocStatusNameProperty, dr.GetString("DocStatusName"));
LoadProperty(CreateDateProperty, dr.GetSmartDate("CreateDate", true));
LoadProperty(CreateUserIDProperty, dr.GetInt32("CreateUserID"));
LoadProperty(ChangeDateProperty, dr.GetSmartDate("ChangeDate", true));
LoadProperty(ChangeUserIDProperty, dr.GetInt32("ChangeUserID"));
LoadProperty(RowVersionProperty, dr.GetValue("RowVersion") as byte[]);
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="DocStatusEditDyna"/> object in the database.
/// </summary>
protected override void DataPortal_Insert()
{
SimpleAuditTrail();
using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.DocStoreConnection, false))
{
using (var cmd = new SqlCommand("AddDocStatusEditDyna", ctx.Connection))
{
cmd.Transaction = ctx.Transaction;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@DocStatusID", ReadProperty(DocStatusIDProperty)).Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("@DocStatusName", ReadProperty(DocStatusNameProperty)).DbType = DbType.String;
cmd.Parameters.AddWithValue("@CreateDate", ReadProperty(CreateDateProperty).DBValue).DbType = DbType.DateTime2;
cmd.Parameters.AddWithValue("@CreateUserID", ReadProperty(CreateUserIDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@ChangeDate", ReadProperty(ChangeDateProperty).DBValue).DbType = DbType.DateTime2;
cmd.Parameters.AddWithValue("@ChangeUserID", ReadProperty(ChangeUserIDProperty)).DbType = DbType.Int32;
cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
LoadProperty(DocStatusIDProperty, (int) cmd.Parameters["@DocStatusID"].Value);
LoadProperty(RowVersionProperty, (byte[]) cmd.Parameters["@NewRowVersion"].Value);
}
ctx.Commit();
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="DocStatusEditDyna"/> object.
/// </summary>
protected override void DataPortal_Update()
{
SimpleAuditTrail();
using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.DocStoreConnection, false))
{
using (var cmd = new SqlCommand("UpdateDocStatusEditDyna", ctx.Connection))
{
cmd.Transaction = ctx.Transaction;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@DocStatusID", ReadProperty(DocStatusIDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@DocStatusName", ReadProperty(DocStatusNameProperty)).DbType = DbType.String;
cmd.Parameters.AddWithValue("@ChangeDate", ReadProperty(ChangeDateProperty).DBValue).DbType = DbType.DateTime2;
cmd.Parameters.AddWithValue("@ChangeUserID", ReadProperty(ChangeUserIDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@RowVersion", ReadProperty(RowVersionProperty)).DbType = DbType.Binary;
cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
LoadProperty(RowVersionProperty, (byte[]) cmd.Parameters["@NewRowVersion"].Value);
}
ctx.Commit();
}
}
private void SimpleAuditTrail()
{
LoadProperty(ChangeDateProperty, DateTime.Now);
LoadProperty(ChangeUserIDProperty, UserInformation.UserId);
if (IsNew)
{
LoadProperty(CreateDateProperty, ReadProperty(ChangeDateProperty));
LoadProperty(CreateUserIDProperty, ReadProperty(ChangeUserIDProperty));
}
}
/// <summary>
/// Self deletes the <see cref="DocStatusEditDyna"/> object.
/// </summary>
protected override void DataPortal_DeleteSelf()
{
DataPortal_Delete(DocStatusID);
}
/// <summary>
/// Deletes the <see cref="DocStatusEditDyna"/> object from database.
/// </summary>
/// <param name="docStatusID">The delete criteria.</param>
protected void DataPortal_Delete(int docStatusID)
{
// audit the object, just in case soft delete is used on this object
SimpleAuditTrail();
using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.DocStoreConnection, false))
{
using (var cmd = new SqlCommand("DeleteDocStatusEditDyna", ctx.Connection))
{
cmd.Transaction = ctx.Transaction;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@DocStatusID", docStatusID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, docStatusID);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
ctx.Commit();
}
}
#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
}
}
| |
namespace ZetaResourceEditor.UI.Translation
{
partial class TranslateOptionsForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.panelControl1 = new ExtendedControlsLibrary.Skinning.CustomPanel.MyPanelControl();
this.xtraTabControl1 = new ExtendedControlsLibrary.Skinning.CustomTabControl.MyXtraTabControl();
this.engineTabPage = new ExtendedControlsLibrary.Skinning.CustomTabControl.MyXtraTabPage();
this.appIDMemoEdit = new ExtendedControlsLibrary.Skinning.CustomMemoEdit.MyMemoEdit();
this.appIDLinkControl = new ExtendedControlsLibrary.Skinning.CustomHyperLinkEdit.MyHyperLinkEdit();
this.labelControl2 = new ExtendedControlsLibrary.Skinning.CustomLabelEdit.MyLabelControl();
this.engineComboBox = new ExtendedControlsLibrary.Skinning.CustomComboBoxEdit.MyComboBoxEdit();
this.appIDLabel = new ExtendedControlsLibrary.Skinning.CustomLabelEdit.MyLabelControl();
this.appIDTextEdit = new ExtendedControlsLibrary.Skinning.CustomTextEdit.MyTextEdit();
this.settingsTabPage = new ExtendedControlsLibrary.Skinning.CustomTabControl.MyXtraTabPage();
this.labelControl1 = new ExtendedControlsLibrary.Skinning.CustomLabelEdit.MyLabelControl();
this.checkEditContinueOnErrors = new ExtendedControlsLibrary.Skinning.CustomCheckEdit.MyCheckEdit();
this.translationDelayTextEdit = new ExtendedControlsLibrary.Skinning.CustomTextEdit.MyTextEdit();
this.label2 = new ExtendedControlsLibrary.Skinning.CustomLabelEdit.MyLabelControl();
this.wordsToKeepTabPage = new ExtendedControlsLibrary.Skinning.CustomTabControl.MyXtraTabPage();
this.buttonAddDefaultWordsToKeep = new ExtendedControlsLibrary.Skinning.CustomButton.MySimpleButton();
this.labelControl4 = new ExtendedControlsLibrary.Skinning.CustomLabelEdit.MyLabelControl();
this.wordsToProtectMemoEdit = new ExtendedControlsLibrary.Skinning.CustomMemoEdit.MyMemoEdit();
this.labelControl5 = new ExtendedControlsLibrary.Skinning.CustomLabelEdit.MyLabelControl();
this.wordsToRemoveTabPage = new ExtendedControlsLibrary.Skinning.CustomTabControl.MyXtraTabPage();
this.myLabelControl1 = new ExtendedControlsLibrary.Skinning.CustomLabelEdit.MyLabelControl();
this.labelControl6 = new ExtendedControlsLibrary.Skinning.CustomLabelEdit.MyLabelControl();
this.wordsToRemoveMemoEdit = new ExtendedControlsLibrary.Skinning.CustomMemoEdit.MyMemoEdit();
this.buttonOK = new ExtendedControlsLibrary.Skinning.CustomButton.MySimpleButton();
this.buttonCancel = new ExtendedControlsLibrary.Skinning.CustomButton.MySimpleButton();
this.myHyperLinkEdit1 = new ExtendedControlsLibrary.Skinning.CustomHyperLinkEdit.MyHyperLinkEdit();
((System.ComponentModel.ISupportInitialize)(this.panelControl1)).BeginInit();
this.panelControl1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.xtraTabControl1)).BeginInit();
this.xtraTabControl1.SuspendLayout();
this.engineTabPage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.appIDMemoEdit.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.appIDLinkControl.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.engineComboBox.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.appIDTextEdit.Properties)).BeginInit();
this.settingsTabPage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.checkEditContinueOnErrors.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.translationDelayTextEdit.Properties)).BeginInit();
this.wordsToKeepTabPage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.wordsToProtectMemoEdit.Properties)).BeginInit();
this.wordsToRemoveTabPage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.wordsToRemoveMemoEdit.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.myHyperLinkEdit1.Properties)).BeginInit();
this.SuspendLayout();
//
// panelControl1
//
this.panelControl1.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder;
this.panelControl1.Controls.Add(this.xtraTabControl1);
this.panelControl1.Controls.Add(this.buttonOK);
this.panelControl1.Controls.Add(this.buttonCancel);
this.panelControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.panelControl1.Location = new System.Drawing.Point(0, 0);
this.panelControl1.Name = "panelControl1";
this.panelControl1.Padding = new System.Windows.Forms.Padding(3);
this.panelControl1.Size = new System.Drawing.Size(461, 419);
this.panelControl1.TabIndex = 0;
//
// xtraTabControl1
//
this.xtraTabControl1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.xtraTabControl1.AppearancePage.Header.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.xtraTabControl1.AppearancePage.Header.Options.UseFont = true;
this.xtraTabControl1.Location = new System.Drawing.Point(6, 6);
this.xtraTabControl1.Name = "xtraTabControl1";
this.xtraTabControl1.SelectedTabPage = this.engineTabPage;
this.xtraTabControl1.Size = new System.Drawing.Size(449, 375);
this.xtraTabControl1.TabIndex = 0;
this.xtraTabControl1.TabPages.AddRange(new DevExpress.XtraTab.XtraTabPage[] {
this.engineTabPage,
this.settingsTabPage,
this.wordsToKeepTabPage,
this.wordsToRemoveTabPage});
//
// engineTabPage
//
this.engineTabPage.Controls.Add(this.appIDMemoEdit);
this.engineTabPage.Controls.Add(this.myHyperLinkEdit1);
this.engineTabPage.Controls.Add(this.appIDLinkControl);
this.engineTabPage.Controls.Add(this.labelControl2);
this.engineTabPage.Controls.Add(this.engineComboBox);
this.engineTabPage.Controls.Add(this.appIDLabel);
this.engineTabPage.Controls.Add(this.appIDTextEdit);
this.engineTabPage.Name = "engineTabPage";
this.engineTabPage.Padding = new System.Windows.Forms.Padding(9);
this.engineTabPage.Size = new System.Drawing.Size(443, 343);
this.engineTabPage.Text = "Service";
//
// appIDMemoEdit
//
this.appIDMemoEdit.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.appIDMemoEdit.CueText = null;
this.appIDMemoEdit.Location = new System.Drawing.Point(12, 154);
this.appIDMemoEdit.Name = "appIDMemoEdit";
this.appIDMemoEdit.Properties.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.appIDMemoEdit.Properties.Appearance.Options.UseFont = true;
this.appIDMemoEdit.Properties.NullValuePrompt = null;
this.appIDMemoEdit.Size = new System.Drawing.Size(419, 149);
this.appIDMemoEdit.TabIndex = 5;
//
// appIDLinkControl
//
this.appIDLinkControl.AllowAutoWidth = true;
this.appIDLinkControl.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.appIDLinkControl.CausesValidation = false;
this.appIDLinkControl.EditValue = "How to get an API key?";
this.appIDLinkControl.Location = new System.Drawing.Point(12, 62);
this.appIDLinkControl.Name = "appIDLinkControl";
this.appIDLinkControl.Properties.AllowFocused = false;
this.appIDLinkControl.Properties.Appearance.BackColor = System.Drawing.Color.Transparent;
this.appIDLinkControl.Properties.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.appIDLinkControl.Properties.Appearance.Options.UseBackColor = true;
this.appIDLinkControl.Properties.Appearance.Options.UseFont = true;
this.appIDLinkControl.Properties.Appearance.Options.UseTextOptions = true;
this.appIDLinkControl.Properties.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.appIDLinkControl.Properties.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder;
this.appIDLinkControl.Properties.ReadOnly = true;
this.appIDLinkControl.Size = new System.Drawing.Size(419, 22);
this.appIDLinkControl.TabIndex = 2;
this.appIDLinkControl.TabStop = false;
this.appIDLinkControl.OpenLink += new DevExpress.XtraEditors.Controls.OpenLinkEventHandler(this.appIDLinkControl_OpenLink);
//
// labelControl2
//
this.labelControl2.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.labelControl2.Appearance.Options.UseFont = true;
this.labelControl2.Location = new System.Drawing.Point(12, 12);
this.labelControl2.Name = "labelControl2";
this.labelControl2.Size = new System.Drawing.Size(151, 17);
this.labelControl2.TabIndex = 0;
this.labelControl2.Text = "Translation service to use:";
//
// engineComboBox
//
this.engineComboBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.engineComboBox.CueText = null;
this.engineComboBox.Location = new System.Drawing.Point(12, 32);
this.engineComboBox.Name = "engineComboBox";
this.engineComboBox.Properties.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.engineComboBox.Properties.Appearance.Options.UseFont = true;
this.engineComboBox.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)});
this.engineComboBox.Properties.NullValuePrompt = null;
this.engineComboBox.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
this.engineComboBox.Size = new System.Drawing.Size(419, 24);
this.engineComboBox.TabIndex = 1;
this.engineComboBox.SelectedIndexChanged += new System.EventHandler(this.engineComboBox_SelectedIndexChanged);
//
// appIDLabel
//
this.appIDLabel.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.appIDLabel.Appearance.Options.UseFont = true;
this.appIDLabel.Location = new System.Drawing.Point(12, 104);
this.appIDLabel.Name = "appIDLabel";
this.appIDLabel.Size = new System.Drawing.Size(107, 17);
this.appIDLabel.TabIndex = 3;
this.appIDLabel.Text = "{0} for this service:";
//
// appIDTextEdit
//
this.appIDTextEdit.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.appIDTextEdit.Bold = false;
this.appIDTextEdit.CueText = null;
this.appIDTextEdit.Location = new System.Drawing.Point(12, 124);
this.appIDTextEdit.MaximumSize = new System.Drawing.Size(0, 24);
this.appIDTextEdit.MinimumSize = new System.Drawing.Size(0, 24);
this.appIDTextEdit.Name = "appIDTextEdit";
this.appIDTextEdit.Properties.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.appIDTextEdit.Properties.Appearance.Options.UseFont = true;
this.appIDTextEdit.Properties.Mask.EditMask = null;
this.appIDTextEdit.Properties.MaxLength = 400;
this.appIDTextEdit.Properties.NullValuePrompt = null;
this.appIDTextEdit.Size = new System.Drawing.Size(419, 24);
this.appIDTextEdit.TabIndex = 4;
this.appIDTextEdit.EditValueChanged += new System.EventHandler(this.translationDelayTextEdit_EditValueChanged);
//
// settingsTabPage
//
this.settingsTabPage.Controls.Add(this.labelControl1);
this.settingsTabPage.Controls.Add(this.checkEditContinueOnErrors);
this.settingsTabPage.Controls.Add(this.translationDelayTextEdit);
this.settingsTabPage.Controls.Add(this.label2);
this.settingsTabPage.Name = "settingsTabPage";
this.settingsTabPage.Padding = new System.Windows.Forms.Padding(9);
this.settingsTabPage.Size = new System.Drawing.Size(443, 343);
this.settingsTabPage.Text = "Settings";
//
// labelControl1
//
this.labelControl1.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.labelControl1.Appearance.Options.UseFont = true;
this.labelControl1.Location = new System.Drawing.Point(277, 43);
this.labelControl1.Name = "labelControl1";
this.labelControl1.Size = new System.Drawing.Size(17, 17);
this.labelControl1.TabIndex = 3;
this.labelControl1.Text = "ms";
//
// checkEditContinueOnErrors
//
this.checkEditContinueOnErrors.Location = new System.Drawing.Point(12, 12);
this.checkEditContinueOnErrors.Name = "checkEditContinueOnErrors";
this.checkEditContinueOnErrors.Properties.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.checkEditContinueOnErrors.Properties.Appearance.Options.UseFont = true;
this.checkEditContinueOnErrors.Properties.AutoWidth = true;
this.checkEditContinueOnErrors.Properties.Caption = "Continue on errors";
this.checkEditContinueOnErrors.Size = new System.Drawing.Size(132, 21);
this.checkEditContinueOnErrors.TabIndex = 0;
//
// translationDelayTextEdit
//
this.translationDelayTextEdit.Bold = false;
this.translationDelayTextEdit.CueText = null;
this.translationDelayTextEdit.Location = new System.Drawing.Point(204, 39);
this.translationDelayTextEdit.MaximumSize = new System.Drawing.Size(0, 24);
this.translationDelayTextEdit.MinimumSize = new System.Drawing.Size(0, 24);
this.translationDelayTextEdit.Name = "translationDelayTextEdit";
this.translationDelayTextEdit.Properties.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.translationDelayTextEdit.Properties.Appearance.Options.UseFont = true;
this.translationDelayTextEdit.Properties.Mask.EditMask = null;
this.translationDelayTextEdit.Properties.MaxLength = 5;
this.translationDelayTextEdit.Properties.NullValuePrompt = null;
this.translationDelayTextEdit.Size = new System.Drawing.Size(67, 24);
this.translationDelayTextEdit.TabIndex = 2;
this.translationDelayTextEdit.EditValueChanged += new System.EventHandler(this.translationDelayTextEdit_EditValueChanged);
//
// label2
//
this.label2.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.label2.Appearance.Options.UseFont = true;
this.label2.Location = new System.Drawing.Point(14, 43);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(184, 17);
this.label2.TabIndex = 1;
this.label2.Text = "Delay between two translations:";
//
// wordsToKeepTabPage
//
this.wordsToKeepTabPage.Controls.Add(this.buttonAddDefaultWordsToKeep);
this.wordsToKeepTabPage.Controls.Add(this.labelControl4);
this.wordsToKeepTabPage.Controls.Add(this.wordsToProtectMemoEdit);
this.wordsToKeepTabPage.Controls.Add(this.labelControl5);
this.wordsToKeepTabPage.Name = "wordsToKeepTabPage";
this.wordsToKeepTabPage.Padding = new System.Windows.Forms.Padding(9);
this.wordsToKeepTabPage.Size = new System.Drawing.Size(443, 343);
this.wordsToKeepTabPage.Text = "Words to keep";
//
// buttonAddDefaultWordsToKeep
//
this.buttonAddDefaultWordsToKeep.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonAddDefaultWordsToKeep.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.buttonAddDefaultWordsToKeep.Appearance.Options.UseFont = true;
this.buttonAddDefaultWordsToKeep.Location = new System.Drawing.Point(336, 262);
this.buttonAddDefaultWordsToKeep.Name = "buttonAddDefaultWordsToKeep";
this.buttonAddDefaultWordsToKeep.Size = new System.Drawing.Size(95, 28);
this.buttonAddDefaultWordsToKeep.TabIndex = 3;
this.buttonAddDefaultWordsToKeep.Text = "Add defaults";
this.buttonAddDefaultWordsToKeep.WantDrawFocusRectangle = true;
this.buttonAddDefaultWordsToKeep.Click += new System.EventHandler(this.buttonAddDefaultWordsToKeep_Click);
//
// labelControl4
//
this.labelControl4.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.labelControl4.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.labelControl4.Appearance.ForeColor = System.Drawing.SystemColors.GrayText;
this.labelControl4.Appearance.Options.UseFont = true;
this.labelControl4.Appearance.Options.UseForeColor = true;
this.labelControl4.Appearance.Options.UseTextOptions = true;
this.labelControl4.Appearance.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;
this.labelControl4.AutoSizeMode = DevExpress.XtraEditors.LabelAutoSizeMode.None;
this.labelControl4.Location = new System.Drawing.Point(12, 296);
this.labelControl4.Name = "labelControl4";
this.labelControl4.Size = new System.Drawing.Size(419, 35);
this.labelControl4.TabIndex = 1;
this.labelControl4.Text = "(One word/sentence per line. [WC] prefix for wildcards, [RX] prefix for Regular E" +
"xpressions)";
//
// wordsToProtectMemoEdit
//
this.wordsToProtectMemoEdit.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.wordsToProtectMemoEdit.CueText = null;
this.wordsToProtectMemoEdit.Location = new System.Drawing.Point(12, 32);
this.wordsToProtectMemoEdit.Name = "wordsToProtectMemoEdit";
this.wordsToProtectMemoEdit.Properties.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.wordsToProtectMemoEdit.Properties.Appearance.Options.UseFont = true;
this.wordsToProtectMemoEdit.Properties.NullValuePrompt = null;
this.wordsToProtectMemoEdit.Size = new System.Drawing.Size(419, 224);
this.wordsToProtectMemoEdit.TabIndex = 0;
//
// labelControl5
//
this.labelControl5.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.labelControl5.Appearance.Options.UseFont = true;
this.labelControl5.Location = new System.Drawing.Point(12, 12);
this.labelControl5.Name = "labelControl5";
this.labelControl5.Size = new System.Drawing.Size(211, 17);
this.labelControl5.TabIndex = 2;
this.labelControl5.Text = "Never translate the following words:";
//
// wordsToRemoveTabPage
//
this.wordsToRemoveTabPage.Controls.Add(this.myLabelControl1);
this.wordsToRemoveTabPage.Controls.Add(this.labelControl6);
this.wordsToRemoveTabPage.Controls.Add(this.wordsToRemoveMemoEdit);
this.wordsToRemoveTabPage.Name = "wordsToRemoveTabPage";
this.wordsToRemoveTabPage.Padding = new System.Windows.Forms.Padding(9);
this.wordsToRemoveTabPage.Size = new System.Drawing.Size(443, 343);
this.wordsToRemoveTabPage.Text = "Words to remove";
//
// myLabelControl1
//
this.myLabelControl1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.myLabelControl1.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.myLabelControl1.Appearance.ForeColor = System.Drawing.SystemColors.GrayText;
this.myLabelControl1.Appearance.Options.UseFont = true;
this.myLabelControl1.Appearance.Options.UseForeColor = true;
this.myLabelControl1.Appearance.Options.UseTextOptions = true;
this.myLabelControl1.Appearance.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;
this.myLabelControl1.AutoSizeMode = DevExpress.XtraEditors.LabelAutoSizeMode.None;
this.myLabelControl1.Location = new System.Drawing.Point(12, 296);
this.myLabelControl1.Name = "myLabelControl1";
this.myLabelControl1.Size = new System.Drawing.Size(419, 35);
this.myLabelControl1.TabIndex = 4;
this.myLabelControl1.Text = "(One word/sentence per line. [WC] prefix for wildcards, [RX] prefix for Regular E" +
"xpressions)";
//
// labelControl6
//
this.labelControl6.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.labelControl6.Appearance.Options.UseFont = true;
this.labelControl6.Location = new System.Drawing.Point(12, 12);
this.labelControl6.Name = "labelControl6";
this.labelControl6.Size = new System.Drawing.Size(277, 17);
this.labelControl6.TabIndex = 3;
this.labelControl6.Text = "Remove the following words before translating:";
//
// wordsToRemoveMemoEdit
//
this.wordsToRemoveMemoEdit.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.wordsToRemoveMemoEdit.CueText = null;
this.wordsToRemoveMemoEdit.Location = new System.Drawing.Point(12, 32);
this.wordsToRemoveMemoEdit.Name = "wordsToRemoveMemoEdit";
this.wordsToRemoveMemoEdit.Properties.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.wordsToRemoveMemoEdit.Properties.Appearance.Options.UseFont = true;
this.wordsToRemoveMemoEdit.Properties.NullValuePrompt = null;
this.wordsToRemoveMemoEdit.Size = new System.Drawing.Size(419, 258);
this.wordsToRemoveMemoEdit.TabIndex = 0;
//
// buttonOK
//
this.buttonOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonOK.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.buttonOK.Appearance.Options.UseFont = true;
this.buttonOK.DialogResult = System.Windows.Forms.DialogResult.OK;
this.buttonOK.Location = new System.Drawing.Point(299, 385);
this.buttonOK.Name = "buttonOK";
this.buttonOK.Size = new System.Drawing.Size(75, 28);
this.buttonOK.TabIndex = 1;
this.buttonOK.Text = "OK";
this.buttonOK.WantDrawFocusRectangle = true;
this.buttonOK.Click += new System.EventHandler(this.buttonOK_Click);
//
// buttonCancel
//
this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonCancel.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.buttonCancel.Appearance.Options.UseFont = true;
this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.buttonCancel.Location = new System.Drawing.Point(380, 385);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(75, 28);
this.buttonCancel.TabIndex = 2;
this.buttonCancel.Text = "Cancel";
this.buttonCancel.WantDrawFocusRectangle = true;
//
// myHyperLinkEdit1
//
this.myHyperLinkEdit1.AllowAutoWidth = true;
this.myHyperLinkEdit1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.myHyperLinkEdit1.CausesValidation = false;
this.myHyperLinkEdit1.EditValue = "JSON validator";
this.myHyperLinkEdit1.Location = new System.Drawing.Point(330, 309);
this.myHyperLinkEdit1.Name = "myHyperLinkEdit1";
this.myHyperLinkEdit1.Properties.AllowFocused = false;
this.myHyperLinkEdit1.Properties.Appearance.BackColor = System.Drawing.Color.Transparent;
this.myHyperLinkEdit1.Properties.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.myHyperLinkEdit1.Properties.Appearance.Options.UseBackColor = true;
this.myHyperLinkEdit1.Properties.Appearance.Options.UseFont = true;
this.myHyperLinkEdit1.Properties.Appearance.Options.UseTextOptions = true;
this.myHyperLinkEdit1.Properties.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far;
this.myHyperLinkEdit1.Properties.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder;
this.myHyperLinkEdit1.Properties.ReadOnly = true;
this.myHyperLinkEdit1.Size = new System.Drawing.Size(101, 22);
this.myHyperLinkEdit1.TabIndex = 2;
this.myHyperLinkEdit1.TabStop = false;
this.myHyperLinkEdit1.OpenLink += new DevExpress.XtraEditors.Controls.OpenLinkEventHandler(this.myHyperLinkEdit1_OpenLink);
//
// TranslateOptionsForm
//
this.AcceptButton = this.buttonOK;
this.Appearance.Options.UseFont = true;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None;
this.CancelButton = this.buttonCancel;
this.ClientSize = new System.Drawing.Size(461, 419);
this.Controls.Add(this.panelControl1);
this.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.MinimumSize = new System.Drawing.Size(398, 373);
this.Name = "TranslateOptionsForm";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Translation settings";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.AutoTranslateOptionsForm_FormClosing);
this.Load += new System.EventHandler(this.AutoTranslateOptionsForm_Load);
this.Shown += new System.EventHandler(this.TranslateOptionsForm_Shown);
((System.ComponentModel.ISupportInitialize)(this.panelControl1)).EndInit();
this.panelControl1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.xtraTabControl1)).EndInit();
this.xtraTabControl1.ResumeLayout(false);
this.engineTabPage.ResumeLayout(false);
this.engineTabPage.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.appIDMemoEdit.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.appIDLinkControl.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.engineComboBox.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.appIDTextEdit.Properties)).EndInit();
this.settingsTabPage.ResumeLayout(false);
this.settingsTabPage.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.checkEditContinueOnErrors.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.translationDelayTextEdit.Properties)).EndInit();
this.wordsToKeepTabPage.ResumeLayout(false);
this.wordsToKeepTabPage.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.wordsToProtectMemoEdit.Properties)).EndInit();
this.wordsToRemoveTabPage.ResumeLayout(false);
this.wordsToRemoveTabPage.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.wordsToRemoveMemoEdit.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.myHyperLinkEdit1.Properties)).EndInit();
this.ResumeLayout(false);
}
#endregion
private ExtendedControlsLibrary.Skinning.CustomPanel.MyPanelControl panelControl1;
private ExtendedControlsLibrary.Skinning.CustomButton.MySimpleButton buttonOK;
private ExtendedControlsLibrary.Skinning.CustomButton.MySimpleButton buttonCancel;
private ExtendedControlsLibrary.Skinning.CustomTextEdit.MyTextEdit translationDelayTextEdit;
private ExtendedControlsLibrary.Skinning.CustomCheckEdit.MyCheckEdit checkEditContinueOnErrors;
private ExtendedControlsLibrary.Skinning.CustomLabelEdit.MyLabelControl label2;
private ExtendedControlsLibrary.Skinning.CustomLabelEdit.MyLabelControl labelControl1;
private ExtendedControlsLibrary.Skinning.CustomComboBoxEdit.MyComboBoxEdit engineComboBox;
private ExtendedControlsLibrary.Skinning.CustomLabelEdit.MyLabelControl labelControl2;
private ExtendedControlsLibrary.Skinning.CustomTabControl.MyXtraTabControl xtraTabControl1;
private ExtendedControlsLibrary.Skinning.CustomTabControl.MyXtraTabPage settingsTabPage;
private ExtendedControlsLibrary.Skinning.CustomTabControl.MyXtraTabPage wordsToKeepTabPage;
private ExtendedControlsLibrary.Skinning.CustomMemoEdit.MyMemoEdit wordsToProtectMemoEdit;
private ExtendedControlsLibrary.Skinning.CustomLabelEdit.MyLabelControl labelControl4;
private ExtendedControlsLibrary.Skinning.CustomTabControl.MyXtraTabPage wordsToRemoveTabPage;
private ExtendedControlsLibrary.Skinning.CustomMemoEdit.MyMemoEdit wordsToRemoveMemoEdit;
private ExtendedControlsLibrary.Skinning.CustomLabelEdit.MyLabelControl labelControl5;
private ExtendedControlsLibrary.Skinning.CustomLabelEdit.MyLabelControl labelControl6;
private ExtendedControlsLibrary.Skinning.CustomButton.MySimpleButton buttonAddDefaultWordsToKeep;
private ExtendedControlsLibrary.Skinning.CustomLabelEdit.MyLabelControl appIDLabel;
private ExtendedControlsLibrary.Skinning.CustomTextEdit.MyTextEdit appIDTextEdit;
private ExtendedControlsLibrary.Skinning.CustomHyperLinkEdit.MyHyperLinkEdit appIDLinkControl;
private ExtendedControlsLibrary.Skinning.CustomTabControl.MyXtraTabPage engineTabPage;
private ExtendedControlsLibrary.Skinning.CustomLabelEdit.MyLabelControl myLabelControl1;
private ExtendedControlsLibrary.Skinning.CustomMemoEdit.MyMemoEdit appIDMemoEdit;
private ExtendedControlsLibrary.Skinning.CustomHyperLinkEdit.MyHyperLinkEdit myHyperLinkEdit1;
}
}
| |
// 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.Reflection;
using System.Collections.Generic;
using System.Reflection.Runtime.General;
using System.Reflection.Runtime.TypeInfos;
using System.Reflection.Runtime.TypeInfos.NativeFormat;
using System.Reflection.Runtime.Assemblies;
using System.Reflection.Runtime.MethodInfos;
using System.Reflection.Runtime.MethodInfos.NativeFormat;
#if ECMA_METADATA_SUPPORT
using System.Reflection.Runtime.TypeInfos.EcmaFormat;
using System.Reflection.Runtime.MethodInfos.EcmaFormat;
#endif
using System.Reflection.Runtime.TypeParsing;
using System.Reflection.Runtime.CustomAttributes;
using Internal.Metadata.NativeFormat;
using Internal.Runtime.Augments;
namespace Internal.Reflection.Core.Execution
{
//
// This singleton class acts as an entrypoint from System.Private.Reflection.Execution to System.Private.Reflection.Core.
//
public sealed class ExecutionDomain
{
internal ExecutionDomain(ReflectionDomainSetup executionDomainSetup, ExecutionEnvironment executionEnvironment)
{
ExecutionEnvironment = executionEnvironment;
ReflectionDomainSetup = executionDomainSetup;
}
//
// Retrieves a type by name. Helper to implement Type.GetType();
//
public Type GetType(String typeName, Func<AssemblyName, Assembly> assemblyResolver, Func<Assembly, string, bool, Type> typeResolver, bool throwOnError, bool ignoreCase, IList<string> defaultAssemblyNames)
{
if (typeName == null)
throw new ArgumentNullException();
if (typeName.Length == 0)
{
if (throwOnError)
throw new TypeLoadException(SR.Arg_TypeLoadNullStr);
else
return null;
}
TypeName parsedName = TypeParser.ParseAssemblyQualifiedTypeName(typeName, throwOnError: throwOnError);
if (parsedName == null)
return null;
CoreAssemblyResolver coreAssemblyResolver = CreateCoreAssemblyResolver(assemblyResolver);
CoreTypeResolver coreTypeResolver = CreateCoreTypeResolver(typeResolver, defaultAssemblyNames, throwOnError: throwOnError, ignoreCase: ignoreCase);
GetTypeOptions getTypeOptions = new GetTypeOptions(coreAssemblyResolver, coreTypeResolver, throwOnError: throwOnError, ignoreCase: ignoreCase);
return parsedName.ResolveType(null, getTypeOptions);
}
private static CoreAssemblyResolver CreateCoreAssemblyResolver(Func<AssemblyName, Assembly> assemblyResolver)
{
if (assemblyResolver == null)
{
return RuntimeAssembly.GetRuntimeAssemblyIfExists;
}
else
{
return delegate (RuntimeAssemblyName runtimeAssemblyName)
{
AssemblyName assemblyName = runtimeAssemblyName.ToAssemblyName();
Assembly assembly = assemblyResolver(assemblyName);
return assembly;
};
}
}
private static CoreTypeResolver CreateCoreTypeResolver(Func<Assembly, string, bool, Type> typeResolver, IList<string> defaultAssemblyNames, bool throwOnError, bool ignoreCase)
{
if (typeResolver == null)
{
return delegate (Assembly containingAssemblyIfAny, string coreTypeName)
{
if (containingAssemblyIfAny != null)
{
return containingAssemblyIfAny.GetTypeCore(coreTypeName, ignoreCase: ignoreCase);
}
else
{
foreach (string defaultAssemblyName in defaultAssemblyNames)
{
RuntimeAssemblyName runtimeAssemblyName = AssemblyNameParser.Parse(defaultAssemblyName);
RuntimeAssembly defaultAssembly = RuntimeAssembly.GetRuntimeAssembly(runtimeAssemblyName);
Type resolvedType = defaultAssembly.GetTypeCore(coreTypeName, ignoreCase: ignoreCase);
if (resolvedType != null)
return resolvedType;
}
if (throwOnError && defaultAssemblyNames.Count > 0)
{
// Though we don't have to throw a TypeLoadException exception (that's our caller's job), we can throw a more specific exception than he would so just do it.
throw Helpers.CreateTypeLoadException(coreTypeName, defaultAssemblyNames[0]);
}
return null;
}
};
}
else
{
return delegate (Assembly containingAssemblyIfAny, string coreTypeName)
{
string escapedName = coreTypeName.EscapeTypeNameIdentifier();
Type type = typeResolver(containingAssemblyIfAny, escapedName, ignoreCase);
return type;
};
}
}
//
// Retrieves the MethodBase for a given method handle. Helper to implement Delegate.GetMethodInfo()
//
public MethodBase GetMethod(RuntimeTypeHandle declaringTypeHandle, QMethodDefinition methodHandle, RuntimeTypeHandle[] genericMethodTypeArgumentHandles)
{
RuntimeTypeInfo contextTypeInfo = declaringTypeHandle.GetTypeForRuntimeTypeHandle();
RuntimeNamedMethodInfo runtimeNamedMethodInfo = null;
if (methodHandle.IsNativeFormatMetadataBased)
{
MethodHandle nativeFormatMethodHandle = methodHandle.NativeFormatHandle;
NativeFormatRuntimeNamedTypeInfo definingTypeInfo = contextTypeInfo.AnchoringTypeDefinitionForDeclaredMembers.CastToNativeFormatRuntimeNamedTypeInfo();
MetadataReader reader = definingTypeInfo.Reader;
if (nativeFormatMethodHandle.IsConstructor(reader))
{
return RuntimePlainConstructorInfo<NativeFormatMethodCommon>.GetRuntimePlainConstructorInfo(new NativeFormatMethodCommon(nativeFormatMethodHandle, definingTypeInfo, contextTypeInfo));
}
else
{
// RuntimeMethodHandles always yield methods whose ReflectedType is the DeclaringType.
RuntimeTypeInfo reflectedType = contextTypeInfo;
runtimeNamedMethodInfo = RuntimeNamedMethodInfo<NativeFormatMethodCommon>.GetRuntimeNamedMethodInfo(new NativeFormatMethodCommon(nativeFormatMethodHandle, definingTypeInfo, contextTypeInfo), reflectedType);
}
}
#if ECMA_METADATA_SUPPORT
else
{
System.Reflection.Metadata.MethodDefinitionHandle ecmaFormatMethodHandle = methodHandle.EcmaFormatHandle;
EcmaFormatRuntimeNamedTypeInfo definingEcmaTypeInfo = contextTypeInfo.AnchoringTypeDefinitionForDeclaredMembers.CastToEcmaFormatRuntimeNamedTypeInfo();
System.Reflection.Metadata.MetadataReader reader = definingEcmaTypeInfo.Reader;
if (ecmaFormatMethodHandle.IsConstructor(reader))
{
return RuntimePlainConstructorInfo<EcmaFormatMethodCommon>.GetRuntimePlainConstructorInfo(new EcmaFormatMethodCommon(ecmaFormatMethodHandle, definingEcmaTypeInfo, contextTypeInfo));
}
else
{
// RuntimeMethodHandles always yield methods whose ReflectedType is the DeclaringType.
RuntimeTypeInfo reflectedType = contextTypeInfo;
runtimeNamedMethodInfo = RuntimeNamedMethodInfo<EcmaFormatMethodCommon>.GetRuntimeNamedMethodInfo(new EcmaFormatMethodCommon(ecmaFormatMethodHandle, definingEcmaTypeInfo, contextTypeInfo), reflectedType);
}
}
#endif
if (!runtimeNamedMethodInfo.IsGenericMethod || genericMethodTypeArgumentHandles == null)
{
return runtimeNamedMethodInfo;
}
else
{
RuntimeTypeInfo[] genericTypeArguments = new RuntimeTypeInfo[genericMethodTypeArgumentHandles.Length];
for (int i = 0; i < genericMethodTypeArgumentHandles.Length; i++)
{
genericTypeArguments[i] = genericMethodTypeArgumentHandles[i].GetTypeForRuntimeTypeHandle();
}
return RuntimeConstructedGenericMethodInfo.GetRuntimeConstructedGenericMethodInfo(runtimeNamedMethodInfo, genericTypeArguments);
}
}
//=======================================================================================
// This group of methods jointly service the Type.GetTypeFromHandle() path. The caller
// is responsible for analyzing the RuntimeTypeHandle to figure out which flavor to call.
//=======================================================================================
public Type GetNamedTypeForHandle(RuntimeTypeHandle typeHandle, bool isGenericTypeDefinition)
{
QTypeDefinition qTypeDefinition;
if (ExecutionEnvironment.TryGetMetadataForNamedType(typeHandle, out qTypeDefinition))
{
#if ECMA_METADATA_SUPPORT
if (qTypeDefinition.IsNativeFormatMetadataBased)
#endif
{
return qTypeDefinition.NativeFormatHandle.GetNamedType(qTypeDefinition.NativeFormatReader, typeHandle);
}
#if ECMA_METADATA_SUPPORT
else
{
return System.Reflection.Runtime.TypeInfos.EcmaFormat.EcmaFormatRuntimeNamedTypeInfo.GetRuntimeNamedTypeInfo(qTypeDefinition.EcmaFormatReader,
qTypeDefinition.EcmaFormatHandle,
typeHandle);
}
#endif
}
else
{
if (ExecutionEnvironment.IsReflectionBlocked(typeHandle))
{
return RuntimeBlockedTypeInfo.GetRuntimeBlockedTypeInfo(typeHandle, isGenericTypeDefinition);
}
else
{
return RuntimeNoMetadataNamedTypeInfo.GetRuntimeNoMetadataNamedTypeInfo(typeHandle, isGenericTypeDefinition);
}
}
}
public Type GetArrayTypeForHandle(RuntimeTypeHandle typeHandle)
{
RuntimeTypeHandle elementTypeHandle;
if (!ExecutionEnvironment.TryGetArrayTypeElementType(typeHandle, out elementTypeHandle))
throw CreateMissingMetadataException((Type)null);
return elementTypeHandle.GetTypeForRuntimeTypeHandle().GetArrayType(typeHandle);
}
public Type GetMdArrayTypeForHandle(RuntimeTypeHandle typeHandle, int rank)
{
RuntimeTypeHandle elementTypeHandle;
if (!ExecutionEnvironment.TryGetArrayTypeElementType(typeHandle, out elementTypeHandle))
throw CreateMissingMetadataException((Type)null);
return elementTypeHandle.GetTypeForRuntimeTypeHandle().GetMultiDimArrayType(rank, typeHandle);
}
public Type GetPointerTypeForHandle(RuntimeTypeHandle typeHandle)
{
RuntimeTypeHandle targetTypeHandle;
if (!ExecutionEnvironment.TryGetPointerTypeTargetType(typeHandle, out targetTypeHandle))
throw CreateMissingMetadataException((Type)null);
return targetTypeHandle.GetTypeForRuntimeTypeHandle().GetPointerType(typeHandle);
}
public Type GetByRefTypeForHandle(RuntimeTypeHandle typeHandle)
{
RuntimeTypeHandle targetTypeHandle;
if (!ExecutionEnvironment.TryGetByRefTypeTargetType(typeHandle, out targetTypeHandle))
throw CreateMissingMetadataException((Type)null);
return targetTypeHandle.GetTypeForRuntimeTypeHandle().GetByRefType(typeHandle);
}
public Type GetConstructedGenericTypeForHandle(RuntimeTypeHandle typeHandle)
{
RuntimeTypeHandle genericTypeDefinitionHandle;
RuntimeTypeHandle[] genericTypeArgumentHandles;
genericTypeDefinitionHandle = RuntimeAugments.GetGenericInstantiation(typeHandle, out genericTypeArgumentHandles);
// Reflection blocked constructed generic types simply pretend to not be generic
// This is reasonable, as the behavior of reflection blocked types is supposed
// to be that they expose the minimal information about a type that is necessary
// for users of Object.GetType to move from that type to a type that isn't
// reflection blocked. By not revealing that reflection blocked types are generic
// we are making it appear as if implementation detail types exposed to user code
// are all non-generic, which is theoretically possible, and by doing so
// we avoid (in all known circumstances) the very complicated case of representing
// the interfaces, base types, and generic parameter types of reflection blocked
// generic type definitions.
if (ExecutionEnvironment.IsReflectionBlocked(genericTypeDefinitionHandle))
{
return RuntimeBlockedTypeInfo.GetRuntimeBlockedTypeInfo(typeHandle, isGenericTypeDefinition: false);
}
RuntimeTypeInfo genericTypeDefinition = genericTypeDefinitionHandle.GetTypeForRuntimeTypeHandle();
int count = genericTypeArgumentHandles.Length;
RuntimeTypeInfo[] genericTypeArguments = new RuntimeTypeInfo[count];
for (int i = 0; i < count; i++)
{
genericTypeArguments[i] = genericTypeArgumentHandles[i].GetTypeForRuntimeTypeHandle();
}
return genericTypeDefinition.GetConstructedGenericType(genericTypeArguments, typeHandle);
}
//=======================================================================================
// MissingMetadataExceptions.
//=======================================================================================
public Exception CreateMissingMetadataException(Type pertainant)
{
return this.ReflectionDomainSetup.CreateMissingMetadataException(pertainant);
}
public Exception CreateMissingMetadataException(TypeInfo pertainant)
{
return this.ReflectionDomainSetup.CreateMissingMetadataException(pertainant);
}
public Exception CreateMissingMetadataException(TypeInfo pertainant, string nestedTypeName)
{
return this.ReflectionDomainSetup.CreateMissingMetadataException(pertainant, nestedTypeName);
}
public Exception CreateNonInvokabilityException(MemberInfo pertainant)
{
return this.ReflectionDomainSetup.CreateNonInvokabilityException(pertainant);
}
public Exception CreateMissingArrayTypeException(Type elementType, bool isMultiDim, int rank)
{
return ReflectionDomainSetup.CreateMissingArrayTypeException(elementType, isMultiDim, rank);
}
public Exception CreateMissingConstructedGenericTypeException(Type genericTypeDefinition, Type[] genericTypeArguments)
{
return ReflectionDomainSetup.CreateMissingConstructedGenericTypeException(genericTypeDefinition, genericTypeArguments);
}
//=======================================================================================
// Miscellaneous.
//=======================================================================================
public RuntimeTypeHandle GetTypeHandleIfAvailable(Type type)
{
if (!type.IsRuntimeImplemented())
return default(RuntimeTypeHandle);
RuntimeTypeInfo runtimeType = type.CastToRuntimeTypeInfo();
if (runtimeType == null)
return default(RuntimeTypeHandle);
return runtimeType.InternalTypeHandleIfAvailable;
}
public bool SupportsReflection(Type type)
{
if (!type.IsRuntimeImplemented())
return false;
RuntimeTypeInfo runtimeType = type.CastToRuntimeTypeInfo();
if (null == runtimeType.InternalNameIfAvailable)
return false;
if (ExecutionEnvironment.IsReflectionBlocked(type.TypeHandle))
{
// The type is an internal framework type and is blocked from reflection
return false;
}
if (runtimeType.InternalFullNameOfAssembly == Internal.Runtime.Augments.RuntimeAugments.HiddenScopeAssemblyName)
{
// The type is an internal framework type but is reflectable for internal class library use
// where we make the type appear in a hidden assembly
return false;
}
return true;
}
internal ExecutionEnvironment ExecutionEnvironment { get; }
internal ReflectionDomainSetup ReflectionDomainSetup { get; }
internal IEnumerable<Type> PrimitiveTypes => s_primitiveTypes;
private static readonly Type[] s_primitiveTypes =
{
CommonRuntimeTypes.Boolean,
CommonRuntimeTypes.Char,
CommonRuntimeTypes.SByte,
CommonRuntimeTypes.Byte,
CommonRuntimeTypes.Int16,
CommonRuntimeTypes.UInt16,
CommonRuntimeTypes.Int32,
CommonRuntimeTypes.UInt32,
CommonRuntimeTypes.Int64,
CommonRuntimeTypes.UInt64,
CommonRuntimeTypes.Single,
CommonRuntimeTypes.Double,
CommonRuntimeTypes.IntPtr,
CommonRuntimeTypes.UIntPtr,
};
}
}
| |
using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using AVFoundation;
using CoreMedia;
using Foundation;
using Mitten.Mobile.Devices;
namespace Mitten.Mobile.iOS.Devices
{
/// <summary>
/// Represents the camera for an iOS device.
/// </summary>
/// <remarks>
/// For the camera device we will be using the AV Mitten framework.
/// https://developer.apple.com/library/ios/documentation/AudioVideo/Conceptual/AVFoundationPG/Articles/04_MediaCapture.html
/// </remarks>
public class CameraDevice : ICameraDevice
{
private readonly AVCaptureDevice device;
private AVCaptureSession session;
private AVCaptureStillImageOutput output;
/// <summary>
/// Initializes a new instance of the CameraDevice class.
/// </summary>
internal CameraDevice()
{
this.device = AVCaptureDevice.Devices.SingleOrDefault(device => device.Position == AVCaptureDevicePosition.Back);
}
/// <summary>
/// Gets the current authorization permissions for the camera.
/// </summary>
public CameraPermission GetPermission()
{
if (this.device == null)
{
return CameraPermission.NotAvailable;
}
AVAuthorizationStatus status = this.GetAuthorizationStatus();
if (status == AVAuthorizationStatus.Authorized)
{
return CameraPermission.Authorized;
}
if (status == AVAuthorizationStatus.Denied)
{
return CameraPermission.Denied;
}
if (status == AVAuthorizationStatus.NotDetermined)
{
return CameraPermission.NotDetermined;
}
if (status == AVAuthorizationStatus.Restricted)
{
return CameraPermission.Restricted;
}
throw new CameraPermissionException("Unexpected AVAuthorizationStatus (" + status + ").");
}
/// <summary>
/// Gets whether or not the camera for the current device is on and ready to capture an image.
/// </summary>
public bool IsCameraOn()
{
return this.session != null && this.session.Running;
}
/// <summary>
/// Gets whether or not the camera has a flash.
/// </summary>
/// <returns>True if the camera flash is supported, otherwise false.</returns>
public bool IsFlashAvailable()
{
return
this.device != null &&
this.device.FlashAvailable;
}
/// <summary>
/// Gets the current mode of the camera's flash.
/// </summary>
/// <returns>The current flash mode.</returns>
public CameraFlashMode GetCurrentFlashMode()
{
if (this.device == null || !this.IsFlashAvailable())
{
return CameraFlashMode.NotAvailable;
}
if (this.device.FlashMode == AVCaptureFlashMode.On)
{
return CameraFlashMode.On;
}
if (this.device.FlashMode == AVCaptureFlashMode.Auto)
{
return CameraFlashMode.Auto;
}
if (this.device.FlashMode == AVCaptureFlashMode.Off)
{
return CameraFlashMode.Off;
}
throw new InvalidOperationException("Unexpected AVCaptureDevice.FlashMode (" + this.device.FlashMode + ").");
}
/// <summary>
/// Sets the camera's flash mode.
/// </summary>
/// <param name="flashMode">The mode to set.</param>
public void SetFlashMode(CameraFlashMode flashMode)
{
if (!this.IsFlashAvailable())
{
throw new InvalidOperationException("The camera's flash is not available.");
}
NSError error;
if (!this.device.LockForConfiguration(out error))
{
throw new NSErrorException(error);
}
try
{
if (flashMode == CameraFlashMode.On)
{
this.device.FlashMode = AVCaptureFlashMode.On;
}
else if (flashMode == CameraFlashMode.Auto)
{
this.device.FlashMode = AVCaptureFlashMode.Auto;
}
else if (flashMode == CameraFlashMode.Off)
{
this.device.FlashMode = AVCaptureFlashMode.Off;
}
else
{
throw new ArgumentException("Invalid CameraFlashMode (" + flashMode + ").");
}
}
finally
{
this.device.UnlockForConfiguration();
}
}
/// <summary>
/// Requests user access to the device.
/// </summary>
/// <returns>True if access was granted, otherwise false.</returns>
public Task<bool> RequestAccessAsync()
{
return AVCaptureDevice.RequestAccessForMediaTypeAsync(AVMediaType.Video);
}
/// <summary>
/// Begins starting the camera.
/// </summary>
/// <param name="cameraStarted">Invoked when the camera has been started. An instance of the current session will be passed as the method's argument.</param>
public void BeginStartCamera(Action<object> cameraStarted)
{
if (this.GetPermission() != CameraPermission.Authorized)
{
throw new InvalidOperationException("Camera access not authorized (" + this.GetPermission() + ").");
}
if (this.IsCameraOn())
{
throw new InvalidOperationException("The camera is already on.");
}
this.InitializeSession();
this.session.StartRunning();
cameraStarted(this.session);
}
/// <summary>
/// Stops the camera.
/// </summary>
public void StopCamera()
{
if (!this.IsCameraOn())
{
throw new InvalidOperationException("The camera has not been started.");
}
this.session.StopRunning();
this.CleanUp();
}
/// <summary>
/// Begins capturing an image an image from the camera.
/// </summary>
/// <param name="imageCaptured">Invoked when an image has been captured.</param>
/// <param name="captureFailed">Invoked when a failure occured while trying to capture an image.</param>
public void BeginCaptureImage(Action<byte[]> imageCaptured, Action<string> captureFailed)
{
if (!this.IsCameraOn())
{
throw new InvalidOperationException("The camera has not been started.");
}
AVCaptureConnection connection = this.output.ConnectionFromMediaType(AVMediaType.Video);
this.output.CaptureStillImageAsynchronously(
connection,
(buffer, error) => this.OnImageCaptured(buffer, error, imageCaptured, captureFailed));
}
private void OnImageCaptured(
CMSampleBuffer buffer,
NSError error,
Action<byte[]> imageCaptured,
Action<string> captureFailed)
{
if (error != null)
{
captureFailed(error.LocalizedDescription);
}
else
{
NSData data = AVCaptureStillImageOutput.JpegStillToNSData(buffer);
byte[] image = new byte[data.Length];
Marshal.Copy(
data.Bytes,
image,
0,
Convert.ToInt32(data.Length));
imageCaptured(image);
}
}
private void CleanUp()
{
this.session.Dispose();
this.session = null;
this.output.Dispose();
this.output = null;
}
private void InitializeSession()
{
if (this.session != null)
{
throw new InvalidOperationException("A session is currently active.");
}
this.session = new AVCaptureSession();
this.session.BeginConfiguration();
this.session.SessionPreset = AVCaptureSession.PresetPhoto;
NSError error;
AVCaptureDeviceInput deviceInput = AVCaptureDeviceInput.FromDevice(this.device, out error);
if (deviceInput == null)
{
throw new NSErrorException(error);
}
this.session.AddInput(deviceInput);
this.InitializeOutput();
this.session.AddOutput(this.output);
session.CommitConfiguration();
}
private void InitializeOutput()
{
if (this.output != null)
{
throw new InvalidOperationException("An image output is currently active.");
}
this.output = new AVCaptureStillImageOutput();
this.output.OutputSettings = new NSDictionary(AVVideo.CodecKey, AVVideo.CodecJPEG);
}
private AVAuthorizationStatus GetAuthorizationStatus()
{
return AVCaptureDevice.GetAuthorizationStatus(AVMediaType.Video);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System.Collections.ObjectModel;
using Microsoft.Azure.Management.Network.Fluent.ApplicationGateway.Definition;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.Resource.Definition;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.Resource.Update;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions;
namespace Microsoft.Azure.Management.Network.Fluent
{
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.Network.Fluent.Models;
using Microsoft.Azure.Management.Network.Fluent.VirtualNetworkGatewayConnection.Definition;
using Microsoft.Azure.Management.Network.Fluent.VirtualNetworkGatewayConnection.Update;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using System.Collections.Generic;
/// <summary>
/// Implementation for VirtualNetworkGatewayConnection and its create and update interfaces.
/// </summary>
///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50Lm5ldHdvcmsuaW1wbGVtZW50YXRpb24uVmlydHVhbE5ldHdvcmtHYXRld2F5Q29ubmVjdGlvbkltcGw=
internal partial class VirtualNetworkGatewayConnectionImpl :
IndependentChildResourceImpl<
IVirtualNetworkGatewayConnection,
IVirtualNetworkGateway,
VirtualNetworkGatewayConnectionInner,
VirtualNetworkGatewayConnectionImpl,
IHasId,
IUpdate,
INetworkManager>,
IVirtualNetworkGatewayConnection,
IDefinition,
IUpdate,
IAppliableWithTags<Microsoft.Azure.Management.Network.Fluent.IVirtualNetworkGatewayConnection>
{
private IVirtualNetworkGateway parent;
///GENMHASH:BCABB5578B0BD7DC8F8C22F4769FD3DE:02984D22C1D2E484D62F2595E7B0E86C
public IVirtualNetworkGatewayConnection ApplyTags()
{
return Extensions.Synchronize(() => ApplyTagsAsync());
}
///GENMHASH:6B8BA63027964E06F44A927837B450A0:BA32A105329DC11B026CC971C7538262
public async Task<Microsoft.Azure.Management.Network.Fluent.IVirtualNetworkGatewayConnection> ApplyTagsAsync(CancellationToken cancellationToken = default(CancellationToken))
{
await Manager.Inner.VirtualNetworkGatewayConnections.UpdateTagsAsync(ResourceGroupName, Name, Inner.Tags, cancellationToken);
await RefreshAsync();
return this;
}
///GENMHASH:F0389EF26F16D377233CEA0243D3C2D3:002AE7D0BF403F77853FCC09647B9C5D
public string LocalNetworkGateway2Id()
{
if (Inner.LocalNetworkGateway2 == null)
{
return null;
}
return Inner.LocalNetworkGateway2.Id;
}
///GENMHASH:CE19D6E1BE71E1233D9525A7E026BFC7:0DAA02A6E6149A594F1E611CEDA41775
public string SharedKey()
{
return Inner.SharedKey;
}
///GENMHASH:A4FB429FC35E326B6CD540115D02D73C:0688D196CF6445EF78F2CB4D55D76410
public string PeerId()
{
return Inner.Peer == null ? null : Inner.Peer.Id;
}
///GENMHASH:FD5D5A8D6904B467321E345BE1FA424E:8AB87020DE6C711CD971F3D80C33DD83
public IVirtualNetworkGateway Parent()
{
return parent;
}
///GENMHASH:AC21A10EE2E745A89E94E447800452C1:A029F579BEAF734FDD0D1A010CE89549
private void BeforeCreating()
{
SubResource virtualNetworkGatewayRef = new SubResource()
{
Id = parent.Id
};
Inner.VirtualNetworkGateway1 = virtualNetworkGatewayRef;
Inner.Location = Parent().RegionName;
}
///GENMHASH:DC68CE09DB266400D8B7E08E0150F876:29C6CFED65DB9A6CE452F3BC85F8D71C
public long IngressBytesTransferred()
{
return Inner.IngressBytesTransferred.HasValue ? Inner.IngressBytesTransferred.Value : 0;
}
///GENMHASH:3A31ACD3BD909199AC20F8F3E3739FBC:D7548BDC33746E38BAEB0C477D73EA03
public int RoutingWeight()
{
return Inner.RoutingWeight.HasValue ? Inner.RoutingWeight.Value : 0;
}
///GENMHASH:B0CEE06B3527C9FAA4A6F6BB52F2A301:62CA2860C467549EA3B59C449E9C2DA6
internal VirtualNetworkGatewayConnectionImpl(string name, VirtualNetworkGatewayImpl parent, VirtualNetworkGatewayConnectionInner inner)
: base(name, inner, parent.Manager)
{
this.parent = parent;
}
///GENMHASH:8D609444E5B12F47A2302B445E89BEE5:43AD2FCE7B0EAA8CBA41E52CCCA78770
public VirtualNetworkGatewayConnectionType ConnectionType()
{
return Inner.ConnectionType;
}
///GENMHASH:5AD91481A0966B059A478CD4E9DD9466:C6001AE2B48A1402A8313022A5CF5590
protected override async Task<VirtualNetworkGatewayConnectionInner> GetInnerAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return await parent.Manager.Inner.VirtualNetworkGatewayConnections.GetAsync(ResourceGroupName, Name, cancellationToken);
}
///GENMHASH:04D6D858FF61D37F76DA127C20A5ABF9:DFC8C1E6C2A0BC0C3178B00DC329D6B7
public VirtualNetworkGatewayConnectionImpl WithLocalNetworkGateway(ILocalNetworkGateway localNetworkGateway)
{
SubResource localNetworkGatewayRef = new SubResource()
{
Id = localNetworkGateway.Id
};
Inner.LocalNetworkGateway2 = localNetworkGatewayRef;
return this;
}
///GENMHASH:DD514B859A01D5FDAFF5D26EACDFE197:40A980295F5EA8FF8304DA8C06E899BF
public VirtualNetworkGatewayConnectionImpl UpdateTags()
{
return this;
}
///GENMHASH:63E7CC3AA7BB3CB910E5D0EE8931223C:05BC5F2415598E47C21323CD8B084A89
public bool UsePolicyBasedTrafficSelectors()
{
return Inner.UsePolicyBasedTrafficSelectors.HasValue ? Inner.UsePolicyBasedTrafficSelectors.Value : false;
}
///GENMHASH:1526F9C6D16D576524554408BA6A97AD:5EBA369C1D9EE8D92A96DC8E7D452DF1
public VirtualNetworkGatewayConnectionImpl WithSecondVirtualNetworkGateway(IVirtualNetworkGateway virtualNetworkGateway2)
{
SubResource virtualNetworkGateway2Ref = new SubResource()
{
Id = virtualNetworkGateway2.Id
};
Inner.VirtualNetworkGateway2 = virtualNetworkGateway2Ref;
return this;
}
///GENMHASH:528DB5AE9087793672AA421058153271:CC4E0FCDD0B71DE7618242C10BC4A4C0
public long EgressBytesTransferred()
{
return Inner.EgressBytesTransferred.HasValue ? Inner.EgressBytesTransferred.Value : 0;
}
///GENMHASH:7F86C125A87D152FD762C431C7E77E76:8499787EA21C54ECB62EBA36A555DD42
public bool IsBgpEnabled()
{
return Inner.EnableBgp.HasValue ? Inner.EnableBgp.Value : false;
}
protected async override Task<IVirtualNetworkGatewayConnection> CreateChildResourceAsync(CancellationToken cancellationToken = new CancellationToken())
{
await CreateResourceAsync(cancellationToken);
return this;
}
///GENMHASH:0202A00A1DCF248D2647DBDBEF2CA865:CD4C551113E5E3B4D9BB22FF3918F2C2
public async override Task<Microsoft.Azure.Management.Network.Fluent.IVirtualNetworkGatewayConnection> CreateResourceAsync(CancellationToken cancellationToken = default(CancellationToken))
{
BeforeCreating();
var connectionInner = await this.Manager.Inner.VirtualNetworkGatewayConnections.CreateOrUpdateAsync(parent.ResourceGroupName, this.Name, Inner, cancellationToken);
SetInner(connectionInner);
return this;
}
protected override void SetParentName(VirtualNetworkGatewayConnectionInner inner)
{
}
///GENMHASH:BA5893FC2B54BDCAFF5340EE3F1D9D5D:0B239CD1935B35B49A325AE508F825DD
public VirtualNetworkGatewayConnectionImpl WithBgp()
{
Inner.EnableBgp = true;
return this;
}
///GENMHASH:0D5B2EA57166FD9D37E2B87078924DF4:12E023CCFEF803E00F18A5BF276D26B7
public string AuthorizationKey()
{
return Inner.AuthorizationKey;
}
///GENMHASH:629786B45F85F8E289D849497FF3EB84:328FF3B049F2421E1BB77C26A4256370
public VirtualNetworkGatewayConnectionImpl WithVNetToVNet()
{
Inner.ConnectionType = VirtualNetworkGatewayConnectionType.Vnet2Vnet;
return this;
}
///GENMHASH:99D5BF64EA8AA0E287C9B6F77AAD6FC4:3DB04077E6BABC0FB5A5ACDA19D11309
public string ProvisioningState()
{
return Inner.ProvisioningState;
}
///GENMHASH:ACAE8064401EC62BFA5012E6FE5ADD0F:E2A95EE63056355B62101870AEDE47A6
public IReadOnlyCollection<IpsecPolicy> IpsecPolicies()
{
return new ReadOnlyCollection<IpsecPolicy>(Inner.IpsecPolicies);
}
///GENMHASH:AD4AAD7D7CE972B5534D97A24606A18F:E35EF8A35A152BC71CE31BA0440B23C7
public string VirtualNetworkGateway2Id()
{
if (Inner.VirtualNetworkGateway2 == null)
{
return null;
}
return Inner.VirtualNetworkGateway2.Id;
}
///GENMHASH:C70D23F4587F98FF6D0A29A186DD0C1E:7AD73DFFC315FFB18F7BA235DFC6F4ED
public VirtualNetworkGatewayConnectionImpl WithExpressRoute(string circuitId)
{
Inner.ConnectionType = VirtualNetworkGatewayConnectionType.ExpressRoute;
Inner.Peer = new SubResource()
{
Id = circuitId
};
return this;
}
///GENMHASH:6C56ED8B9268C869E730DCC2AA432590:E6D2C0ECA74E9925CAF40C55749D0EB1
public VirtualNetworkGatewayConnectionImpl WithExpressRoute(IExpressRouteCircuit circuit)
{
return WithExpressRoute(circuit.Id);
}
///GENMHASH:07B3D80A2B51CD1129DBD008D4FD771E:8F1916B6FE6A9A2F468F118EFB9F7036
public VirtualNetworkGatewayConnectionImpl WithAuthorization(string authorizationKey)
{
Inner.AuthorizationKey = authorizationKey;
return this;
}
///GENMHASH:6E2DB095301FA5F54EABD8841D651031:07DD1422A75C454174F9F62F5D008DAC
public VirtualNetworkGatewayConnectionImpl WithoutBgp()
{
Inner.EnableBgp = false;
return this;
}
///GENMHASH:1C40B7D65DDDB1CEAAD72DFB63629A65:AC41AE86773F8512C8D6E31D6F29A914
public string VirtualNetworkGateway1Id()
{
if (Inner.VirtualNetworkGateway1 == null)
{
return null;
}
return Inner.VirtualNetworkGateway1.Id;
}
///GENMHASH:FEB663768504525640BBFB5A208F3B76:BC57D6829223294BCF9ED45D4B96D238
public VirtualNetworkGatewayConnectionStatus ConnectionStatus()
{
return Inner.ConnectionStatus;
}
///GENMHASH:21044C5DE2790341DFD3F758A2850299:735429DEBDE0B3FC24266278F000BE53
public VirtualNetworkGatewayConnectionImpl WithSiteToSite()
{
Inner.ConnectionType = VirtualNetworkGatewayConnectionType.IPsec;
return this;
}
///GENMHASH:1CF1AEE9F6AD3D22730A7743178A5C9A:5B7F93EEF9A0C96F43B06C539EA492CF
public VirtualNetworkGatewayConnectionImpl WithSharedKey(string sharedKey)
{
Inner.SharedKey = sharedKey;
return this;
}
///GENMHASH:AEC5916EA96BA85F7A39800471D3F359:729D419AA8EB92D8E2582EA1988A5D32
public IReadOnlyCollection<TunnelConnectionHealth> TunnelConnectionStatus()
{
return new ReadOnlyCollection<TunnelConnectionHealth>(Inner.TunnelConnectionStatus);
}
UpdatableWithTags.UpdatableWithTags.IUpdateWithTags<IVirtualNetworkGatewayConnection> IUpdatableWithTags<IVirtualNetworkGatewayConnection>.UpdateTags()
{
return UpdateTags();
}
}
}
| |
namespace ArgumentValidator.Tests
{
using System;
using System.Data;
using System.Collections;
using System.Collections.Generic;
using ArgumentValidator;
using Microsoft.VisualStudio.TestTools.UnitTesting;
/// <summary>
/// Testing the argument validations.
/// </summary>
[TestClass]
public class ThrowTests
{
/// <summary>
/// A sample test enum
/// </summary>
enum TestEnum
{
Important,
NotSoImportant
}
/// <summary>
/// IfNullOrEmpty throws <exception cref="ArgumentException"/> when the argument is empty.
/// </summary>
[TestMethod]
[ExpectedException(typeof(ArgumentException))
]
public void IfNullOrEmpty_Empty_ThrowsArgumentException()
{
// Arrange
var argument = string.Empty;
// Act
Throw.IfNullOrEmpty(argument, nameof(argument));
}
/// <summary>
/// IfNullOrEmpty throws <exception cref="ArgumentNullException"/> when the argument is null.
/// </summary>
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void IfNullOrEmpty_Null_ThrowsArgumentNullException()
{
// Arrange
string argument = null;
// Act
Throw.IfNullOrEmpty(argument, nameof(argument));
}
/// <summary>
/// IfNullOrEmpty does not throw any exception when argument is white space.
/// </summary>
[TestMethod]
public void IfNullOrEmpty_WhiteSpace_NoExceptionThrown()
{
// Arrange
string argument = " ";
// Act
Throw.IfNullOrEmpty(argument, nameof(argument));
}
/// <summary>
/// IfNullOrEmpty does not throw any exception when argument is not null and not empty.
/// </summary>
[TestMethod]
public void IfNullOrEmpty_NotNullNotEmpty_NoExceptionThrown()
{
// Arrange
string argument = "dummy";
// Act
Throw.IfNullOrEmpty(argument, nameof(argument));
}
/// <summary>
/// IfNull throws <exception cref="ArgumentNullException"/> when the argument is null.
/// </summary>
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void IfNull_Null_ThrowsArgumentNullException()
{
// Arrange
object argument = null;
// Act
Throw.IfNull(argument, nameof(argument));
}
/// <summary>
/// IfNull does not throw any exception when argument is not null.
/// </summary>
[TestMethod]
public void IfNull_NotNull_NoExceptionThrown()
{
// Arrange
object argument = 42;
// Act
Throw.IfNull(argument, nameof(argument));
}
/// <summary>
/// IfNullOrEmpty throws <exception cref="ArgumentNullException"/> when the collection is null.
/// </summary>
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void IfNullOrEmpty_NullCollection_ThrowsArgumentNullException()
{
// Arrange
ICollection argument = null;
// Act
Throw.IfNullOrEmpty(argument, nameof(argument));
}
/// <summary>
/// IfNullOrEmpty throws <exception cref="ArgumentException"/> when the argument is an empty collection.
/// </summary>
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void IfNullOrEmpty_EmptyCollection_ThrowsArgumentNullException()
{
// Arrange
var argument = new List<string>();
// Act
Throw.IfNullOrEmpty(argument, nameof(argument));
}
/// <summary>
/// IfNullOrEmpty does not throw any exception when argument is not an empty collection.
/// </summary>
[TestMethod]
public void IfNullOrEmpty_NonEmptyCollection_NoExceptionThrown()
{
// Arrange
var argument = new List<string>() { "oneitme" };
// Act
Throw.IfNullOrEmpty(argument, nameof(argument));
}
/// <summary>
/// IfHasNull throws <exception cref="ArgumentException"/> when the collection has null.
/// </summary>
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void IfNullOrHasNull_CollectionHasNull_ThrowsArgumentException()
{
// Arrange
var argument = new List<string>() { "oneitem", null, "seconditem" };
// Act
Throw.IfHasNull(argument, nameof(argument));
}
/// <summary>
/// IfHasNull does not throw any exception when collection does not have a null value.
/// </summary>
[TestMethod]
public void IfNullOrHasNull_CollectionHasNoNull_NoExceptionThrown()
{
// Arrange
var argument = new List<string> { "oneitem", "seconditem" };
// Act
Throw.IfHasNull(argument, nameof(argument));
}
/// <summary>
/// IfHasNull does not throw any exception when collection is null.
/// </summary>
[TestMethod]
public void IfNullOrHasNull_CollectionIsNull_NoExceptionThrown()
{
// Arrange
ICollection<int> argument = null;
// Act
Throw.IfHasNull(argument, nameof(argument));
}
/// <summary>
/// IfEmpty throws <exception cref="ArgumentException"/> when the argument is an empty Guid.
/// </summary>
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void IfEmpty_EmptyGuid_ThrowsArgumentException()
{
// Arrange
var argument = Guid.Empty;
// Act
Throw.IfEmpty(argument, nameof(argument));
}
/// <summary>
/// IfEmpty does not throw any exception when argument is a non empty guid.
/// </summary>
[TestMethod]
public void IfEmpty_NonEmptyGuid_NoExceptionThrown()
{
// Arrange
var argument = Guid.NewGuid();
// Act
Throw.IfEmpty(argument, nameof(argument));
}
/// <summary>
/// IfNot throws <exception cref="InvalidConstraintException"/> when constraint is false.
/// </summary>
[TestMethod]
[ExpectedException(typeof(InvalidConstraintException))]
public void IfNot_ExpressionTrue_ThrowInvalidConstraintException()
{
// Arrange
var argumentValue = 10;
// Act
Throw.IfNot(() => argumentValue > 100);
}
/// <summary>
/// IfNot does not throw any exception when constraint is true.
/// </summary>
[TestMethod]
public void IfNot_ExpressionFalse_NoExceptionThrown()
{
// Arrange
var argumentValue = 43;
// Act
Throw.IfNot(() => argumentValue > 42);
}
/// <summary>
/// IfNull throws <exception cref="ArgumentException"/> when the nullable argument is null.
/// </summary>
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void IfNull_NullableTypeUndefinedValue_ThrowsArgumentException()
{
// Arrange
int? argument = null;
// Act
Throw.IfNull(argument, nameof(argument));
}
/// <summary>
/// IfNull does not throw any exception when nullable argument is valid value.
/// </summary>
[TestMethod]
public void IfNull_NullableTypeValidValue_NoExceptionThrown()
{
// Arrange
int? argument = 31412;
// Act
Throw.IfNull(argument, nameof(argument));
}
/// <summary>
/// IfOutOfRange throws <exception cref="ArgumentOutOfRangeException"/> when the argument
/// is not given inside the range.
/// </summary>
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void IfOutOfRange_GreaterThanEndRangeValue_ThrowsArgumentOutOfRangeException()
{
// Arrange
var argument = 500;
var startRange = 1;
var endRange = 100;
// Act
Throw.IfOutOfRange(argument, startRange, endRange, nameof(argument));
}
/// <summary>
/// IfOutOfRange throws <exception cref="ArgumentOutOfRangeException"/> when the argument
/// is not given inside the range.
/// </summary>
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void IfOutOfRange_EnumOutOfRangeValue_ThrowsArgumentOutOfRangeException()
{
// Arrange
TestEnum argument = (TestEnum)5;
// Act
Throw.IfOutOfRange(argument, nameof(argument));
}
/// <summary>
/// IfOutOfRange throws <exception cref="ArgumentOutOfRangeException"/> when the argument
/// is not given inside the range.
/// </summary>
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void IfOutOfRange_LessThanStartRangeValue_ThrowsArgumentOutOfRangeException()
{
// Arrange
var argument = 0;
var startRange = 1;
var endRange = 100;
// Act
Throw.IfOutOfRange(argument, startRange, endRange, nameof(argument));
}
/// <summary>
/// IfOutOfRange throws no exception when argument is in range.
/// </summary>
[TestMethod]
public void IfOutOfRange_StartRangeValue_NoExceptionThrown()
{
// Arrange
var argument = 1;
var startRange = 1;
var endRange = 100;
// Act
Throw.IfOutOfRange(argument, startRange, endRange, nameof(argument));
}
/// <summary>
/// IfOutOfRange throws no exception when argument is in range.
/// </summary>
[TestMethod]
public void IfOutOfRange_EndRangeValue_NoExceptionThrown()
{
// Arrange
var argument = 100;
var startRange = 1;
var endRange = 100;
// Act
Throw.IfOutOfRange(argument, startRange, endRange, nameof(argument));
}
/// <summary>
/// IfOutOfRange does not throw any exception when argument is inside the given range.
/// </summary>
[TestMethod]
public void IfOutOfRange_InRange_NoExceptionThrown()
{
// Arrange
var argument = 50;
var startRange = 1;
var endRange = 100;
// Acts
Throw.IfOutOfRange(argument, startRange, endRange, nameof(argument));
}
/// <summary>
/// IfInRange throws no exception when argument is not in range.
/// </summary>
[TestMethod]
public void IfInRange_GreaterThanEndRangeValue_NoExceptionThrown()
{
// Arrange
var argument = 500;
var startRange = 1;
var endRange = 100;
// Act
Throw.IfInRange(argument, startRange, endRange, nameof(argument));
}
/// <summary>
/// IfInRange throws no exception when argument is not in range.
/// </summary>
[TestMethod]
public void IfInRange_LessThanStartRangeValue_NoExceptionThrown()
{
// Arrange
var argument = 0;
var startRange = 1;
var endRange = 100;
// Act
Throw.IfInRange(argument, startRange, endRange, nameof(argument));
}
/// <summary>
/// IfInRange throws <exception cref="ArgumentOutOfRangeException"/> when the argument
/// is equal to start range value.
/// </summary>
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void IfInRange_StartRangeValue_ThrowsArgumentOutOfRangeException()
{
// Arrange
var argument = 1;
var startRange = 1;
var endRange = 100;
// Act
Throw.IfInRange(argument, startRange, endRange, nameof(argument));
}
/// <summary>
/// IfInRange throws <exception cref="ArgumentOutOfRangeException"/> when the argument
/// is equal to the end range value.
/// </summary>
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void IfInRange_EndRangeValue_ThrowsArgumentOutOfRangeException()
{
// Arrange
var argument = 100;
var startRange = 1;
var endRange = 100;
// Act
Throw.IfInRange(argument, startRange, endRange, nameof(argument));
}
/// <summary>
/// IfInRange throws <exception cref="ArgumentOutOfRangeException"/> when the argument
/// is inside the range.
/// </summary>
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void IfInRange_InRange_NoExceptionThrowsArgumentOutOfRangeException()
{
// Arrange
var argument = 50;
var startRange = 1;
var endRange = 100;
// Acts
Throw.IfInRange(argument, startRange, endRange, nameof(argument));
}
}
}
| |
// 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 Xunit;
namespace System.Collections.Tests
{
public class Hashtable_CopyToTests
{
[Fact]
public void TestCopyToBasic()
{
Hashtable hash = null; // the hashtable object which will be used in the tests
object[] objArr = null; // the object array corresponding to arr
object[] objArr2 = null; // helper object array
object[,] objArrRMDim = null; // multi dimensional object array
// these are the keys and values which will be added to the hashtable in the tests
object[] keys = new object[] {
new object(),
"Hello" ,
"my array" ,
new DateTime(),
new SortedList(),
typeof( System.Environment ),
5
};
object[] values = new object[] {
"Somestring" ,
new object(),
new int [] { 1, 2, 3, 4, 5 },
new Hashtable(),
new Exception(),
new Hashtable_CopyToTests(),
null
};
//[]test normal conditions, array is large enough to hold all elements
// make new hashtable
hash = new Hashtable();
// put in values and keys
for (int i = 0; i < values.Length; i++)
{
hash.Add(keys[i], values[i]);
}
// now try getting out the values using CopyTo method
objArr = new object[values.Length + 2];
// put a sentinal in first position, and make sure it is not overriden
objArr[0] = "startstring";
// put a sentinal in last position, and make sure it is not overriden
objArr[values.Length + 1] = "endstring";
hash.Values.CopyTo((Array)objArr, 1);
// make sure sentinal character is still there
Assert.Equal("startstring", objArr[0]);
Assert.Equal("endstring", objArr[values.Length + 1]);
// check to make sure arr is filled up with the correct elements
objArr2 = new object[values.Length];
Array.Copy(objArr, 1, objArr2, 0, values.Length);
objArr = objArr2;
Assert.True(CompareArrays(objArr, values));
//[] This is the same test as before but now we are going to used Hashtable.CopyTo instead of Hasthabe.Values.CopyTo
// now try getting out the values using CopyTo method
objArr = new object[values.Length + 2];
// put a sentinal in first position, and make sure it is not overriden
objArr[0] = "startstring";
// put a sentinal in last position, and make sure it is not overriden
objArr[values.Length + 1] = "endstring";
hash.CopyTo((Array)objArr, 1);
// make sure sentinal character is still there
Assert.Equal("startstring", objArr[0]);
Assert.Equal("endstring", objArr[values.Length + 1]);
// check to make sure arr is filled up with the correct elements
BitArray bitArray = new BitArray(values.Length);
for (int i = 0; i < values.Length; i++)
{
DictionaryEntry entry = (DictionaryEntry)objArr[i + 1];
int valueIndex = Array.IndexOf(values, entry.Value);
int keyIndex = Array.IndexOf(keys, entry.Key);
Assert.NotEqual(-1, valueIndex);
Assert.NotEqual(-1, keyIndex);
Assert.Equal(valueIndex, keyIndex);
bitArray[i] = true;
}
for (int i = 0; i < ((ICollection)bitArray).Count; i++)
{
Assert.True(bitArray[i]);
}
//[] Parameter validation
//[] Null array
Assert.Throws<ArgumentNullException>(() =>
{
hash = new Hashtable();
objArr = new object[0];
hash.CopyTo(null, 0);
}
);
//[] Multidimentional array
Assert.Throws<ArgumentException>(() =>
{
hash = new Hashtable();
objArrRMDim = new object[16, 16];
hash.CopyTo(objArrRMDim, 0);
}
);
//[] Array not large enough
Assert.Throws<ArgumentException>(() =>
{
hash = new Hashtable();
for (int i = 0; i < 256; i++)
{
hash.Add(i.ToString(), i);
}
objArr = new object[hash.Count + 8];
hash.CopyTo(objArr, 9);
}
);
Assert.Throws<ArgumentException>(() =>
{
hash = new Hashtable();
objArr = new object[0];
hash.CopyTo(objArr, Int32.MaxValue);
}
);
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
hash = new Hashtable();
objArr = new object[0];
hash.CopyTo(objArr, Int32.MinValue);
}
);
//[]copy should throw because of outofrange
Random random = new Random(-55);
for (int iii = 0; iii < 20; iii++)
{
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
hash = new Hashtable();
objArr = new object[0];
hash.CopyTo(objArr, random.Next(-1000, 0));
}
);
}
//[]test when array is to small to hold all values hashtable has more values then array can hold
hash = new Hashtable();
// put in values and keys
for (int i = 0; i < values.Length; i++)
{
hash.Add(keys[i], values[i]);
}
// now try getting out the values using CopyTo method into a small array
objArr = new object[values.Length - 1];
Assert.Throws<ArgumentException>(() =>
{
hash.Values.CopyTo((Array)objArr, 0);
}
);
//[]test when array is size 0
// now try getting out the values using CopyTo method into a 0 sized array
objArr = new object[0];
Assert.Throws<ArgumentException>(() =>
{
hash.Values.CopyTo((Array)objArr, 0);
}
);
//[]test when array is null
Assert.Throws<ArgumentNullException>(() =>
{
hash.Values.CopyTo(null, 0);
}
);
}
[Fact]
public void TestCopyToWithValidIndex()
{
//[]test when hashtable has no elements in it
var hash = new Hashtable();
// make an array of 100 size to hold elements
var objArr = new object[100];
hash.Values.CopyTo(objArr, 0);
objArr = new object[100];
hash.Values.CopyTo(objArr, 99);
objArr = new object[100];
// valid now
hash.Values.CopyTo(objArr, 100);
// make an array of 0 size to hold elements
objArr = new object[0];
hash.Values.CopyTo(objArr, 0);
int key = 123;
int val = 456;
hash.Add(key, val);
objArr = new object[100];
objArr[0] = 0;
hash.Values.CopyTo(objArr, 0);
Assert.Equal(val, objArr[0]);
hash.Values.CopyTo(objArr, 99);
Assert.Equal(val, objArr[99]);
}
[Fact]
public void TestCopyToWithInvalidIndex()
{
object[] objArr = null;
object[][] objArrMDim = null; // multi dimensional object array
object[,] objArrRMDim = null; // multi dimensional object array
//[]test when hashtable has no elements in it and index is out of range (negative)
var hash = new Hashtable();
// put no elements in hashtable
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
// make an array of 100 size to hold elements
objArr = new object[0];
hash.Values.CopyTo(objArr, -1);
}
);
//[]test when array is multi dimensional and array is large enough
hash = new Hashtable();
// put elements into hashtable
for (int i = 0; i < 100; i++)
{
hash.Add(i.ToString(), i.ToString());
}
Assert.Throws<InvalidCastException>(() =>
{
// make an array of 100 size to hold elements
objArrMDim = new object[100][];
for (int i = 0; i < 100; i++)
{
objArrMDim[i] = new object[i + 1];
}
hash.Values.CopyTo(objArrMDim, 0);
}
);
Assert.Throws<ArgumentException>(() =>
{
// make an array of 100 size to hold elements
objArrRMDim = new object[100, 100];
hash.Values.CopyTo(objArrRMDim, 0);
}
);
//[]test when array is multi dimensional and array is small
hash = new Hashtable();
// put elements into hashtable
for (int i = 0; i < 100; i++)
{
hash.Add(i.ToString(), i.ToString());
}
Assert.Throws<ArgumentException>(() =>
{
// make an array of 100 size to hold elements
objArrMDim = new object[99][];
for (int i = 0; i < 99; i++)
{
objArrMDim[i] = new object[i + 1];
}
hash.Values.CopyTo(objArrMDim, 0);
}
);
//[]test to see if CopyTo throws correct exception
hash = new Hashtable();
Assert.Throws<ArgumentException>(() =>
{
string[] str = new string[100];
// i will be calling CopyTo with the str array and index 101 it should throw an exception
// since the array index 101 is not valid
hash.Values.CopyTo(str, 101);
}
);
}
/////////////////////////// HELPER FUNCTIONS
// this is pretty slow algorithm but it works
// returns true if arr1 has the same elements as arr2
// arrays can have nulls in them, but arr1 and arr2 should not be null
public static bool CompareArrays(object[] arr1, object[] arr2)
{
if (arr1.Length != arr2.Length)
{
return false;
}
int i, j;
bool fPresent = false;
for (i = 0; i < arr1.Length; i++)
{
fPresent = false;
for (j = 0; j < arr2.Length && (fPresent == false); j++)
{
if ((arr1[i] == null && arr2[j] == null)
||
(arr1[i] != null && arr1[i].Equals(arr2[j])))
{
fPresent = true;
}
}
if (fPresent == false)
{
return false;
}
}
// now do the same thing but the other way around
for (i = 0; i < arr2.Length; i++)
{
fPresent = false;
for (j = 0; j < arr1.Length && (fPresent == false); j++)
{
if ((arr2[i] == null && arr1[j] == null) || (arr2[i] != null && arr2[i].Equals(arr1[j])))
{
fPresent = true;
}
}
if (fPresent == false)
{
return false;
}
}
return true;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#if ES_BUILD_STANDALONE
using System;
using System.Diagnostics;
#endif
using System.Collections.Generic;
using System.Threading;
#if ES_BUILD_STANDALONE
namespace Microsoft.Diagnostics.Tracing
#else
namespace System.Diagnostics.Tracing
#endif
{
internal class CounterGroup
{
private readonly EventSource _eventSource;
private readonly List<DiagnosticCounter> _counters;
private static readonly object s_counterGroupLock = new object();
internal CounterGroup(EventSource eventSource)
{
_eventSource = eventSource;
_counters = new List<DiagnosticCounter>();
RegisterCommandCallback();
}
internal void Add(DiagnosticCounter eventCounter)
{
lock (s_counterGroupLock) // Lock the CounterGroup
_counters.Add(eventCounter);
}
internal void Remove(DiagnosticCounter eventCounter)
{
lock (s_counterGroupLock) // Lock the CounterGroup
_counters.Remove(eventCounter);
}
#region EventSource Command Processing
private void RegisterCommandCallback()
{
_eventSource.EventCommandExecuted += OnEventSourceCommand;
}
private void OnEventSourceCommand(object? sender, EventCommandEventArgs e)
{
if (e.Command == EventCommand.Enable || e.Command == EventCommand.Update)
{
Debug.Assert(e.Arguments != null);
if (e.Arguments.TryGetValue("EventCounterIntervalSec", out string? valueStr) && float.TryParse(valueStr, out float value))
{
lock (s_counterGroupLock) // Lock the CounterGroup
{
EnableTimer(value);
}
}
}
else if (e.Command == EventCommand.Disable)
{
lock (s_counterGroupLock)
{
DisableTimer();
}
}
}
#endregion // EventSource Command Processing
#region Global CounterGroup Array management
// We need eventCounters to 'attach' themselves to a particular EventSource.
// this table provides the mapping from EventSource -> CounterGroup
// which represents this 'attached' information.
private static WeakReference<CounterGroup>[]? s_counterGroups;
private static void EnsureEventSourceIndexAvailable(int eventSourceIndex)
{
Debug.Assert(Monitor.IsEntered(s_counterGroupLock));
if (CounterGroup.s_counterGroups == null)
{
CounterGroup.s_counterGroups = new WeakReference<CounterGroup>[eventSourceIndex + 1];
}
else if (eventSourceIndex >= CounterGroup.s_counterGroups.Length)
{
WeakReference<CounterGroup>[] newCounterGroups = new WeakReference<CounterGroup>[eventSourceIndex + 1];
Array.Copy(CounterGroup.s_counterGroups, newCounterGroups, CounterGroup.s_counterGroups.Length);
CounterGroup.s_counterGroups = newCounterGroups;
}
}
internal static CounterGroup GetCounterGroup(EventSource eventSource)
{
lock (s_counterGroupLock)
{
int eventSourceIndex = EventListener.EventSourceIndex(eventSource);
EnsureEventSourceIndexAvailable(eventSourceIndex);
Debug.Assert(s_counterGroups != null);
WeakReference<CounterGroup> weakRef = CounterGroup.s_counterGroups[eventSourceIndex];
CounterGroup? ret = null;
if (weakRef == null || !weakRef.TryGetTarget(out ret))
{
ret = new CounterGroup(eventSource);
CounterGroup.s_counterGroups[eventSourceIndex] = new WeakReference<CounterGroup>(ret);
}
return ret;
}
}
#endregion // Global CounterGroup Array management
#region Timer Processing
private DateTime _timeStampSinceCollectionStarted;
private int _pollingIntervalInMilliseconds;
private DateTime _nextPollingTimeStamp;
private void EnableTimer(float pollingIntervalInSeconds)
{
Debug.Assert(Monitor.IsEntered(s_counterGroupLock));
if (pollingIntervalInSeconds <= 0)
{
_pollingIntervalInMilliseconds = 0;
}
else if (_pollingIntervalInMilliseconds == 0 || pollingIntervalInSeconds * 1000 < _pollingIntervalInMilliseconds)
{
_pollingIntervalInMilliseconds = (int)(pollingIntervalInSeconds * 1000);
ResetCounters(); // Reset statistics for counters before we start the thread.
_timeStampSinceCollectionStarted = DateTime.UtcNow;
// Don't capture the current ExecutionContext and its AsyncLocals onto the timer causing them to live forever
bool restoreFlow = false;
try
{
if (!ExecutionContext.IsFlowSuppressed())
{
ExecutionContext.SuppressFlow();
restoreFlow = true;
}
_nextPollingTimeStamp = DateTime.UtcNow + new TimeSpan(0, 0, (int)pollingIntervalInSeconds);
// Create the polling thread and init all the shared state if needed
if (s_pollingThread == null)
{
s_pollingThreadSleepEvent = new AutoResetEvent(false);
s_counterGroupEnabledList = new List<CounterGroup>();
s_pollingThread = new Thread(PollForValues) { IsBackground = true };
s_pollingThread.Start();
}
if (!s_counterGroupEnabledList!.Contains(this))
{
s_counterGroupEnabledList.Add(this);
}
// notify the polling thread that the polling interval may have changed and the sleep should
// be recomputed
s_pollingThreadSleepEvent!.Set();
}
finally
{
// Restore the current ExecutionContext
if (restoreFlow)
ExecutionContext.RestoreFlow();
}
}
}
private void DisableTimer()
{
_pollingIntervalInMilliseconds = 0;
s_counterGroupEnabledList?.Remove(this);
}
private void ResetCounters()
{
lock (s_counterGroupLock) // Lock the CounterGroup
{
foreach (DiagnosticCounter counter in _counters)
{
if (counter is IncrementingEventCounter ieCounter)
{
ieCounter.UpdateMetric();
}
else if (counter is IncrementingPollingCounter ipCounter)
{
ipCounter.UpdateMetric();
}
else if (counter is EventCounter eCounter)
{
eCounter.ResetStatistics();
}
}
}
}
private void OnTimer()
{
Debug.Assert(Monitor.IsEntered(s_counterGroupLock));
if (_eventSource.IsEnabled())
{
DateTime now = DateTime.UtcNow;
TimeSpan elapsed = now - _timeStampSinceCollectionStarted;
foreach (DiagnosticCounter counter in _counters)
{
counter.WritePayload((float)elapsed.TotalSeconds, _pollingIntervalInMilliseconds);
}
_timeStampSinceCollectionStarted = now;
do
{
_nextPollingTimeStamp += new TimeSpan(0, 0, 0, 0, _pollingIntervalInMilliseconds);
} while (_nextPollingTimeStamp <= now);
}
}
private static Thread? s_pollingThread;
// Used for sleeping for a certain amount of time while allowing the thread to be woken up
private static AutoResetEvent? s_pollingThreadSleepEvent;
private static List<CounterGroup>? s_counterGroupEnabledList;
private static void PollForValues()
{
AutoResetEvent? sleepEvent = null;
while (true)
{
int sleepDurationInMilliseconds = int.MaxValue;
lock (s_counterGroupLock)
{
sleepEvent = s_pollingThreadSleepEvent;
foreach (CounterGroup counterGroup in s_counterGroupEnabledList!)
{
DateTime now = DateTime.UtcNow;
if (counterGroup._nextPollingTimeStamp < now + new TimeSpan(0, 0, 0, 0, 1))
{
counterGroup.OnTimer();
}
int millisecondsTillNextPoll = (int)((counterGroup._nextPollingTimeStamp - now).TotalMilliseconds);
millisecondsTillNextPoll = Math.Max(1, millisecondsTillNextPoll);
sleepDurationInMilliseconds = Math.Min(sleepDurationInMilliseconds, millisecondsTillNextPoll);
}
}
if (sleepDurationInMilliseconds == int.MaxValue)
{
sleepDurationInMilliseconds = -1; // WaitOne uses -1 to mean infinite
}
sleepEvent?.WaitOne(sleepDurationInMilliseconds);
}
}
#endregion // Timer Processing
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests
{
using System.Reflection;
using NLog.Targets;
using System;
using System.Globalization;
using NLog.Config;
#if ASYNC_SUPPORTED
using System.Threading.Tasks;
#endif
using Xunit;
public class LoggerTests : NLogTestBase
{
[Fact]
public void TraceTest()
{
// test all possible overloads of the Trace() method
for (int enabled = 0; enabled < 2; ++enabled)
{
if (enabled == 0)
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='' writeTo='debug' />
</rules>
</nlog>");
}
else
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='Trace' writeTo='debug' />
</rules>
</nlog>");
}
ILogger logger = LogManager.GetLogger("A");
logger.Trace("message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.Trace("message{0}", (ulong)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", (ulong)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Trace("message{0}", (long)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", (long)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Trace("message{0}", (uint)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", (uint)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Trace("message{0}", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Trace("message{0}", (ushort)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", (ushort)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Trace("message{0}", (sbyte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", (sbyte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Trace("message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.Trace("message{0}", (short)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", (short)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Trace("message{0}", (byte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", (byte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Trace("message{0}", 'c');
if (enabled == 1) AssertDebugLastMessage("debug", "messagec");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", 'd');
if (enabled == 1) AssertDebugLastMessage("debug", "messaged");
logger.Trace("message{0}", "ddd");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee");
logger.Trace("message{0}{1}", "ddd", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1");
logger.Trace(CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2");
logger.Trace("message{0}{1}{2}", "ddd", 1, "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1eee");
logger.Trace(CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fff");
logger.Trace("message{0}{1}{2}{3}", "eee", 2, "fff", "ggg");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fffggg");
logger.Trace("message{0}", true);
if (enabled == 1) AssertDebugLastMessage("debug", "messageTrue");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", false);
if (enabled == 1) AssertDebugLastMessage("debug", "messageFalse");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", (float)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", 2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", (decimal)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
#pragma warning disable 0618
// Obsolete method requires testing until removed.
logger.TraceException("message", new Exception("test"));
if (enabled == 1) AssertDebugLastMessage("debug", "message");
#pragma warning restore 0618
logger.Trace(new Exception("test"), "message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.Trace(delegate { return "message from lambda"; });
if (enabled == 1) AssertDebugLastMessage("debug", "message from lambda");
if (enabled == 0)
AssertDebugCounter("debug", 0);
}
}
[Fact]
public void DebugTest()
{
// test all possible overloads of the Debug() method
for (int enabled = 0; enabled < 2; ++enabled)
{
if (enabled == 0)
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='' writeTo='debug' />
</rules>
</nlog>");
}
else
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='Debug' writeTo='debug' />
</rules>
</nlog>");
}
ILogger logger = LogManager.GetLogger("A");
logger.Debug("message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.Debug("message{0}", (ulong)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", (ulong)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Debug("message{0}", (long)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", (long)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Debug("message{0}", (uint)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", (uint)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Debug("message{0}", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Debug("message{0}", (ushort)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", (ushort)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Debug("message{0}", (sbyte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", (sbyte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Debug("message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.Debug("message{0}", (short)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", (short)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Debug("message{0}", (byte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", (byte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Debug("message{0}", 'c');
if (enabled == 1) AssertDebugLastMessage("debug", "messagec");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", 'd');
if (enabled == 1) AssertDebugLastMessage("debug", "messaged");
logger.Debug("message{0}", "ddd");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee");
logger.Debug("message{0}{1}", "ddd", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1");
logger.Debug(CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2");
logger.Debug("message{0}{1}{2}", "ddd", 1, "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1eee");
logger.Debug(CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fff");
logger.Debug("message{0}{1}{2}{3}", "eee", 2, "fff", "ggg");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fffggg");
logger.Debug("message{0}", true);
if (enabled == 1) AssertDebugLastMessage("debug", "messageTrue");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", false);
if (enabled == 1) AssertDebugLastMessage("debug", "messageFalse");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", (float)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", 2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", (decimal)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
#pragma warning disable 0618
// Obsolete method requires testing until completely removed.
logger.DebugException("message", new Exception("test"));
if (enabled == 1) AssertDebugLastMessage("debug", "message");
#pragma warning restore 0618
logger.Debug(delegate { return "message from lambda"; });
if (enabled == 1) AssertDebugLastMessage("debug", "message from lambda");
if (enabled == 0)
AssertDebugCounter("debug", 0);
}
}
[Fact]
public void InfoTest()
{
// test all possible overloads of the Info() method
for (int enabled = 0; enabled < 2; ++enabled)
{
if (enabled == 0)
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='' writeTo='debug' />
</rules>
</nlog>");
}
else
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='Info' writeTo='debug' />
</rules>
</nlog>");
}
ILogger logger = LogManager.GetLogger("A");
logger.Info("message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.Info("message{0}", (ulong)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Info(CultureInfo.InvariantCulture, "message{0}", (ulong)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Info("message{0}", (long)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Info(CultureInfo.InvariantCulture, "message{0}", (long)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Info("message{0}", (uint)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Info(CultureInfo.InvariantCulture, "message{0}", (uint)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Info("message{0}", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Info(CultureInfo.InvariantCulture, "message{0}", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Info("message{0}", (ushort)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Info(CultureInfo.InvariantCulture, "message{0}", (ushort)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Info("message{0}", (sbyte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Info(CultureInfo.InvariantCulture, "message{0}", (sbyte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Info("message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.Info(CultureInfo.InvariantCulture, "message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.Info("message{0}", (short)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Info(CultureInfo.InvariantCulture, "message{0}", (short)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Info("message{0}", (byte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Info(CultureInfo.InvariantCulture, "message{0}", (byte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Info("message{0}", 'c');
if (enabled == 1) AssertDebugLastMessage("debug", "messagec");
logger.Info(CultureInfo.InvariantCulture, "message{0}", 'd');
if (enabled == 1) AssertDebugLastMessage("debug", "messaged");
logger.Info("message{0}", "ddd");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd");
logger.Info(CultureInfo.InvariantCulture, "message{0}", "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee");
logger.Info("message{0}{1}", "ddd", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1");
logger.Info(CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2");
logger.Info("message{0}{1}{2}", "ddd", 1, "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1eee");
logger.Info(CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fff");
logger.Info("message{0}{1}{2}{3}", "eee", 2, "fff", "ggg");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fffggg");
logger.Info("message{0}", true);
if (enabled == 1) AssertDebugLastMessage("debug", "messageTrue");
logger.Info(CultureInfo.InvariantCulture, "message{0}", false);
if (enabled == 1) AssertDebugLastMessage("debug", "messageFalse");
logger.Info(CultureInfo.InvariantCulture, "message{0}", (float)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Info(CultureInfo.InvariantCulture, "message{0}", 2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Info(CultureInfo.InvariantCulture, "message{0}", (decimal)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
#pragma warning disable 0618
// Obsolete method requires testing until removed.
logger.InfoException("message", new Exception("test"));
if (enabled == 1) AssertDebugLastMessage("debug", "message");
#pragma warning restore 0618
logger.Info(new Exception("test"), "message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.Info(delegate { return "message from lambda"; });
if (enabled == 1) AssertDebugLastMessage("debug", "message from lambda");
if (enabled == 0)
AssertDebugCounter("debug", 0);
}
}
[Fact]
public void WarnTest()
{
// test all possible overloads of the Warn() method
for (int enabled = 0; enabled < 2; ++enabled)
{
if (enabled == 0)
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='' writeTo='debug' />
</rules>
</nlog>");
}
else
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='Warn' writeTo='debug' />
</rules>
</nlog>");
}
ILogger logger = LogManager.GetLogger("A");
logger.Warn("message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.Warn("message{0}", (ulong)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", (ulong)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Warn("message{0}", (long)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", (long)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Warn("message{0}", (uint)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", (uint)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Warn("message{0}", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Warn("message{0}", (ushort)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", (ushort)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Warn("message{0}", (sbyte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", (sbyte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Warn("message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.Warn("message{0}", (short)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", (short)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Warn("message{0}", (byte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", (byte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Warn("message{0}", 'c');
if (enabled == 1) AssertDebugLastMessage("debug", "messagec");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", 'd');
if (enabled == 1) AssertDebugLastMessage("debug", "messaged");
logger.Warn("message{0}", "ddd");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee");
logger.Warn("message{0}{1}", "ddd", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1");
logger.Warn(CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2");
logger.Warn("message{0}{1}{2}", "ddd", 1, "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1eee");
logger.Warn(CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fff");
logger.Warn("message{0}{1}{2}{3}", "eee", 2, "fff", "ggg");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fffggg");
logger.Warn("message{0}", true);
if (enabled == 1) AssertDebugLastMessage("debug", "messageTrue");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", false);
if (enabled == 1) AssertDebugLastMessage("debug", "messageFalse");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", (float)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", 2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", (decimal)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
#pragma warning disable 0618
// Obsolete method requires testing until removed.
logger.WarnException("message", new Exception("test"));
if (enabled == 1) AssertDebugLastMessage("debug", "message");
#pragma warning restore 0618
logger.Warn(new Exception("test"), "message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.Warn(delegate { return "message from lambda"; });
if (enabled == 1) AssertDebugLastMessage("debug", "message from lambda");
if (enabled == 0)
AssertDebugCounter("debug", 0);
}
}
[Fact]
public void ErrorTest()
{
// test all possible overloads of the Error() method
for (int enabled = 0; enabled < 2; ++enabled)
{
if (enabled == 0)
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='' writeTo='debug' />
</rules>
</nlog>");
}
else
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='Error' writeTo='debug' />
</rules>
</nlog>");
}
ILogger logger = LogManager.GetLogger("A");
logger.Error("message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.Error("message{0}", (ulong)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Error(CultureInfo.InvariantCulture, "message{0}", (ulong)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Error("message{0}", (long)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Error(CultureInfo.InvariantCulture, "message{0}", (long)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Error("message{0}", (uint)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Error(CultureInfo.InvariantCulture, "message{0}", (uint)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Error("message{0}", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Error(CultureInfo.InvariantCulture, "message{0}", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Error("message{0}", (ushort)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Error(CultureInfo.InvariantCulture, "message{0}", (ushort)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Error("message{0}", (sbyte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Error(CultureInfo.InvariantCulture, "message{0}", (sbyte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Error("message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.Error(CultureInfo.InvariantCulture, "message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.Error("message{0}", (short)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Error(CultureInfo.InvariantCulture, "message{0}", (short)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Error("message{0}", (byte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Error(CultureInfo.InvariantCulture, "message{0}", (byte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Error("message{0}", 'c');
if (enabled == 1) AssertDebugLastMessage("debug", "messagec");
logger.Error(CultureInfo.InvariantCulture, "message{0}", 'd');
if (enabled == 1) AssertDebugLastMessage("debug", "messaged");
logger.Error("message{0}", "ddd");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd");
logger.Error(CultureInfo.InvariantCulture, "message{0}", "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee");
logger.Error("message{0}{1}", "ddd", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1");
logger.Error(CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2");
logger.Error("message{0}{1}{2}", "ddd", 1, "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1eee");
logger.Error(CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fff");
logger.Error("message{0}{1}{2}{3}", "eee", 2, "fff", "ggg");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fffggg");
logger.Error("message{0}", true);
if (enabled == 1) AssertDebugLastMessage("debug", "messageTrue");
logger.Error(CultureInfo.InvariantCulture, "message{0}", false);
if (enabled == 1) AssertDebugLastMessage("debug", "messageFalse");
logger.Error(CultureInfo.InvariantCulture, "message{0}", (float)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Error(CultureInfo.InvariantCulture, "message{0}", 2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Error(CultureInfo.InvariantCulture, "message{0}", (decimal)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
#pragma warning disable 0618
// Obsolete method requires testing until completely removed.
logger.ErrorException("message", new Exception("test"));
if (enabled == 1) AssertDebugLastMessage("debug", "message");
#pragma warning restore 0618
logger.Error(new Exception("test"), "message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.Error(delegate { return "message from lambda"; });
if (enabled == 1) AssertDebugLastMessage("debug", "message from lambda");
if (enabled == 0)
AssertDebugCounter("debug", 0);
}
}
[Fact]
public void FatalTest()
{
// test all possible overloads of the Fatal() method
for (int enabled = 0; enabled < 2; ++enabled)
{
if (enabled == 0)
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='' writeTo='debug' />
</rules>
</nlog>");
}
else
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='Fatal' writeTo='debug' />
</rules>
</nlog>");
}
ILogger logger = LogManager.GetLogger("A");
logger.Fatal("message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.Fatal("message{0}", (ulong)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (ulong)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Fatal("message{0}", (long)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (long)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Fatal("message{0}", (uint)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (uint)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Fatal("message{0}", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Fatal("message{0}", (ushort)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (ushort)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Fatal("message{0}", (sbyte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (sbyte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Fatal("message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.Fatal("message{0}", (short)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (short)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Fatal("message{0}", (byte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (byte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Fatal("message{0}", 'c');
if (enabled == 1) AssertDebugLastMessage("debug", "messagec");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", 'd');
if (enabled == 1) AssertDebugLastMessage("debug", "messaged");
logger.Fatal("message{0}", "ddd");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee");
logger.Fatal("message{0}{1}", "ddd", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2");
logger.Fatal("message{0}{1}{2}", "ddd", 1, "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1eee");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fff");
logger.Fatal("message{0}{1}{2}{3}", "eee", 2, "fff", "ggg");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fffggg");
logger.Fatal("message{0}", true);
if (enabled == 1) AssertDebugLastMessage("debug", "messageTrue");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", false);
if (enabled == 1) AssertDebugLastMessage("debug", "messageFalse");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (float)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", 2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (decimal)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
#pragma warning disable 0618
// Obsolete method requires testing until removed.
logger.FatalException("message", new Exception("test"));
if (enabled == 1) AssertDebugLastMessage("debug", "message");
#pragma warning restore 0618
logger.Fatal(new Exception("test"), "message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.Fatal(delegate { return "message from lambda"; });
if (enabled == 1) AssertDebugLastMessage("debug", "message from lambda");
if (enabled == 0)
AssertDebugCounter("debug", 0);
}
}
[Fact]
public void LogTest()
{
// test all possible overloads of the Log(level) method
foreach (LogLevel level in new LogLevel[] { LogLevel.Debug, LogLevel.Info, LogLevel.Warn, LogLevel.Error, LogLevel.Fatal })
{
for (int enabled = 0; enabled < 2; ++enabled)
{
if (enabled == 0)
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='' writeTo='debug' />
</rules>
</nlog>");
}
else
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='" + level.Name + @"' writeTo='debug' />
</rules>
</nlog>");
}
ILogger logger = LogManager.GetLogger("A");
logger.Log(level, "message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.Log(level, "message{0}", (ulong)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (ulong)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Log(level, "message{0}", (long)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (long)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Log(level, "message{0}", (uint)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (uint)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Log(level, "message{0}", (int)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (int)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Log(level, "message{0}", (ushort)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (ushort)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Log(level, "message{0}", (sbyte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (sbyte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Log(level, "message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.Log(level, "message{0}", (short)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (short)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Log(level, "message{0}", (byte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (byte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Log(level, "message{0}", 'c');
if (enabled == 1) AssertDebugLastMessage("debug", "messagec");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", 'd');
if (enabled == 1) AssertDebugLastMessage("debug", "messaged");
logger.Log(level, "message{0}", "ddd");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee");
logger.Log(level, "message{0}{1}", "ddd", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2");
logger.Log(level, "message{0}{1}{2}", "ddd", 1, "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1eee");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fff");
logger.Log(level, "message{0}{1}{2}{3}", "eee", 2, "fff", "ggg");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fffggg");
logger.Log(level, "message{0}", true);
if (enabled == 1) AssertDebugLastMessage("debug", "messageTrue");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", false);
if (enabled == 1) AssertDebugLastMessage("debug", "messageFalse");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (float)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (double)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (decimal)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Log(level, new Exception("test"), "message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
#pragma warning disable 0618
// Obsolete method requires testing until removed.
logger.LogException(level, "message", new Exception("test"));
if (enabled == 1) AssertDebugLastMessage("debug", "message");
#pragma warning restore 0618
logger.Log(level, delegate { return "message from lambda"; });
if (enabled == 1) AssertDebugLastMessage("debug", "message from lambda");
if (enabled == 0)
AssertDebugCounter("debug", 0);
}
}
}
#region Conditional Logger
#if DEBUG
[Fact]
public void ConditionalTraceTest()
{
// test all possible overloads of the Trace() method
for (int enabled = 0; enabled < 2; ++enabled)
{
if (enabled == 0)
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='' writeTo='debug' />
</rules>
</nlog>");
}
else
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='Trace' writeTo='debug' />
</rules>
</nlog>");
}
var logger = LogManager.GetLogger("A");
logger.ConditionalTrace("message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.ConditionalTrace("message{0}", (ulong)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (ulong)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalTrace("message{0}", (long)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (long)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalTrace("message{0}", (uint)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (uint)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalTrace("message{0}", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalTrace("message{0}", (ushort)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (ushort)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalTrace("message{0}", (sbyte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (sbyte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalTrace("message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.ConditionalTrace("message{0}", (short)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (short)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalTrace("message{0}", (byte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (byte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalTrace("message{0}", 'c');
if (enabled == 1) AssertDebugLastMessage("debug", "messagec");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", 'd');
if (enabled == 1) AssertDebugLastMessage("debug", "messaged");
logger.ConditionalTrace("message{0}", "ddd");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee");
logger.ConditionalTrace("message{0}{1}", "ddd", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2");
logger.ConditionalTrace("message{0}{1}{2}", "ddd", 1, "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1eee");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fff");
logger.ConditionalTrace("message{0}{1}{2}{3}", "eee", 2, "fff", "ggg");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fffggg");
logger.ConditionalTrace("message{0}", true);
if (enabled == 1) AssertDebugLastMessage("debug", "messageTrue");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", false);
if (enabled == 1) AssertDebugLastMessage("debug", "messageFalse");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (float)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", 2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (decimal)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.ConditionalTrace(new Exception("test"), "message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.ConditionalTrace(delegate { return "message from lambda"; });
if (enabled == 1) AssertDebugLastMessage("debug", "message from lambda");
if (enabled == 0)
AssertDebugCounter("debug", 0);
}
}
[Fact]
public void ConditionalDebugTest()
{
// test all possible overloads of the Debug() method
for (int enabled = 0; enabled < 2; ++enabled)
{
if (enabled == 0)
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='' writeTo='debug' />
</rules>
</nlog>");
}
else
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='Debug' writeTo='debug' />
</rules>
</nlog>");
}
var logger = LogManager.GetLogger("A");
logger.ConditionalDebug("message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.ConditionalDebug("message{0}", (ulong)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (ulong)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalDebug("message{0}", (long)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (long)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalDebug("message{0}", (uint)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (uint)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalDebug("message{0}", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalDebug("message{0}", (ushort)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (ushort)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalDebug("message{0}", (sbyte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (sbyte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalDebug("message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.ConditionalDebug("message{0}", (short)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (short)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalDebug("message{0}", (byte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (byte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalDebug("message{0}", 'c');
if (enabled == 1) AssertDebugLastMessage("debug", "messagec");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", 'd');
if (enabled == 1) AssertDebugLastMessage("debug", "messaged");
logger.ConditionalDebug("message{0}", "ddd");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee");
logger.ConditionalDebug("message{0}{1}", "ddd", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2");
logger.ConditionalDebug("message{0}{1}{2}", "ddd", 1, "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1eee");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fff");
logger.ConditionalDebug("message{0}{1}{2}{3}", "eee", 2, "fff", "ggg");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fffggg");
logger.ConditionalDebug("message{0}", true);
if (enabled == 1) AssertDebugLastMessage("debug", "messageTrue");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", false);
if (enabled == 1) AssertDebugLastMessage("debug", "messageFalse");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (float)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", 2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (decimal)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.ConditionalDebug(delegate { return "message from lambda"; });
if (enabled == 1) AssertDebugLastMessage("debug", "message from lambda");
if (enabled == 0)
AssertDebugCounter("debug", 0);
}
}
#endif
#endregion
[Fact]
public void SwallowTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='Error' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
bool warningFix = true;
bool executed = false;
logger.Swallow(() => executed = true);
Assert.True(executed);
Assert.Equal(1, logger.Swallow(() => 1));
Assert.Equal(1, logger.Swallow(() => 1, 2));
#if ASYNC_SUPPORTED
logger.SwallowAsync(Task.WhenAll()).Wait();
executed = false;
logger.SwallowAsync(async () => { await Task.Delay(20); executed = true; }).Wait();
Assert.True(executed);
Assert.Equal(1, logger.SwallowAsync(async () => { await Task.Delay(20); return 1; }).Result);
Assert.Equal(1, logger.SwallowAsync(async () => { await Task.Delay(20); return 1; }, 2).Result);
#endif
AssertDebugCounter("debug", 0);
logger.Swallow(() => { throw new InvalidOperationException("Test message 1"); });
AssertDebugLastMessageContains("debug", "Test message 1");
Assert.Equal(0, logger.Swallow(() => { if (warningFix) throw new InvalidOperationException("Test message 2"); return 1; }));
AssertDebugLastMessageContains("debug", "Test message 2");
Assert.Equal(2, logger.Swallow(() => { if (warningFix) throw new InvalidOperationException("Test message 3"); return 1; }, 2));
AssertDebugLastMessageContains("debug", "Test message 3");
#if ASYNC_SUPPORTED
var completion = new TaskCompletionSource<bool>();
completion.SetException(new InvalidOperationException("Test message 4"));
logger.SwallowAsync(completion.Task).Wait();
AssertDebugLastMessageContains("debug", "Test message 4");
logger.SwallowAsync(async () => { await Task.Delay(20); throw new InvalidOperationException("Test message 5"); }).Wait();
AssertDebugLastMessageContains("debug", "Test message 5");
Assert.Equal(0, logger.SwallowAsync(async () => { await Task.Delay(20); if (warningFix) throw new InvalidOperationException("Test message 6"); return 1; }).Result);
AssertDebugLastMessageContains("debug", "Test message 6");
Assert.Equal(2, logger.SwallowAsync(async () => { await Task.Delay(20); if (warningFix) throw new InvalidOperationException("Test message 7"); return 1; }, 2).Result);
AssertDebugLastMessageContains("debug", "Test message 7");
#endif
}
[Fact]
public void StringFormatWillNotCauseExceptions()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog throwExceptions='true'>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' minLevel='Info' writeTo='debug' />
</rules>
</nlog>");
ILogger l = LogManager.GetLogger("StringFormatWillNotCauseExceptions");
// invalid format string
l.Info("aaaa {0");
AssertDebugLastMessage("debug", "aaaa {0");
}
[Fact]
public void MultipleLoggersWithSameNameShouldBothReceiveMessages()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='first' type='Debug' layout='${message}' />
<target name='second' type='Debug' layout='${message}' />
</targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='first' />
<logger name='*' minlevel='Debug' writeTo='second' />
</rules>
</nlog>");
var logger = LogManager.GetLogger("A");
const string logMessage = "Anything";
logger.Debug(logMessage);
AssertDebugLastMessage("first", logMessage);
AssertDebugLastMessage("second", logMessage);
}
[Fact]
public void When_Logging_LogEvent_Without_Level_Defined_No_Exception_Should_Be_Thrown()
{
var config = new LoggingConfiguration();
var target = new MyTarget();
config.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, target));
LogManager.Configuration = config;
var logger = LogManager.GetLogger("A");
Assert.Throws<InvalidOperationException>(() => logger.Log(new LogEventInfo()));
}
public abstract class BaseWrapper
{
public void Log(string what)
{
InternalLog(what);
}
protected abstract void InternalLog(string what);
}
public class MyWrapper : BaseWrapper
{
private readonly ILogger wrapperLogger;
public MyWrapper()
{
wrapperLogger = LogManager.GetLogger("WrappedLogger");
}
protected override void InternalLog(string what)
{
LogEventInfo info = new LogEventInfo(LogLevel.Warn, wrapperLogger.Name, what);
// Provide BaseWrapper as wrapper type.
// Expected: UserStackFrame should point to the method that calls a
// method of BaseWrapper.
wrapperLogger.Log(typeof(BaseWrapper), info);
}
}
public class MyTarget : TargetWithLayout
{
public MyTarget()
{
// enforce creation of stack trace
Layout = "${stacktrace}";
}
public LogEventInfo LastEvent { get; private set; }
protected override void Write(LogEventInfo logEvent)
{
LastEvent = logEvent;
base.Write(logEvent);
}
}
public override string ToString()
{
return "object-to-string";
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright>
// Copyright (C) Ruslan Yakushev for the PHP Manager for IIS project.
//
// This file is subject to the terms and conditions of the Microsoft Public License (MS-PL).
// See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL for more details.
// </copyright>
//-----------------------------------------------------------------------
//#define VSDesigner
using System;
using System.Windows.Forms;
using Microsoft.Web.Management.Client.Win32;
namespace Web.Management.PHP.Extensions
{
internal sealed class AddExtensionDialog :
#if VSDesigner
Form
#else
TaskForm
#endif
{
private PHPModule _module;
private bool _isLocalConnection;
private bool _canAccept;
private ManagementPanel _contentPanel;
private TextBox _extensionPathTextBox;
private Button _browseButton;
private Label _exampleLabel;
private Label _pathToExtenionLabel;
private string _addedExtensionName;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
public string AddedExtensionName
{
get
{
return _addedExtensionName;
}
}
public AddExtensionDialog(PHPModule module, bool isLocalConnection) : base(module)
{
_module = module;
_isLocalConnection = isLocalConnection;
InitializeComponent();
InitializeUI();
}
protected override bool CanAccept
{
get
{
return _canAccept;
}
}
protected override bool CanShowHelp
{
get
{
return true;
}
}
/// <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);
}
private void InitializeComponent()
{
this._pathToExtenionLabel = new System.Windows.Forms.Label();
this._extensionPathTextBox = new System.Windows.Forms.TextBox();
this._browseButton = new System.Windows.Forms.Button();
this._exampleLabel = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// _pathToExtenionLabel
//
this._pathToExtenionLabel.AutoSize = true;
this._pathToExtenionLabel.Location = new System.Drawing.Point(0, 13);
this._pathToExtenionLabel.Name = "_pathToExtenionLabel";
this._pathToExtenionLabel.Size = new System.Drawing.Size(193, 13);
this._pathToExtenionLabel.TabIndex = 0;
this._pathToExtenionLabel.Text = Resources.AddExtensionDialogProvidePath;
//
// _extensionPathTextBox
//
this._extensionPathTextBox.Location = new System.Drawing.Point(3, 30);
this._extensionPathTextBox.Name = "_extensionPathTextBox";
this._extensionPathTextBox.Size = new System.Drawing.Size(371, 20);
this._extensionPathTextBox.TabIndex = 1;
this._extensionPathTextBox.TextChanged += new System.EventHandler(this.OnExtensionPathTextBoxTextChanged);
//
// _browseButton
//
this._browseButton.Location = new System.Drawing.Point(380, 28);
this._browseButton.Name = "_browseButton";
this._browseButton.Size = new System.Drawing.Size(27, 23);
this._browseButton.TabIndex = 2;
this._browseButton.Text = "...";
this._browseButton.UseVisualStyleBackColor = true;
this._browseButton.Click += new System.EventHandler(this.OnBrowseButtonClick);
//
// _exampleLabel
//
this._exampleLabel.AutoSize = true;
this._exampleLabel.Location = new System.Drawing.Point(0, 53);
this._exampleLabel.Name = "_exampleLabel";
this._exampleLabel.Size = new System.Drawing.Size(159, 13);
this._exampleLabel.TabIndex = 3;
this._exampleLabel.Text = Resources.AddExtensionDialogExample;
//
// AddExtensionDialog
//
this.ClientSize = new System.Drawing.Size(434, 142);
this.Controls.Add(this._exampleLabel);
this.Controls.Add(this._browseButton);
this.Controls.Add(this._extensionPathTextBox);
this.Controls.Add(this._pathToExtenionLabel);
this.Name = "AddExtensionDialog";
this.ResumeLayout(false);
this.ResumeLayout(false);
#if VSDesigner
this.PerformLayout();
#endif
}
private void InitializeUI()
{
_contentPanel = new ManagementPanel();
_contentPanel.SuspendLayout();
// Only show the auto suggest if it is a local connection.
// Otherwise do not show auto suggest and also hide the browse button.
if (_isLocalConnection)
{
this._extensionPathTextBox.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest;
this._extensionPathTextBox.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.FileSystem;
}
else
{
this._browseButton.Visible = false;
}
this._contentPanel.Location = new System.Drawing.Point(0, 0);
this._contentPanel.Dock = DockStyle.Fill;
this._contentPanel.Controls.Add(_pathToExtenionLabel);
this._contentPanel.Controls.Add(_extensionPathTextBox);
this._contentPanel.Controls.Add(_browseButton);
this._contentPanel.Controls.Add(_exampleLabel);
this._contentPanel.ResumeLayout(false);
this._contentPanel.PerformLayout();
this.Text = Resources.AddExtensionDialogAddExtension;
SetContent(_contentPanel);
UpdateTaskForm();
}
protected override void OnAccept()
{
try
{
string path = _extensionPathTextBox.Text.Trim();
_addedExtensionName = _module.Proxy.AddExtension(path);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
DisplayErrorMessage(ex, Resources.ResourceManager);
}
}
private void OnBrowseButtonClick(object sender, EventArgs e)
{
using (OpenFileDialog dlg = new OpenFileDialog())
{
dlg.Title = Resources.AddExtensionDialogOpenFileTitle;
dlg.Filter = Resources.AddExtensionDialogOpenFileFilter;
if (!String.IsNullOrEmpty(_extensionPathTextBox.Text))
{
dlg.InitialDirectory = System.IO.Path.GetDirectoryName(_extensionPathTextBox.Text.Trim());
}
else
{
dlg.InitialDirectory = Environment.ExpandEnvironmentVariables("%SystemDrive%");
}
if (dlg.ShowDialog() == DialogResult.OK)
{
_extensionPathTextBox.Text = dlg.FileName;
}
}
}
private void OnExtensionPathTextBoxTextChanged(object sender, EventArgs e)
{
string path = _extensionPathTextBox .Text.Trim();
_canAccept = !String.IsNullOrEmpty(path);
UpdateTaskForm();
}
protected override void ShowHelp()
{
Helper.Browse(Globals.AddExtensionOnlineHelp);
}
}
}
| |
// Visual Studio Shared Project
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using VSLangProj;
using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
namespace Microsoft.VisualStudioTools.Project {
/// <summary>
/// All public properties on Nodeproperties or derived classes are assumed to be used by Automation by default.
/// Set this attribute to false on Properties that should not be visible for Automation.
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class AutomationBrowsableAttribute : System.Attribute {
public AutomationBrowsableAttribute(bool browsable) {
this.browsable = browsable;
}
public bool Browsable {
get {
return this.browsable;
}
}
private bool browsable;
}
/// <summary>
/// This attribute is used to mark properties that shouldn't be serialized. Marking properties with this will
/// result in them not being serialized and not being bold in the properties pane.
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
internal sealed class AlwaysSerializedAttribute : Attribute {
public AlwaysSerializedAttribute() { }
}
/// <summary>
/// To create your own localizable node properties, subclass this and add public properties
/// decorated with your own localized display name, category and description attributes.
/// </summary>
[ComVisible(true)]
public class NodeProperties : LocalizableProperties,
ISpecifyPropertyPages,
IVsGetCfgProvider,
IVsSpecifyProjectDesignerPages,
IVsBrowseObject {
#region fields
private HierarchyNode node;
#endregion
#region properties
[Browsable(false)]
[AutomationBrowsable(true)]
public object Node {
get { return this.node; }
}
internal HierarchyNode HierarchyNode {
get { return this.node; }
}
/// <summary>
/// Used by Property Pages Frame to set it's title bar. The Caption of the Hierarchy Node is returned.
/// </summary>
[Browsable(false)]
[AutomationBrowsable(false)]
public virtual string Name {
get { return this.node.Caption; }
}
#endregion
#region ctors
internal NodeProperties(HierarchyNode node) {
Utilities.ArgumentNotNull("node", node);
this.node = node;
}
#endregion
#region ISpecifyPropertyPages methods
public virtual void GetPages(CAUUID[] pages) {
this.GetCommonPropertyPages(pages);
}
#endregion
#region IVsSpecifyProjectDesignerPages
/// <summary>
/// Implementation of the IVsSpecifyProjectDesignerPages. It will retun the pages that are configuration independent.
/// </summary>
/// <param name="pages">The pages to return.</param>
/// <returns></returns>
public virtual int GetProjectDesignerPages(CAUUID[] pages) {
this.GetCommonPropertyPages(pages);
return VSConstants.S_OK;
}
#endregion
#region IVsGetCfgProvider methods
public virtual int GetCfgProvider(out IVsCfgProvider p) {
p = null;
return VSConstants.E_NOTIMPL;
}
#endregion
#region IVsBrowseObject methods
/// <summary>
/// Maps back to the hierarchy or project item object corresponding to the browse object.
/// </summary>
/// <param name="hier">Reference to the hierarchy object.</param>
/// <param name="itemid">Reference to the project item.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns>
public virtual int GetProjectItem(out IVsHierarchy hier, out uint itemid) {
Utilities.CheckNotNull(node);
hier = node.ProjectMgr.GetOuterInterface<IVsHierarchy>();
itemid = this.node.ID;
return VSConstants.S_OK;
}
#endregion
#region overridden methods
/// <summary>
/// Get the Caption of the Hierarchy Node instance. If Caption is null or empty we delegate to base
/// </summary>
/// <returns>Caption of Hierarchy node instance</returns>
public override string GetComponentName() {
string caption = this.HierarchyNode.Caption;
if (string.IsNullOrEmpty(caption)) {
return base.GetComponentName();
} else {
return caption;
}
}
#endregion
#region helper methods
protected string GetProperty(string name, string def) {
string a = this.HierarchyNode.ItemNode.GetMetadata(name);
return (a == null) ? def : a;
}
protected void SetProperty(string name, string value) {
this.HierarchyNode.ItemNode.SetMetadata(name, value);
}
/// <summary>
/// Retrieves the common property pages. The NodeProperties is the BrowseObject and that will be called to support
/// configuration independent properties.
/// </summary>
/// <param name="pages">The pages to return.</param>
private void GetCommonPropertyPages(CAUUID[] pages) {
// We do not check whether the supportsProjectDesigner is set to false on the ProjectNode.
// We rely that the caller knows what to call on us.
Utilities.ArgumentNotNull("pages", pages);
if (pages.Length == 0) {
throw new ArgumentException(SR.GetString(SR.InvalidParameter), "pages");
}
// Only the project should show the property page the rest should show the project properties.
if (this.node != null && (this.node is ProjectNode)) {
// Retrieve the list of guids from hierarchy properties.
// Because a flavor could modify that list we must make sure we are calling the outer most implementation of IVsHierarchy
string guidsList = String.Empty;
IVsHierarchy hierarchy = HierarchyNode.ProjectMgr.GetOuterInterface<IVsHierarchy>();
object variant = null;
ErrorHandler.ThrowOnFailure(hierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID2.VSHPROPID_PropertyPagesCLSIDList, out variant));
guidsList = (string)variant;
Guid[] guids = Utilities.GuidsArrayFromSemicolonDelimitedStringOfGuids(guidsList);
if (guids == null || guids.Length == 0) {
pages[0] = new CAUUID();
pages[0].cElems = 0;
} else {
pages[0] = PackageUtilities.CreateCAUUIDFromGuidArray(guids);
}
} else {
pages[0] = new CAUUID();
pages[0].cElems = 0;
}
}
#endregion
#region ExtenderSupport
[Browsable(false)]
public virtual string ExtenderCATID {
get {
Guid catid = this.HierarchyNode.ProjectMgr.GetCATIDForType(this.GetType());
if (Guid.Empty.CompareTo(catid) == 0) {
return null;
}
return catid.ToString("B");
}
}
[Browsable(false)]
public object ExtenderNames() {
EnvDTE.ObjectExtenders extenderService = (EnvDTE.ObjectExtenders)this.HierarchyNode.GetService(typeof(EnvDTE.ObjectExtenders));
Utilities.CheckNotNull(extenderService, "Could not get the ObjectExtenders object from the services exposed by this property object");
return extenderService.GetExtenderNames(this.ExtenderCATID, this);
}
public object Extender(string extenderName) {
EnvDTE.ObjectExtenders extenderService = (EnvDTE.ObjectExtenders)this.HierarchyNode.GetService(typeof(EnvDTE.ObjectExtenders));
Utilities.CheckNotNull(extenderService, "Could not get the ObjectExtenders object from the services exposed by this property object");
return extenderService.GetExtender(this.ExtenderCATID, extenderName, this);
}
#endregion
}
[ComVisible(true)]
public class FileNodeProperties : NodeProperties {
#region properties
[SRCategoryAttribute(SR.Misc)]
[SRDisplayName(SR.FileName)]
[SRDescriptionAttribute(SR.FileNameDescription)]
[AlwaysSerialized]
public virtual string FileName {
get {
return this.HierarchyNode.Caption;
}
set {
this.HierarchyNode.SetEditLabel(value);
}
}
[SRCategoryAttribute(SR.Misc)]
[SRDisplayName(SR.FullPath)]
[SRDescriptionAttribute(SR.FullPathDescription)]
public string FullPath {
get {
return this.HierarchyNode.Url;
}
}
#region non-browsable properties - used for automation only
[Browsable(false)]
public string URL {
get {
return this.HierarchyNode.Url;
}
}
[Browsable(false)]
public string Extension {
get {
return Path.GetExtension(this.HierarchyNode.Caption);
}
}
[Browsable(false)]
public bool IsLinkFile {
get {
return HierarchyNode.IsLinkFile;
}
}
#endregion
#endregion
#region ctors
internal FileNodeProperties(HierarchyNode node)
: base(node) {
}
#endregion
public override string GetClassName() {
return SR.GetString(SR.FileProperties);
}
}
[ComVisible(true)]
public class ExcludedFileNodeProperties : FileNodeProperties {
internal ExcludedFileNodeProperties(HierarchyNode node)
: base(node) {
}
[SRCategoryAttribute(SR.Advanced)]
[SRDisplayName(SR.BuildAction)]
[SRDescriptionAttribute(SR.BuildActionDescription)]
[TypeConverter(typeof(BuildActionTypeConverter))]
public prjBuildAction BuildAction {
get {
return prjBuildAction.prjBuildActionNone;
}
}
}
[ComVisible(true)]
public class IncludedFileNodeProperties : FileNodeProperties {
internal IncludedFileNodeProperties(HierarchyNode node)
: base(node) {
}
/// <summary>
/// Specifies the build action as a string so the user can configure it to any value.
/// </summary>
[SRCategoryAttribute(SR.Advanced)]
[SRDisplayName(SR.BuildAction)]
[SRDescriptionAttribute(SR.BuildActionDescription)]
[AlwaysSerialized]
[TypeConverter(typeof(BuildActionStringConverter))]
public string ItemType {
get {
return HierarchyNode.ItemNode.ItemTypeName;
}
set {
HierarchyNode.ItemNode.ItemTypeName = value;
}
}
/// <summary>
/// Specifies the build action as a projBuildAction so that automation can get the
/// expected enum value.
/// </summary>
[Browsable(false)]
public prjBuildAction BuildAction {
get {
var res = BuildActionTypeConverter.Instance.ConvertFromString(HierarchyNode.ItemNode.ItemTypeName);
if (res is prjBuildAction) {
return (prjBuildAction)res;
}
return prjBuildAction.prjBuildActionContent;
}
set {
this.HierarchyNode.ItemNode.ItemTypeName = BuildActionTypeConverter.Instance.ConvertToString(value);
}
}
[SRCategoryAttribute(SR.Advanced)]
[SRDisplayName(SR.Publish)]
[SRDescriptionAttribute(SR.PublishDescription)]
public bool Publish {
get {
var publish = this.HierarchyNode.ItemNode.GetMetadata("Publish");
if (String.IsNullOrEmpty(publish)) {
if (this.HierarchyNode.ItemNode.ItemTypeName == ProjectFileConstants.Compile) {
return true;
}
return false;
}
return Convert.ToBoolean(publish);
}
set {
this.HierarchyNode.ItemNode.SetMetadata("Publish", value.ToString());
}
}
[Browsable(false)]
public bool ShouldSerializePublish() {
// If compile, default should be true, else the default is false.
if (HierarchyNode.ItemNode.ItemTypeName == ProjectFileConstants.Compile) {
return !Publish;
}
return Publish;
}
[Browsable(false)]
public void ResetPublish() {
// If compile, default should be true, else the default is false.
if (HierarchyNode.ItemNode.ItemTypeName == ProjectFileConstants.Compile) {
Publish = true;
}
Publish = false;
}
[Browsable(false)]
public string SourceControlStatus {
get {
// remove STATEICON_ and return rest of enum
return HierarchyNode.StateIconIndex.ToString().Substring(10);
}
}
[Browsable(false)]
public string SubType {
get {
return this.HierarchyNode.ItemNode.GetMetadata("SubType");
}
set {
this.HierarchyNode.ItemNode.SetMetadata("SubType", value.ToString());
}
}
}
[ComVisible(true)]
public class LinkFileNodeProperties : FileNodeProperties {
internal LinkFileNodeProperties(HierarchyNode node)
: base(node) {
}
/// <summary>
/// Specifies the build action as a string so the user can configure it to any value.
/// </summary>
[SRCategoryAttribute(SR.Advanced)]
[SRDisplayName(SR.BuildAction)]
[SRDescriptionAttribute(SR.BuildActionDescription)]
[AlwaysSerialized]
[TypeConverter(typeof(BuildActionStringConverter))]
public string ItemType {
get {
return HierarchyNode.ItemNode.ItemTypeName;
}
set {
HierarchyNode.ItemNode.ItemTypeName = value;
}
}
[SRCategoryAttribute(SR.Misc)]
[SRDisplayName(SR.FileName)]
[SRDescriptionAttribute(SR.FileNameDescription)]
[ReadOnly(true)]
public override string FileName {
get {
return this.HierarchyNode.Caption;
}
set {
throw new InvalidOperationException();
}
}
}
[ComVisible(true)]
public class DependentFileNodeProperties : NodeProperties {
#region properties
[SRCategoryAttribute(SR.Misc)]
[SRDisplayName(SR.FileName)]
[SRDescriptionAttribute(SR.FileNameDescription)]
public virtual string FileName {
get {
return this.HierarchyNode.Caption;
}
}
[SRCategoryAttribute(SR.Misc)]
[SRDisplayName(SR.FullPath)]
[SRDescriptionAttribute(SR.FullPathDescription)]
public string FullPath {
get {
return this.HierarchyNode.Url;
}
}
#endregion
#region ctors
internal DependentFileNodeProperties(HierarchyNode node)
: base(node) {
}
#endregion
public override string GetClassName() {
return SR.GetString(SR.FileProperties);
}
}
class BuildActionTypeConverter : StringConverter {
internal static readonly BuildActionTypeConverter Instance = new BuildActionTypeConverter();
public BuildActionTypeConverter() {
}
public override bool GetStandardValuesSupported(ITypeDescriptorContext context) {
return true;
}
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) {
if (sourceType == typeof(string)) {
return true;
}
return base.CanConvertFrom(context, sourceType);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) {
return base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) {
if (destinationType == typeof(string)) {
switch ((prjBuildAction)value) {
case prjBuildAction.prjBuildActionCompile:
return ProjectFileConstants.Compile;
case prjBuildAction.prjBuildActionContent:
return ProjectFileConstants.Content;
case prjBuildAction.prjBuildActionNone:
return ProjectFileConstants.None;
}
}
return base.ConvertTo(context, culture, value, destinationType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) {
if (value is string) {
string strVal = (string)value;
if (strVal.Equals(ProjectFileConstants.Compile, StringComparison.OrdinalIgnoreCase)) {
return prjBuildAction.prjBuildActionCompile;
} else if (strVal.Equals(ProjectFileConstants.Content, StringComparison.OrdinalIgnoreCase)) {
return prjBuildAction.prjBuildActionContent;
} else if (strVal.Equals(ProjectFileConstants.None, StringComparison.OrdinalIgnoreCase)) {
return prjBuildAction.prjBuildActionNone;
}
}
return base.ConvertFrom(context, culture, value);
}
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) {
return new StandardValuesCollection(new[] { prjBuildAction.prjBuildActionNone, prjBuildAction.prjBuildActionCompile, prjBuildAction.prjBuildActionContent });
}
}
/// <summary>
/// This type converter doesn't really do any conversions, but allows us to provide
/// a list of standard values for the build action.
/// </summary>
class BuildActionStringConverter : StringConverter {
internal static readonly BuildActionStringConverter Instance = new BuildActionStringConverter();
public BuildActionStringConverter() {
}
public override bool GetStandardValuesSupported(ITypeDescriptorContext context) {
return true;
}
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) {
if (sourceType == typeof(string)) {
return true;
}
return base.CanConvertFrom(context, sourceType);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) {
return base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) {
return value;
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) {
return value;
}
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) {
FileNodeProperties nodeProps = context.Instance as FileNodeProperties;
IEnumerable<string> itemNames;
if (nodeProps != null) {
itemNames = nodeProps.HierarchyNode.ProjectMgr.GetAvailableItemNames();
} else {
itemNames = new[] { ProjectFileConstants.None, ProjectFileConstants.Compile, ProjectFileConstants.Content };
}
return new StandardValuesCollection(itemNames.ToArray());
}
}
[ComVisible(true)]
public class ProjectNodeProperties : NodeProperties, EnvDTE80.IInternalExtenderProvider {
#region properties
[SRCategoryAttribute(SR.Misc)]
[SRDisplayName(SR.ProjectFolder)]
[SRDescriptionAttribute(SR.ProjectFolderDescription)]
[AutomationBrowsable(false)]
public string ProjectFolder {
get {
return this.Node.ProjectMgr.ProjectFolder;
}
}
[SRCategoryAttribute(SR.Misc)]
[SRDisplayName(SR.ProjectFile)]
[SRDescriptionAttribute(SR.ProjectFileDescription)]
[AutomationBrowsable(false)]
public string ProjectFile {
get {
return this.Node.ProjectMgr.ProjectFile;
}
set {
this.Node.ProjectMgr.ProjectFile = value;
}
}
#region non-browsable properties - used for automation only
[Browsable(false)]
public string Guid {
get {
return this.Node.ProjectMgr.ProjectIDGuid.ToString();
}
}
[Browsable(false)]
public string FileName {
get {
return this.Node.ProjectMgr.ProjectFile;
}
set {
this.Node.ProjectMgr.ProjectFile = value;
}
}
[Browsable(false)]
public string FullPath {
get {
return CommonUtils.NormalizeDirectoryPath(this.Node.ProjectMgr.ProjectFolder);
}
}
#endregion
#endregion
#region ctors
internal ProjectNodeProperties(ProjectNode node)
: base(node) {
}
internal new ProjectNode Node {
get {
return (ProjectNode)base.Node;
}
}
#endregion
#region overridden methods
/// <summary>
/// ICustomTypeDescriptor.GetEditor
/// To enable the "Property Pages" button on the properties browser
/// the browse object (project properties) need to be unmanaged
/// or it needs to provide an editor of type ComponentEditor.
/// </summary>
/// <param name="editorBaseType">Type of the editor</param>
/// <returns>Editor</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope",
Justification = "The service provider is used by the PropertiesEditorLauncher")]
public override object GetEditor(Type editorBaseType) {
// Override the scenario where we are asked for a ComponentEditor
// as this is how the Properties Browser calls us
if (editorBaseType == typeof(ComponentEditor)) {
IOleServiceProvider sp;
ErrorHandler.ThrowOnFailure(Node.ProjectMgr.GetSite(out sp));
return new PropertiesEditorLauncher(new ServiceProvider(sp));
}
return base.GetEditor(editorBaseType);
}
public override int GetCfgProvider(out IVsCfgProvider p) {
if (this.Node != null && this.Node.ProjectMgr != null) {
return this.Node.ProjectMgr.GetCfgProvider(out p);
}
return base.GetCfgProvider(out p);
}
public override string GetClassName() {
return SR.GetString(SR.ProjectProperties);
}
#endregion
#region IInternalExtenderProvider Members
bool EnvDTE80.IInternalExtenderProvider.CanExtend(string extenderCATID, string extenderName, object extendeeObject) {
EnvDTE80.IInternalExtenderProvider outerHierarchy = Node.GetOuterInterface<EnvDTE80.IInternalExtenderProvider>();
if (outerHierarchy != null) {
return outerHierarchy.CanExtend(extenderCATID, extenderName, extendeeObject);
}
return false;
}
object EnvDTE80.IInternalExtenderProvider.GetExtender(string extenderCATID, string extenderName, object extendeeObject, EnvDTE.IExtenderSite extenderSite, int cookie) {
EnvDTE80.IInternalExtenderProvider outerHierarchy = Node.GetOuterInterface<EnvDTE80.IInternalExtenderProvider>();
if (outerHierarchy != null) {
return outerHierarchy.GetExtender(extenderCATID, extenderName, extendeeObject, extenderSite, cookie);
}
return null;
}
object EnvDTE80.IInternalExtenderProvider.GetExtenderNames(string extenderCATID, object extendeeObject) {
return null;
}
#endregion
}
[ComVisible(true)]
public class FolderNodeProperties : NodeProperties {
#region properties
[SRCategoryAttribute(SR.Misc)]
[SRDisplayName(SR.FolderName)]
[SRDescriptionAttribute(SR.FolderNameDescription)]
public string FolderName {
get {
return this.HierarchyNode.Caption;
}
set {
HierarchyNode.ProjectMgr.Site.GetUIThread().Invoke(() => {
this.HierarchyNode.SetEditLabel(value);
this.HierarchyNode.ProjectMgr.ReDrawNode(HierarchyNode, UIHierarchyElement.Caption);
});
}
}
#region properties - used for automation only
[Browsable(false)]
[AutomationBrowsable(true)]
public string FileName {
get {
return this.HierarchyNode.Caption;
}
set {
HierarchyNode.ProjectMgr.Site.GetUIThread().Invoke(() => {
this.HierarchyNode.SetEditLabel(value);
this.HierarchyNode.ProjectMgr.ReDrawNode(HierarchyNode, UIHierarchyElement.Caption);
});
}
}
[Browsable(true)]
[AutomationBrowsable(true)]
[SRCategoryAttribute(SR.Misc)]
[SRDisplayName(SR.FullPath)]
[SRDescriptionAttribute(SR.FullPathDescription)]
public string FullPath {
get {
return CommonUtils.NormalizeDirectoryPath(this.HierarchyNode.GetMkDocument());
}
}
#endregion
#endregion
#region ctors
internal FolderNodeProperties(HierarchyNode node)
: base(node) {
}
#endregion
public override string GetClassName() {
return SR.GetString(SR.FolderProperties);
}
}
[CLSCompliant(false), ComVisible(true)]
public class ReferenceNodeProperties : NodeProperties {
#region properties
[SRCategoryAttribute(SR.Misc)]
[SRDisplayName(SR.RefName)]
[SRDescriptionAttribute(SR.RefNameDescription)]
[Browsable(true)]
[AutomationBrowsable(true)]
public override string Name {
get {
return this.HierarchyNode.Caption;
}
}
[SRCategoryAttribute(SR.Misc)]
[SRDisplayName(SR.CopyToLocal)]
[SRDescriptionAttribute(SR.CopyToLocalDescription)]
public bool CopyToLocal {
get {
string copyLocal = this.GetProperty(ProjectFileConstants.Private, "False");
if (copyLocal == null || copyLocal.Length == 0)
return true;
return bool.Parse(copyLocal);
}
set {
this.SetProperty(ProjectFileConstants.Private, value.ToString());
}
}
[SRCategoryAttribute(SR.Misc)]
[SRDisplayName(SR.FullPath)]
[SRDescriptionAttribute(SR.FullPathDescription)]
public virtual string FullPath {
get {
return this.HierarchyNode.Url;
}
}
#endregion
#region ctors
internal ReferenceNodeProperties(HierarchyNode node)
: base(node) {
}
#endregion
#region overridden methods
public override string GetClassName() {
return SR.GetString(SR.ReferenceProperties);
}
#endregion
}
[ComVisible(true)]
public class ProjectReferencesProperties : ReferenceNodeProperties {
#region ctors
internal ProjectReferencesProperties(ProjectReferenceNode node)
: base(node) {
}
#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 System.Collections.Generic;
using System.Threading;
namespace Apache.Geode.Client.UnitTests
{
using NUnit.Framework;
using Apache.Geode.DUnitFramework;
using Apache.Geode.Client;
[TestFixture]
[Category("group1")]
[Category("unicast_only")]
[Category("generics")]
public class ThinClientRegionInterestFailoverRegexInterestTests : ThinClientRegionSteps
{
#region Private members and methods
private UnitProcess m_client1, m_client2, m_client3, m_feeder;
private static string[] m_regexes = { "Key-*1", "Key-*2",
"Key-*3", "Key-*4" };
private const string m_regex23 = "Key-[23]";
private const string m_regexWildcard = "Key-.*";
private const int m_numUnicodeStrings = 5;
private static string[] m_keysNonRegex = { "key-1", "key-2", "key-3" };
private static string[] m_keysForRegex = {"key-regex-1",
"key-regex-2", "key-regex-3" };
private static string[] RegionNamesForInterestNotify =
{ "RegionTrue", "RegionFalse", "RegionOther" };
string GetUnicodeString(int index)
{
return new string('\x0905', 40) + index.ToString("D10");
}
#endregion
protected override ClientBase[] GetClients()
{
m_client1 = new UnitProcess();
m_client2 = new UnitProcess();
m_client3 = new UnitProcess();
m_feeder = new UnitProcess();
return new ClientBase[] { m_client1, m_client2, m_client3, m_feeder };
}
[TestFixtureTearDown]
public override void EndTests()
{
CacheHelper.StopJavaServers();
base.EndTests();
}
[TearDown]
public override void EndTest()
{
try
{
m_client1.Call(DestroyRegions);
m_client2.Call(DestroyRegions);
CacheHelper.ClearEndpoints();
}
finally
{
CacheHelper.StopJavaServers();
}
base.EndTest();
}
#region Steps for Thin Client IRegion<object, object> with Interest
public void StepFourIL()
{
VerifyCreated(m_regionNames[0], m_keys[0]);
VerifyCreated(m_regionNames[1], m_keys[2]);
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]);
VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2]);
}
public void StepFourRegex3()
{
IRegion<object, object> region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
IRegion<object, object> region1 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[1]);
try
{
Util.Log("Registering empty regular expression.");
region0.GetSubscriptionService().RegisterRegex(string.Empty);
Assert.Fail("Did not get expected exception!");
}
catch (Exception ex)
{
Util.Log("Got expected exception {0}: {1}", ex.GetType(), ex.Message);
}
try
{
Util.Log("Registering null regular expression.");
region1.GetSubscriptionService().RegisterRegex(null);
Assert.Fail("Did not get expected exception!");
}
catch (Exception ex)
{
Util.Log("Got expected exception {0}: {1}", ex.GetType(), ex.Message);
}
try
{
Util.Log("Registering non-existent regular expression.");
region1.GetSubscriptionService().UnregisterRegex("Non*Existent*Regex*");
Assert.Fail("Did not get expected exception!");
}
catch (Exception ex)
{
Util.Log("Got expected exception {0}: {1}", ex.GetType(), ex.Message);
}
}
public void StepFourFailoverRegex()
{
VerifyCreated(m_regionNames[0], m_keys[0]);
VerifyCreated(m_regionNames[1], m_keys[2]);
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]);
VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2]);
UpdateEntry(m_regionNames[1], m_keys[1], m_vals[1], true);
UnregisterRegexes(null, m_regexes[2]);
}
public void StepFiveIL()
{
VerifyCreated(m_regionNames[0], m_keys[1]);
VerifyCreated(m_regionNames[1], m_keys[3]);
VerifyEntry(m_regionNames[0], m_keys[1], m_vals[1]);
VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3]);
UpdateEntry(m_regionNames[0], m_keys[0], m_nvals[0], false);
UpdateEntry(m_regionNames[1], m_keys[2], m_nvals[2], false);
}
public void StepFiveRegex()
{
CreateEntry(m_regionNames[0], m_keys[2], m_vals[2]);
CreateEntry(m_regionNames[1], m_keys[3], m_vals[3]);
}
public void CreateAllEntries(string regionName)
{
CreateEntry(regionName, m_keys[0], m_vals[0]);
CreateEntry(regionName, m_keys[1], m_vals[1]);
CreateEntry(regionName, m_keys[2], m_vals[2]);
CreateEntry(regionName, m_keys[3], m_vals[3]);
}
public void VerifyAllEntries(string regionName, bool newVal, bool checkVal)
{
string[] vals = newVal ? m_nvals : m_vals;
VerifyEntry(regionName, m_keys[0], vals[0], checkVal);
VerifyEntry(regionName, m_keys[1], vals[1], checkVal);
VerifyEntry(regionName, m_keys[2], vals[2], checkVal);
VerifyEntry(regionName, m_keys[3], vals[3], checkVal);
}
public void VerifyInvalidAll(string regionName, params string[] keys)
{
if (keys != null)
{
foreach (string key in keys)
{
VerifyInvalid(regionName, key);
}
}
}
public void UpdateAllEntries(string regionName, bool checkVal)
{
UpdateEntry(regionName, m_keys[0], m_nvals[0], checkVal);
UpdateEntry(regionName, m_keys[1], m_nvals[1], checkVal);
UpdateEntry(regionName, m_keys[2], m_nvals[2], checkVal);
UpdateEntry(regionName, m_keys[3], m_nvals[3], checkVal);
}
public void DoNetsearchAllEntries(string regionName, bool newVal,
bool checkNoKey)
{
string[] vals;
if (newVal)
{
vals = m_nvals;
}
else
{
vals = m_vals;
}
DoNetsearch(regionName, m_keys[0], vals[0], checkNoKey);
DoNetsearch(regionName, m_keys[1], vals[1], checkNoKey);
DoNetsearch(regionName, m_keys[2], vals[2], checkNoKey);
DoNetsearch(regionName, m_keys[3], vals[3], checkNoKey);
}
public void StepFiveFailoverRegex()
{
UpdateEntry(m_regionNames[0], m_keys[0], m_nvals[0], false);
UpdateEntry(m_regionNames[1], m_keys[2], m_nvals[2], false);
VerifyEntry(m_regionNames[1], m_keys[1], m_vals[1], false);
}
public void StepSixIL()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0]);
VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2]);
IRegion<object, object> region0 = CacheHelper.GetRegion<object, object>(m_regionNames[0]);
IRegion<object, object> region1 = CacheHelper.GetRegion<object, object>(m_regionNames[1]);
region0.Remove(m_keys[1]);
region1.Remove(m_keys[3]);
}
public void StepSixRegex()
{
CreateEntry(m_regionNames[0], m_keys[0], m_vals[0]);
CreateEntry(m_regionNames[1], m_keys[1], m_vals[1]);
VerifyEntry(m_regionNames[0], m_keys[2], m_vals[2]);
VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3]);
UnregisterRegexes(null, m_regexes[3]);
}
public void StepSixFailoverRegex()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0], false);
VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2], false);
UpdateEntry(m_regionNames[1], m_keys[1], m_nvals[1], false);
}
public void StepSevenIL()
{
VerifyDestroyed(m_regionNames[0], m_keys[1]);
VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3]);
}
public void StepSevenRegex()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]);
VerifyEntry(m_regionNames[1], m_keys[1], m_vals[1]);
UpdateEntry(m_regionNames[0], m_keys[2], m_nvals[2], true);
UpdateEntry(m_regionNames[1], m_keys[3], m_nvals[3], true);
UnregisterRegexes(null, m_regexes[1]);
}
public void StepSevenRegex2()
{
VerifyEntry(m_regionNames[0], m_keys[1], m_vals[1]);
VerifyEntry(m_regionNames[0], m_keys[2], m_vals[2]);
DoNetsearch(m_regionNames[0], m_keys[0], m_vals[0], true);
DoNetsearch(m_regionNames[0], m_keys[3], m_vals[3], true);
UpdateAllEntries(m_regionNames[1], true);
}
public void StepSevenInterestResultPolicyInv()
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
region.GetSubscriptionService().RegisterRegex(m_regex23);
VerifyInvalidAll(m_regionNames[0], m_keys[1], m_keys[2]);
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0], true);
VerifyEntry(m_regionNames[0], m_keys[3], m_vals[3], true);
}
public void StepSevenFailoverRegex()
{
UpdateEntry(m_regionNames[0], m_keys[0], m_vals[0], true);
UpdateEntry(m_regionNames[1], m_keys[2], m_vals[2], true);
VerifyEntry(m_regionNames[1], m_keys[1], m_nvals[1]);
}
public void StepEightIL()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0]);
VerifyEntry(m_regionNames[1], m_keys[2], m_nvals[2]);
}
public void StepEightRegex()
{
VerifyEntry(m_regionNames[0], m_keys[2], m_nvals[2]);
VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3]);
UpdateEntry(m_regionNames[0], m_keys[0], m_nvals[0], true);
UpdateEntry(m_regionNames[1], m_keys[1], m_nvals[1], true);
}
public void StepEightInterestResultPolicyInv()
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[1]);
region.GetSubscriptionService().RegisterAllKeys();
VerifyInvalidAll(m_regionNames[1], m_keys[0], m_keys[1],
m_keys[2], m_keys[3]);
UpdateAllEntries(m_regionNames[0], true);
}
public void StepEightFailoverRegex()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]);
VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2]);
}
public void StepNineRegex()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0]);
VerifyEntry(m_regionNames[1], m_keys[1], m_vals[1]);
}
public void StepNineRegex2()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]);
VerifyEntry(m_regionNames[0], m_keys[1], m_nvals[1]);
VerifyEntry(m_regionNames[0], m_keys[2], m_nvals[2]);
VerifyEntry(m_regionNames[0], m_keys[3], m_vals[3]);
}
public void StepNineInterestResultPolicyInv()
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
region.GetSubscriptionService().UnregisterRegex(m_regex23);
List<Object> keys = new List<Object>();
keys.Add(m_keys[0]);
keys.Add(m_keys[1]);
keys.Add(m_keys[2]);
region.GetSubscriptionService().RegisterKeys(keys);
VerifyInvalidAll(m_regionNames[0], m_keys[0], m_keys[1], m_keys[2]);
}
public void PutUnicodeKeys(string regionName, bool updates)
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(regionName);
string key;
object val;
for (int index = 0; index < m_numUnicodeStrings; ++index)
{
key = GetUnicodeString(index);
if (updates)
{
val = index + 100;
}
else
{
val = (float)index + 20.0F;
}
region[key] = val;
}
}
public void RegisterUnicodeKeys(string regionName)
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(regionName);
string[] keys = new string[m_numUnicodeStrings];
for (int index = 0; index < m_numUnicodeStrings; ++index)
{
keys[m_numUnicodeStrings - index - 1] = GetUnicodeString(index);
}
region.GetSubscriptionService().RegisterKeys(keys);
}
public void VerifyUnicodeKeys(string regionName, bool updates)
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(regionName);
string key;
object expectedVal;
for (int index = 0; index < m_numUnicodeStrings; ++index)
{
key = GetUnicodeString(index);
if (updates)
{
expectedVal = index + 100;
Assert.AreEqual(expectedVal, region.GetEntry(key).Value,
"Got unexpected value");
}
else
{
expectedVal = (float)index + 20.0F;
Assert.AreEqual(expectedVal, region[key],
"Got unexpected value");
}
}
}
public void CreateRegionsInterestNotify_Pool(string[] regionNames,
string locators, string poolName, bool notify, string nbs)
{
var props = Properties<string, string>.Create();
//props.Insert("notify-by-subscription-override", nbs);
CacheHelper.InitConfig(props);
CacheHelper.CreateTCRegion_Pool(regionNames[0], true, true,
new TallyListener<object, object>(), locators, poolName, notify);
CacheHelper.CreateTCRegion_Pool(regionNames[1], true, true,
new TallyListener<object, object>(), locators, poolName, notify);
CacheHelper.CreateTCRegion_Pool(regionNames[2], true, true,
new TallyListener<object, object>(), locators, poolName, notify);
}
/*
public void CreateRegionsInterestNotify(string[] regionNames,
string endpoints, bool notify, string nbs)
{
Properties props = Properties.Create();
//props.Insert("notify-by-subscription-override", nbs);
CacheHelper.InitConfig(props);
CacheHelper.CreateTCRegion(regionNames[0], true, false,
new TallyListener(), endpoints, notify);
CacheHelper.CreateTCRegion(regionNames[1], true, false,
new TallyListener(), endpoints, notify);
CacheHelper.CreateTCRegion(regionNames[2], true, false,
new TallyListener(), endpoints, notify);
}
* */
public void DoFeed()
{
foreach (string regionName in RegionNamesForInterestNotify)
{
IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName);
foreach (string key in m_keysNonRegex)
{
region[key] = "00";
}
foreach (string key in m_keysForRegex)
{
region[key] = "00";
}
}
}
public void DoFeederOps()
{
foreach (string regionName in RegionNamesForInterestNotify)
{
IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName);
foreach (string key in m_keysNonRegex)
{
region[key] = "11";
region[key] = "22";
region[key] = "33";
region.GetLocalView().Invalidate(key);
region.Remove(key);
}
foreach (string key in m_keysForRegex)
{
region[key] = "11";
region[key] = "22";
region[key] = "33";
region.GetLocalView().Invalidate(key);
region.Remove(key);
}
}
}
public void DoRegister()
{
DoRegisterInterests(RegionNamesForInterestNotify[0], true);
DoRegisterInterests(RegionNamesForInterestNotify[1], false);
// We intentionally do not register interest in Region3
//DoRegisterInterestsBlah(RegionNamesForInterestNotifyBlah[2]);
}
public void DoRegisterInterests(string regionName, bool receiveValues)
{
IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName);
List<string> keys = new List<string>();
foreach (string key in m_keysNonRegex)
{
keys.Add(key);
}
region.GetSubscriptionService().RegisterKeys(keys.ToArray(), false, false, receiveValues);
region.GetSubscriptionService().RegisterRegex("key-regex.*", false, false, receiveValues);
}
public void DoUnregister()
{
DoUnregisterInterests(RegionNamesForInterestNotify[0]);
DoUnregisterInterests(RegionNamesForInterestNotify[1]);
}
public void DoUnregisterInterests(string regionName)
{
List<string> keys = new List<string>();
foreach (string key in m_keysNonRegex)
{
keys.Add(key);
}
IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName);
region.GetSubscriptionService().UnregisterKeys(keys.ToArray());
region.GetSubscriptionService().UnregisterRegex("key-regex.*");
}
public void DoValidation(string clientName, string regionName,
int creates, int updates, int invalidates, int destroys)
{
IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName);
TallyListener<object, object> listener = region.Attributes.CacheListener as TallyListener<object, object>;
Util.Log(clientName + ": " + regionName + ": creates expected=" + creates +
", actual=" + listener.Creates);
Util.Log(clientName + ": " + regionName + ": updates expected=" + updates +
", actual=" + listener.Updates);
Util.Log(clientName + ": " + regionName + ": invalidates expected=" + invalidates +
", actual=" + listener.Invalidates);
Util.Log(clientName + ": " + regionName + ": destroys expected=" + destroys +
", actual=" + listener.Destroys);
Assert.AreEqual(creates, listener.Creates, clientName + ": " + regionName);
Assert.AreEqual(updates, listener.Updates, clientName + ": " + regionName);
Assert.AreEqual(invalidates, listener.Invalidates, clientName + ": " + regionName);
Assert.AreEqual(destroys, listener.Destroys, clientName + ": " + regionName);
}
#endregion
[Test]
public void FailoverRegexInterest()
{
CacheHelper.SetupJavaServers(true,
"cacheserver_notify_subscription.xml",
"cacheserver_notify_subscription2.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
m_client1.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", true);
m_client1.Call(CreateEntry, RegionNames[1], m_keys[1], m_vals[1]);
Util.Log("StepOne complete.");
m_client2.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", true);
m_client2.Call(CreateEntry, RegionNames[1], m_keys[1], m_nvals[1]);
m_client2.Call(RegisterRegexes, m_regexes[0], m_regexes[2]);
Util.Log("StepTwo complete.");
m_client1.Call(StepThree);
m_client1.Call(RegisterRegexes, (string)null, m_regexes[1]);
m_client1.Call(DoNetsearch, RegionNames[1],
m_keys[1], m_nvals[1], false);
Util.Log("StepThree complete.");
m_client2.Call(StepFourFailoverRegex);
Util.Log("StepFour complete.");
CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1);
Util.Log("Cacheserver 2 started.");
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
m_client1.Call(StepFiveFailoverRegex);
Util.Log("StepFive complete.");
m_client2.Call(StepSixFailoverRegex);
Util.Log("StepSix complete.");
m_client1.Call(StepSevenFailoverRegex);
Util.Log("StepSeven complete.");
m_client2.Call(StepEightFailoverRegex);
Util.Log("StepEight complete.");
m_client1.Call(Close);
m_client2.Call(Close);
CacheHelper.StopJavaServer(2);
Util.Log("Cacheserver 2 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator stopped");
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
}
}
| |
// 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.
//
// Don't override IsAlwaysNormalized because it is just a Unicode Transformation and could be confused.
//
namespace System.Text
{
using System;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Diagnostics.Contracts;
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class UTF7Encoding : Encoding
{
private const String base64Chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
// 0123456789111111111122222222223333333333444444444455555555556666
// 012345678901234567890123456789012345678901234567890123
// These are the characters that can be directly encoded in UTF7.
private const String directChars =
"\t\n\r '(),-./0123456789:?ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
// These are the characters that can be optionally directly encoded in UTF7.
private const String optionalChars =
"!\"#$%&*;<=>@[]^_`{|}";
// Used by Encoding.UTF7 for lazy initialization
// The initialization code will not be run until a static member of the class is referenced
internal static readonly UTF7Encoding s_default = new UTF7Encoding();
// The set of base 64 characters.
private byte[] base64Bytes;
// The decoded bits for every base64 values. This array has a size of 128 elements.
// The index is the code point value of the base 64 characters. The value is -1 if
// the code point is not a valid base 64 character. Otherwise, the value is a value
// from 0 ~ 63.
private sbyte[] base64Values;
// The array to decide if a Unicode code point below 0x80 can be directly encoded in UTF7.
// This array has a size of 128.
private bool[] directEncode;
[OptionalField(VersionAdded = 2)]
private bool m_allowOptionals;
private const int UTF7_CODEPAGE=65000;
public UTF7Encoding()
: this(false)
{
}
public UTF7Encoding(bool allowOptionals)
: base(UTF7_CODEPAGE) //Set the data item.
{
// Allowing optionals?
this.m_allowOptionals = allowOptionals;
// Make our tables
MakeTables();
}
private void MakeTables()
{
// Build our tables
base64Bytes = new byte[64];
for (int i = 0; i < 64; i++) base64Bytes[i] = (byte)base64Chars[i];
base64Values = new sbyte[128];
for (int i = 0; i < 128; i++) base64Values[i] = -1;
for (int i = 0; i < 64; i++) base64Values[base64Bytes[i]] = (sbyte)i;
directEncode = new bool[128];
int count = directChars.Length;
for (int i = 0; i < count; i++)
{
directEncode[directChars[i]] = true;
}
if (this.m_allowOptionals)
{
count = optionalChars.Length;
for (int i = 0; i < count; i++)
{
directEncode[optionalChars[i]] = true;
}
}
}
// We go ahead and set this because Encoding expects it, however nothing can fall back in UTF7.
internal override void SetDefaultFallbacks()
{
// UTF7 had an odd decoderFallback behavior, and the Encoder fallback
// is irrelevent because we encode surrogates individually and never check for unmatched ones
// (so nothing can fallback during encoding)
this.encoderFallback = new EncoderReplacementFallback(String.Empty);
this.decoderFallback = new DecoderUTF7Fallback();
}
[OnDeserializing]
private void OnDeserializing(StreamingContext ctx)
{
// make sure the optional fields initialized correctly.
base.OnDeserializing();
}
[OnDeserialized]
private void OnDeserialized(StreamingContext ctx)
{
base.OnDeserialized();
if (m_deserializedFromEverett)
{
// If 1st optional char is encoded we're allowing optionals
m_allowOptionals = directEncode[optionalChars[0]];
}
MakeTables();
}
[System.Runtime.InteropServices.ComVisible(false)]
public override bool Equals(Object value)
{
UTF7Encoding that = value as UTF7Encoding;
if (that != null)
{
return (m_allowOptionals == that.m_allowOptionals) &&
(EncoderFallback.Equals(that.EncoderFallback)) &&
(DecoderFallback.Equals(that.DecoderFallback));
}
return (false);
}
// Compared to all the other encodings, variations of UTF7 are unlikely
[System.Runtime.InteropServices.ComVisible(false)]
public override int GetHashCode()
{
return this.CodePage + this.EncoderFallback.GetHashCode() + this.DecoderFallback.GetHashCode();
}
// NOTE: Many methods in this class forward to EncodingForwarder for
// validating arguments/wrapping the unsafe methods in this class
// which do the actual work. That class contains
// shared logic for doing this which is used by
// ASCIIEncoding, EncodingNLS, UnicodeEncoding, UTF32Encoding,
// UTF7Encoding, and UTF8Encoding.
// The reason the code is separated out into a static class, rather
// than a base class which overrides all of these methods for us
// (which is what EncodingNLS is for internal Encodings) is because
// that's really more of an implementation detail so it's internal.
// At the same time, C# doesn't allow a public class subclassing an
// internal/private one, so we end up having to re-override these
// methods in all of the public Encodings + EncodingNLS.
// Returns the number of bytes required to encode a range of characters in
// a character array.
public override int GetByteCount(char[] chars, int index, int count)
{
return EncodingForwarder.GetByteCount(this, chars, index, count);
}
[System.Runtime.InteropServices.ComVisible(false)]
public override int GetByteCount(String s)
{
return EncodingForwarder.GetByteCount(this, s);
}
[System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public override unsafe int GetByteCount(char* chars, int count)
{
return EncodingForwarder.GetByteCount(this, chars, count);
}
[System.Runtime.InteropServices.ComVisible(false)]
public override int GetBytes(String s, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
return EncodingForwarder.GetBytes(this, s, charIndex, charCount, bytes, byteIndex);
}
// Encodes a range of characters in a character array into a range of bytes
// in a byte array. An exception occurs if the byte array is not large
// enough to hold the complete encoding of the characters. The
// GetByteCount method can be used to determine the exact number of
// bytes that will be produced for a given range of characters.
// Alternatively, the GetMaxByteCount method can be used to
// determine the maximum number of bytes that will be produced for a given
// number of characters, regardless of the actual character values.
public override int GetBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
return EncodingForwarder.GetBytes(this, chars, charIndex, charCount, bytes, byteIndex);
}
[System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
{
return EncodingForwarder.GetBytes(this, chars, charCount, bytes, byteCount);
}
// Returns the number of characters produced by decoding a range of bytes
// in a byte array.
public override int GetCharCount(byte[] bytes, int index, int count)
{
return EncodingForwarder.GetCharCount(this, bytes, index, count);
}
[System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public override unsafe int GetCharCount(byte* bytes, int count)
{
return EncodingForwarder.GetCharCount(this, bytes, count);
}
public override int GetChars(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex)
{
return EncodingForwarder.GetChars(this, bytes, byteIndex, byteCount, chars, charIndex);
}
[System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount)
{
return EncodingForwarder.GetChars(this, bytes, byteCount, chars, charCount);
}
// Returns a string containing the decoded representation of a range of
// bytes in a byte array.
[System.Runtime.InteropServices.ComVisible(false)]
public override String GetString(byte[] bytes, int index, int count)
{
return EncodingForwarder.GetString(this, bytes, index, count);
}
// End of overridden methods which use EncodingForwarder
[System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS baseEncoder)
{
Contract.Assert(chars!=null, "[UTF7Encoding.GetByteCount]chars!=null");
Contract.Assert(count >=0, "[UTF7Encoding.GetByteCount]count >=0");
// Just call GetBytes with bytes == null
return GetBytes(chars, count, null, 0, baseEncoder);
}
[System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetBytes(char* chars, int charCount,
byte* bytes, int byteCount, EncoderNLS baseEncoder)
{
Contract.Assert(byteCount >=0, "[UTF7Encoding.GetBytes]byteCount >=0");
Contract.Assert(chars!=null, "[UTF7Encoding.GetBytes]chars!=null");
Contract.Assert(charCount >=0, "[UTF7Encoding.GetBytes]charCount >=0");
// Get encoder info
UTF7Encoding.Encoder encoder = (UTF7Encoding.Encoder)baseEncoder;
// Default bits & count
int bits = 0;
int bitCount = -1;
// prepare our helpers
Encoding.EncodingByteBuffer buffer = new Encoding.EncodingByteBuffer(
this, encoder, bytes, byteCount, chars, charCount);
if (encoder != null)
{
bits = encoder.bits;
bitCount = encoder.bitCount;
// May have had too many left over
while (bitCount >= 6)
{
bitCount -= 6;
// If we fail we'll never really have enough room
if (!buffer.AddByte(base64Bytes[(bits >> bitCount) & 0x3F]))
ThrowBytesOverflow(encoder, buffer.Count == 0);
}
}
while (buffer.MoreData)
{
char currentChar = buffer.GetNextChar();
if (currentChar < 0x80 && directEncode[currentChar])
{
if (bitCount >= 0)
{
if (bitCount > 0)
{
// Try to add the next byte
if (!buffer.AddByte(base64Bytes[bits << 6 - bitCount & 0x3F]))
break; // Stop here, didn't throw
bitCount = 0;
}
// Need to get emit '-' and our char, 2 bytes total
if (!buffer.AddByte((byte)'-'))
break; // Stop here, didn't throw
bitCount = -1;
}
// Need to emit our char
if (!buffer.AddByte((byte)currentChar))
break; // Stop here, didn't throw
}
else if (bitCount < 0 && currentChar == '+')
{
if (!buffer.AddByte((byte)'+', (byte)'-'))
break; // Stop here, didn't throw
}
else
{
if (bitCount < 0)
{
// Need to emit a + and 12 bits (3 bytes)
// Only 12 of the 16 bits will be emitted this time, the other 4 wait 'til next time
if (!buffer.AddByte((byte)'+'))
break; // Stop here, didn't throw
// We're now in bit mode, but haven't stored data yet
bitCount = 0;
}
// Add our bits
bits = bits << 16 | currentChar;
bitCount += 16;
while (bitCount >= 6)
{
bitCount -= 6;
if (!buffer.AddByte(base64Bytes[(bits >> bitCount) & 0x3F]))
{
bitCount += 6; // We didn't use these bits
currentChar = buffer.GetNextChar(); // We're processing this char still, but AddByte
// --'d it when we ran out of space
break; // Stop here, not enough room for bytes
}
}
if (bitCount >= 6)
break; // Didn't have room to encode enough bits
}
}
// Now if we have bits left over we have to encode them.
// MustFlush may have been cleared by encoding.ThrowBytesOverflow earlier if converting
if (bitCount >= 0 && (encoder == null || encoder.MustFlush))
{
// Do we have bits we have to stick in?
if (bitCount > 0)
{
if (buffer.AddByte(base64Bytes[(bits << (6 - bitCount)) & 0x3F]))
{
// Emitted spare bits, 0 bits left
bitCount = 0;
}
}
// If converting and failed bitCount above, then we'll fail this too
if (buffer.AddByte((byte)'-'))
{
// turned off bit mode';
bits = 0;
bitCount = -1;
}
else
// If not successful, convert will maintain state for next time, also
// AddByte will have decremented our char count, however we need it to remain the same
buffer.GetNextChar();
}
// Do we have an encoder we're allowed to use?
// bytes == null if counting, so don't use encoder then
if (bytes != null && encoder != null)
{
// We already cleared bits & bitcount for mustflush case
encoder.bits = bits;
encoder.bitCount = bitCount;
encoder.m_charsUsed = buffer.CharsUsed;
}
return buffer.Count;
}
[System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder)
{
Contract.Assert(count >=0, "[UTF7Encoding.GetCharCount]count >=0");
Contract.Assert(bytes!=null, "[UTF7Encoding.GetCharCount]bytes!=null");
// Just call GetChars with null char* to do counting
return GetChars(bytes, count, null, 0, baseDecoder);
}
[System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, DecoderNLS baseDecoder)
{
Contract.Assert(byteCount >=0, "[UTF7Encoding.GetChars]byteCount >=0");
Contract.Assert(bytes!=null, "[UTF7Encoding.GetChars]bytes!=null");
Contract.Assert(charCount >=0, "[UTF7Encoding.GetChars]charCount >=0");
// Might use a decoder
UTF7Encoding.Decoder decoder = (UTF7Encoding.Decoder) baseDecoder;
// Get our output buffer info.
Encoding.EncodingCharBuffer buffer = new Encoding.EncodingCharBuffer(
this, decoder, chars, charCount, bytes, byteCount);
// Get decoder info
int bits = 0;
int bitCount = -1;
bool firstByte = false;
if (decoder != null)
{
bits = decoder.bits;
bitCount = decoder.bitCount;
firstByte = decoder.firstByte;
Contract.Assert(firstByte == false || decoder.bitCount <= 0,
"[UTF7Encoding.GetChars]If remembered bits, then first byte flag shouldn't be set");
}
// We may have had bits in the decoder that we couldn't output last time, so do so now
if (bitCount >= 16)
{
// Check our decoder buffer
if (!buffer.AddChar((char)((bits >> (bitCount - 16)) & 0xFFFF)))
ThrowCharsOverflow(decoder, true); // Always throw, they need at least 1 char even in Convert
// Used this one, clean up extra bits
bitCount -= 16;
}
// Loop through the input
while (buffer.MoreData)
{
byte currentByte = buffer.GetNextByte();
int c;
if (bitCount >= 0)
{
//
// Modified base 64 encoding.
//
sbyte v;
if (currentByte < 0x80 && ((v = base64Values[currentByte]) >=0))
{
firstByte = false;
bits = (bits << 6) | ((byte)v);
bitCount += 6;
if (bitCount >= 16)
{
c = (bits >> (bitCount - 16)) & 0xFFFF;
bitCount -= 16;
}
// If not enough bits just continue
else continue;
}
else
{
// If it wasn't a base 64 byte, everything's going to turn off base 64 mode
bitCount = -1;
if (currentByte != '-')
{
// >= 0x80 (because of 1st if statemtn)
// We need this check since the base64Values[b] check below need b <= 0x7f.
// This is not a valid base 64 byte. Terminate the shifted-sequence and
// emit this byte.
// not in base 64 table
// According to the RFC 1642 and the example code of UTF-7
// in Unicode 2.0, we should just zero-extend the invalid UTF7 byte
// Chars won't be updated unless this works, try to fallback
if (!buffer.Fallback(currentByte))
break; // Stop here, didn't throw
// Used that byte, we're done with it
continue;
}
//
// The encoding for '+' is "+-".
//
if (firstByte) c = '+';
// We just turn it off if not emitting a +, so we're done.
else continue;
}
//
// End of modified base 64 encoding block.
//
}
else if (currentByte == '+')
{
//
// Found the start of a modified base 64 encoding block or a plus sign.
//
bitCount = 0;
firstByte = true;
continue;
}
else
{
// Normal character
if (currentByte >= 0x80)
{
// Try to fallback
if (!buffer.Fallback(currentByte))
break; // Stop here, didn't throw
// Done falling back
continue;
}
// Use the normal character
c = currentByte;
}
if (c >= 0)
{
// Check our buffer
if (!buffer.AddChar((char)c))
{
// No room. If it was a plain char we'll try again later.
// Note, we'll consume this byte and stick it in decoder, even if we can't output it
if (bitCount >= 0) // Can we rememmber this byte (char)
{
buffer.AdjustBytes(+1); // Need to readd the byte that AddChar subtracted when it failed
bitCount += 16; // We'll still need that char we have in our bits
}
break; // didn't throw, stop
}
}
}
// Stick stuff in the decoder if we can (chars == null if counting, so don't store decoder)
if (chars != null && decoder != null)
{
// MustFlush? (Could've been cleared by ThrowCharsOverflow if Convert & didn't reach end of buffer)
if (decoder.MustFlush)
{
// RFC doesn't specify what would happen if we have non-0 leftover bits, we just drop them
decoder.bits = 0;
decoder.bitCount = -1;
decoder.firstByte = false;
}
else
{
decoder.bits = bits;
decoder.bitCount = bitCount;
decoder.firstByte = firstByte;
}
decoder.m_bytesUsed = buffer.BytesUsed;
}
// else ignore any hanging bits.
// Return our count
return buffer.Count;
}
public override System.Text.Decoder GetDecoder()
{
return new UTF7Encoding.Decoder(this);
}
public override System.Text.Encoder GetEncoder()
{
return new UTF7Encoding.Encoder(this);
}
public override int GetMaxByteCount(int charCount)
{
if (charCount < 0)
throw new ArgumentOutOfRangeException("charCount",
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
// Suppose that every char can not be direct-encoded, we know that
// a byte can encode 6 bits of the Unicode character. And we will
// also need two extra bytes for the shift-in ('+') and shift-out ('-') mark.
// Therefore, the max byte should be:
// byteCount = 2 + Math.Ceiling((double)charCount * 16 / 6);
// That is always <= 2 + 3 * charCount;
// Longest case is alternating encoded, direct, encoded data for 5 + 1 + 5... bytes per char.
// UTF7 doesn't have left over surrogates, but if no input we may need an output - to turn off
// encoding if MustFlush is true.
// Its easiest to think of this as 2 bytes to turn on/off the base64 mode, then 3 bytes per char.
// 3 bytes is 18 bits of encoding, which is more than we need, but if its direct encoded then 3
// bytes allows us to turn off and then back on base64 mode if necessary.
// Note that UTF7 encoded surrogates individually and isn't worried about mismatches, so all
// code points are encodable int UTF7.
long byteCount = (long)charCount * 3 + 2;
// check for overflow
if (byteCount > 0x7fffffff)
throw new ArgumentOutOfRangeException("charCount", Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
return (int)byteCount;
}
public override int GetMaxCharCount(int byteCount)
{
if (byteCount < 0)
throw new ArgumentOutOfRangeException("byteCount",
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
// Worst case is 1 char per byte. Minimum 1 for left over bits in case decoder is being flushed
// Also note that we ignore extra bits (per spec), so UTF7 doesn't have unknown in this direction.
int charCount = byteCount;
if (charCount == 0) charCount = 1;
return charCount;
}
[Serializable]
// Of all the amazing things... This MUST be Decoder so that our com name
// for System.Text.Decoder doesn't change
private class Decoder : DecoderNLS, ISerializable
{
/*private*/
internal int bits;
/*private*/ internal int bitCount;
/*private*/ internal bool firstByte;
public Decoder(UTF7Encoding encoding) : base (encoding)
{
// base calls reset
}
// Constructor called by serialization, have to handle deserializing from Everett
internal Decoder(SerializationInfo info, StreamingContext context)
{
// Any info?
if (info==null) throw new ArgumentNullException("info");
Contract.EndContractBlock();
// Get common info
this.bits = (int)info.GetValue("bits", typeof(int));
this.bitCount = (int)info.GetValue("bitCount", typeof(int));
this.firstByte = (bool)info.GetValue("firstByte", typeof(bool));
this.m_encoding = (Encoding)info.GetValue("encoding", typeof(Encoding));
}
// ISerializable implementation, get data for this object
[System.Security.SecurityCritical] // auto-generated_required
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
// Any info?
if (info==null) throw new ArgumentNullException("info");
Contract.EndContractBlock();
// Save Whidbey data
info.AddValue("encoding", this.m_encoding);
info.AddValue("bits", this.bits);
info.AddValue("bitCount", this.bitCount);
info.AddValue("firstByte", this.firstByte);
}
public override void Reset()
{
this.bits = 0;
this.bitCount = -1;
this.firstByte = false;
if (m_fallbackBuffer != null)
m_fallbackBuffer.Reset();
}
// Anything left in our encoder?
internal override bool HasState
{
get
{
// NOTE: This forces the last -, which some encoder might not encode. If we
// don't see it we don't think we're done reading.
return (this.bitCount != -1);
}
}
}
[Serializable]
// Of all the amazing things... This MUST be Encoder so that our com name
// for System.Text.Encoder doesn't change
private class Encoder : EncoderNLS, ISerializable
{
/*private*/
internal int bits;
/*private*/ internal int bitCount;
public Encoder(UTF7Encoding encoding) : base(encoding)
{
// base calls reset
}
// Constructor called by serialization, have to handle deserializing from Everett
internal Encoder(SerializationInfo info, StreamingContext context)
{
// Any info?
if (info==null) throw new ArgumentNullException("info");
Contract.EndContractBlock();
// Get common info
this.bits = (int)info.GetValue("bits", typeof(int));
this.bitCount = (int)info.GetValue("bitCount", typeof(int));
this.m_encoding = (Encoding)info.GetValue("encoding", typeof(Encoding));
}
// ISerializable implementation, get data for this object
[System.Security.SecurityCritical] // auto-generated_required
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
// Any info?
if (info==null) throw new ArgumentNullException("info");
Contract.EndContractBlock();
// Save Whidbey data
info.AddValue("encoding", this.m_encoding);
info.AddValue("bits", this.bits);
info.AddValue("bitCount", this.bitCount);
}
public override void Reset()
{
this.bitCount = -1;
this.bits = 0;
if (m_fallbackBuffer != null)
m_fallbackBuffer.Reset();
}
// Anything left in our encoder?
internal override bool HasState
{
get
{
return (this.bits != 0 || this.bitCount != -1);
}
}
}
// Preexisting UTF7 behavior for bad bytes was just to spit out the byte as the next char
// and turn off base64 mode if it was in that mode. We still exit the mode, but now we fallback.
[Serializable]
internal sealed class DecoderUTF7Fallback : DecoderFallback
{
// Construction. Default replacement fallback uses no best fit and ? replacement string
public DecoderUTF7Fallback()
{
}
public override DecoderFallbackBuffer CreateFallbackBuffer()
{
return new DecoderUTF7FallbackBuffer(this);
}
// Maximum number of characters that this instance of this fallback could return
public override int MaxCharCount
{
get
{
// returns 1 char per bad byte
return 1;
}
}
public override bool Equals(Object value)
{
DecoderUTF7Fallback that = value as DecoderUTF7Fallback;
if (that != null)
{
return true;
}
return (false);
}
public override int GetHashCode()
{
return 984;
}
}
internal sealed class DecoderUTF7FallbackBuffer : DecoderFallbackBuffer
{
// Store our default string
char cFallback = (char)0;
int iCount = -1;
int iSize;
// Construction
public DecoderUTF7FallbackBuffer(DecoderUTF7Fallback fallback)
{
}
// Fallback Methods
public override bool Fallback(byte[] bytesUnknown, int index)
{
// We expect no previous fallback in our buffer
Contract.Assert(iCount < 0, "[DecoderUTF7FallbackBuffer.Fallback] Can't have recursive fallbacks");
Contract.Assert(bytesUnknown.Length == 1, "[DecoderUTF7FallbackBuffer.Fallback] Only possible fallback case should be 1 unknown byte");
// Go ahead and get our fallback
cFallback = (char)bytesUnknown[0];
// Any of the fallback characters can be handled except for 0
if (cFallback == 0)
{
return false;
}
iCount = iSize = 1;
return true;
}
public override char GetNextChar()
{
if (iCount-- > 0)
return cFallback;
// Note: this means that 0 in UTF7 stream will never be emitted.
return (char)0;
}
public override bool MovePrevious()
{
if (iCount >= 0)
{
iCount++;
}
// return true if we were allowed to do this
return (iCount >= 0 && iCount <= iSize);
}
// Return # of chars left in this fallback
public override int Remaining
{
get
{
return (iCount > 0) ? iCount : 0;
}
}
// Clear the buffer
[System.Security.SecuritySafeCritical] // overrides public transparent member
public override unsafe void Reset()
{
iCount = -1;
byteStart = null;
}
// This version just counts the fallback and doesn't actually copy anything.
[System.Security.SecurityCritical] // auto-generated
internal unsafe override int InternalFallback(byte[] bytes, byte* pBytes)
// Right now this has both bytes and bytes[], since we might have extra bytes, hence the
// array, and we might need the index, hence the byte*
{
// We expect no previous fallback in our buffer
Contract.Assert(iCount < 0, "[DecoderUTF7FallbackBuffer.InternalFallback] Can't have recursive fallbacks");
if (bytes.Length != 1)
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex"));
}
// Can't fallback a byte 0, so return for that case, 1 otherwise.
return bytes[0] == 0 ? 0 : 1;
}
}
}
}
| |
// 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;
namespace System.Tests
{
public static class Int64Tests
{
[Fact]
public static void Ctor_Empty()
{
var i = new long();
Assert.Equal(0, i);
}
[Fact]
public static void Ctor_Value()
{
long i = 41;
Assert.Equal(41, i);
}
[Fact]
public static void MaxValue()
{
Assert.Equal(0x7FFFFFFFFFFFFFFF, long.MaxValue);
}
[Fact]
public static void MinValue()
{
Assert.Equal(unchecked((long)0x8000000000000000), long.MinValue);
}
[Theory]
[InlineData((long)234, (long)234, 0)]
[InlineData((long)234, long.MinValue, 1)]
[InlineData((long)234, (long)-123, 1)]
[InlineData((long)234, (long)0, 1)]
[InlineData((long)234, (long)123, 1)]
[InlineData((long)234, (long)456, -1)]
[InlineData((long)234, long.MaxValue, -1)]
[InlineData((long)-234, (long)-234, 0)]
[InlineData((long)-234, (long)234, -1)]
[InlineData((long)-234, (long)-432, 1)]
[InlineData((long)234, null, 1)]
public static void CompareTo(long i, object value, long expected)
{
if (value is long)
{
Assert.Equal(expected, Math.Sign(i.CompareTo((long)value)));
}
IComparable comparable = i;
Assert.Equal(expected, Math.Sign(comparable.CompareTo(value)));
}
[Fact]
public static void CompareTo_ObjectNotLong_ThrowsArgumentException()
{
IComparable comparable = (long)234;
AssertExtensions.Throws<ArgumentException>(null, () => comparable.CompareTo("a")); // Obj is not a long
AssertExtensions.Throws<ArgumentException>(null, () => comparable.CompareTo(234)); // Obj is not a long
}
[Theory]
[InlineData((long)789, (long)789, true)]
[InlineData((long)789, (long)-789, false)]
[InlineData((long)789, (long)0, false)]
[InlineData((long)0, (long)0, true)]
[InlineData((long)-789, (long)-789, true)]
[InlineData((long)-789, (long)789, false)]
[InlineData((long)789, null, false)]
[InlineData((long)789, "789", false)]
[InlineData((long)789, 789, false)]
public static void Equals(long i1, object obj, bool expected)
{
if (obj is long)
{
long i2 = (long)obj;
Assert.Equal(expected, i1.Equals(i2));
Assert.Equal(expected, i1.GetHashCode().Equals(i2.GetHashCode()));
}
Assert.Equal(expected, i1.Equals(obj));
}
public static IEnumerable<object[]> ToString_TestData()
{
NumberFormatInfo emptyFormat = NumberFormatInfo.CurrentInfo;
yield return new object[] { long.MinValue, "G", emptyFormat, "-9223372036854775808" };
yield return new object[] { (long)-4567, "G", emptyFormat, "-4567" };
yield return new object[] { (long)0, "G", emptyFormat, "0" };
yield return new object[] { (long)4567, "G", emptyFormat, "4567" };
yield return new object[] { long.MaxValue, "G", emptyFormat, "9223372036854775807" };
yield return new object[] { (long)0x2468, "x", emptyFormat, "2468" };
yield return new object[] { (long)2468, "N", emptyFormat, string.Format("{0:N}", 2468.00) };
NumberFormatInfo customFormat = new NumberFormatInfo();
customFormat.NegativeSign = "#";
customFormat.NumberDecimalSeparator = "~";
customFormat.NumberGroupSeparator = "*";
yield return new object[] { (long)-2468, "N", customFormat, "#2*468~00" };
yield return new object[] { (long)2468, "N", customFormat, "2*468~00" };
}
[Theory]
[MemberData(nameof(ToString_TestData))]
public static void ToString(long i, 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, i.ToString());
Assert.Equal(upperExpected, i.ToString((IFormatProvider)null));
}
Assert.Equal(upperExpected, i.ToString(provider));
}
if (isDefaultProvider)
{
Assert.Equal(upperExpected, i.ToString(upperFormat));
Assert.Equal(lowerExpected, i.ToString(lowerFormat));
Assert.Equal(upperExpected, i.ToString(upperFormat, null));
Assert.Equal(lowerExpected, i.ToString(lowerFormat, null));
}
Assert.Equal(upperExpected, i.ToString(upperFormat, provider));
Assert.Equal(lowerExpected, i.ToString(lowerFormat, provider));
}
[Fact]
public static void ToString_InvalidFormat_ThrowsFormatException()
{
long i = 123;
Assert.Throws<FormatException>(() => i.ToString("Y")); // Invalid format
Assert.Throws<FormatException>(() => i.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[] { "-9223372036854775808", defaultStyle, null, -9223372036854775808 };
yield return new object[] { "-123", defaultStyle, null, (long)-123 };
yield return new object[] { "0", defaultStyle, null, (long)0 };
yield return new object[] { "123", defaultStyle, null, (long)123 };
yield return new object[] { "+123", defaultStyle, null, (long)123 };
yield return new object[] { " 123 ", defaultStyle, null, (long)123 };
yield return new object[] { "9223372036854775807", defaultStyle, null, 9223372036854775807 };
yield return new object[] { "123", NumberStyles.HexNumber, null, (long)0x123 };
yield return new object[] { "abc", NumberStyles.HexNumber, null, (long)0xabc };
yield return new object[] { "ABC", NumberStyles.HexNumber, null, (long)0xabc };
yield return new object[] { "1000", NumberStyles.AllowThousands, null, (long)1000 };
yield return new object[] { "(123)", NumberStyles.AllowParentheses, null, (long)-123 }; // Parentheses = negative
yield return new object[] { "123", defaultStyle, emptyFormat, (long)123 };
yield return new object[] { "123", NumberStyles.Any, emptyFormat, (long)123 };
yield return new object[] { "12", NumberStyles.HexNumber, emptyFormat, (long)0x12 };
yield return new object[] { "$1,000", NumberStyles.Currency, customFormat, (long)1000 };
}
[Theory]
[MemberData(nameof(Parse_Valid_TestData))]
public static void Parse(string value, NumberStyles style, IFormatProvider provider, long expected)
{
long result;
// If no style is specified, use the (String) or (String, IFormatProvider) overload
if (style == NumberStyles.Integer)
{
Assert.True(long.TryParse(value, out result));
Assert.Equal(expected, result);
Assert.Equal(expected, long.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, long.Parse(value, provider));
}
}
// If a format provider isn't specified, test the default one, using a new instance of NumberFormatInfo
Assert.True(long.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, long.Parse(value, style));
}
Assert.Equal(expected, long.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[] { "abc", 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[] { 1000.ToString("C0"), defaultStyle, null, typeof(FormatException) }; // Currency
yield return new object[] { 1000.ToString("N0"), defaultStyle, null, typeof(FormatException) }; // Thousands
yield return new object[] { 678.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[] { "abc", 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[] { "-9223372036854775809", defaultStyle, null, typeof(OverflowException) }; // < min value
yield return new object[] { "9223372036854775808", defaultStyle, null, typeof(OverflowException) }; // > max value
}
[Theory]
[MemberData(nameof(Parse_Invalid_TestData))]
public static void Parse_Invalid(string value, NumberStyles style, IFormatProvider provider, Type exceptionType)
{
long result;
// If no style is specified, use the (String) or (String, IFormatProvider) overload
if (style == NumberStyles.Integer)
{
Assert.False(long.TryParse(value, out result));
Assert.Equal(default(long), result);
Assert.Throws(exceptionType, () => long.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, () => long.Parse(value, provider));
}
}
// If a format provider isn't specified, test the default one, using a new instance of NumberFormatInfo
Assert.False(long.TryParse(value, style, provider ?? new NumberFormatInfo(), out result));
Assert.Equal(default(long), result);
// If a format provider isn't specified, test the default one, using the (String, NumberStyles) overload
if (provider == null)
{
Assert.Throws(exceptionType, () => long.Parse(value, style));
}
Assert.Throws(exceptionType, () => long.Parse(value, style, provider ?? new NumberFormatInfo()));
}
[Theory]
[InlineData(NumberStyles.HexNumber | NumberStyles.AllowParentheses)]
[InlineData(unchecked((NumberStyles)0xFFFFFC00))]
public static void TryParse_InvalidNumberStyle_ThrowsArgumentException(NumberStyles style)
{
long result = 0;
Assert.Throws<ArgumentException>(() => long.TryParse("1", style, null, out result));
Assert.Equal(default(long), result);
Assert.Throws<ArgumentException>(() => long.Parse("1", style));
Assert.Throws<ArgumentException>(() => long.Parse("1", style, null));
}
}
}
| |
/*
Copyright 2012-2022 Marco De Salvo
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 RDFSharp.Model;
using RDFSharp.Store;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Linq;
using System.Collections.Generic;
namespace RDFSharp.Test.Store
{
[TestClass]
public class RDFStoreIndexTest
{
#region Tests
[TestMethod]
public void ShouldCreateStoreIndex()
{
RDFStoreIndex storeIndex = new RDFStoreIndex();
Assert.IsNotNull(storeIndex);
Assert.IsNotNull(storeIndex.Contexts);
Assert.IsTrue(storeIndex.Contexts.Count == 0);
Assert.IsNotNull(storeIndex.Subjects);
Assert.IsTrue(storeIndex.Subjects.Count == 0);
Assert.IsNotNull(storeIndex.Predicates);
Assert.IsTrue(storeIndex.Predicates.Count == 0);
Assert.IsNotNull(storeIndex.Objects);
Assert.IsTrue(storeIndex.Objects.Count == 0);
Assert.IsNotNull(storeIndex.Literals);
Assert.IsTrue(storeIndex.Literals.Count == 0);
}
[TestMethod]
public void ShouldAddCSPOIndex()
{
RDFContext ctx = new RDFContext("http://ctx/");
RDFResource subj = new RDFResource("http://subj/");
RDFResource pred = new RDFResource("http://pred/");
RDFResource obj = new RDFResource("http://obj/");
RDFQuadruple quadruple = new RDFQuadruple(ctx, subj, pred, obj);
RDFStoreIndex storeIndex = new RDFStoreIndex().AddIndex(quadruple);
Assert.IsTrue(storeIndex.Contexts.Count == 1);
Assert.IsTrue(storeIndex.Contexts[ctx.PatternMemberID].Contains(quadruple.QuadrupleID));
Assert.IsTrue(storeIndex.Subjects.Count == 1);
Assert.IsTrue(storeIndex.Subjects[subj.PatternMemberID].Contains(quadruple.QuadrupleID));
Assert.IsTrue(storeIndex.Predicates.Count == 1);
Assert.IsTrue(storeIndex.Predicates[pred.PatternMemberID].Contains(quadruple.QuadrupleID));
Assert.IsTrue(storeIndex.Objects.Count == 1);
Assert.IsTrue(storeIndex.Objects[obj.PatternMemberID].Contains(quadruple.QuadrupleID));
Assert.IsTrue(storeIndex.Literals.Count == 0);
}
[TestMethod]
public void ShouldAddCSPLIndex()
{
RDFContext ctx = new RDFContext("http://ctx/");
RDFResource subj = new RDFResource("http://subj/");
RDFResource pred = new RDFResource("http://pred/");
RDFTypedLiteral lit = new RDFTypedLiteral("lit", RDFModelEnums.RDFDatatypes.XSD_STRING);
RDFQuadruple quadruple = new RDFQuadruple(ctx, subj, pred, lit);
RDFStoreIndex storeIndex = new RDFStoreIndex().AddIndex(quadruple);
Assert.IsTrue(storeIndex.Contexts.Count == 1);
Assert.IsTrue(storeIndex.Contexts[ctx.PatternMemberID].Contains(quadruple.QuadrupleID));
Assert.IsTrue(storeIndex.Subjects.Count == 1);
Assert.IsTrue(storeIndex.Subjects[subj.PatternMemberID].Contains(quadruple.QuadrupleID));
Assert.IsTrue(storeIndex.Predicates.Count == 1);
Assert.IsTrue(storeIndex.Predicates[pred.PatternMemberID].Contains(quadruple.QuadrupleID));
Assert.IsTrue(storeIndex.Objects.Count == 0);
Assert.IsTrue(storeIndex.Literals.Count == 1);
Assert.IsTrue(storeIndex.Literals[lit.PatternMemberID].Contains(quadruple.QuadrupleID));
}
[TestMethod]
public void ShouldAddSameContextMultipleTimes()
{
RDFContext ctx = new RDFContext("http://ctx/");
RDFResource subj1 = new RDFResource("http://subj1/");
RDFResource pred1 = new RDFResource("http://pred1/");
RDFResource obj1 = new RDFResource("http://obj1/");
RDFQuadruple quadruple1 = new RDFQuadruple(ctx, subj1, pred1, obj1);
RDFResource subj2 = new RDFResource("http://subj2/");
RDFResource pred2 = new RDFResource("http://pred2/");
RDFResource obj2 = new RDFResource("http://obj2/");
RDFQuadruple quadruple2 = new RDFQuadruple(ctx, subj2, pred2, obj2);
RDFStoreIndex storeIndex = new RDFStoreIndex().AddIndex(quadruple1).AddIndex(quadruple1).AddIndex(quadruple2);
Assert.IsTrue(storeIndex.Contexts.Count == 1);
Assert.IsTrue(storeIndex.Contexts[ctx.PatternMemberID].Contains(quadruple1.QuadrupleID));
Assert.IsTrue(storeIndex.Contexts[ctx.PatternMemberID].Contains(quadruple2.QuadrupleID));
Assert.IsTrue(storeIndex.Subjects.Count == 2);
Assert.IsTrue(storeIndex.Subjects[subj1.PatternMemberID].Contains(quadruple1.QuadrupleID));
Assert.IsTrue(storeIndex.Subjects[subj2.PatternMemberID].Contains(quadruple2.QuadrupleID));
Assert.IsTrue(storeIndex.Predicates.Count == 2);
Assert.IsTrue(storeIndex.Predicates[pred1.PatternMemberID].Contains(quadruple1.QuadrupleID));
Assert.IsTrue(storeIndex.Predicates[pred2.PatternMemberID].Contains(quadruple2.QuadrupleID));
Assert.IsTrue(storeIndex.Objects.Count == 2);
Assert.IsTrue(storeIndex.Objects[obj1.PatternMemberID].Contains(quadruple1.QuadrupleID));
Assert.IsTrue(storeIndex.Objects[obj2.PatternMemberID].Contains(quadruple2.QuadrupleID));
Assert.IsTrue(storeIndex.Literals.Count == 0);
}
[TestMethod]
public void ShouldAddSameSubjectMultipleTimes()
{
RDFContext ctx1 = new RDFContext("http://ctx1/");
RDFResource subj = new RDFResource("http://subj/");
RDFResource pred1 = new RDFResource("http://pred1/");
RDFResource obj1 = new RDFResource("http://obj1/");
RDFQuadruple quadruple1 = new RDFQuadruple(ctx1, subj, pred1, obj1);
RDFContext ctx2 = new RDFContext("http://ctx2/");
RDFResource pred2 = new RDFResource("http://pred2/");
RDFResource obj2 = new RDFResource("http://obj2/");
RDFQuadruple quadruple2 = new RDFQuadruple(ctx2, subj, pred2, obj2);
RDFStoreIndex storeIndex = new RDFStoreIndex().AddIndex(quadruple1).AddIndex(quadruple1).AddIndex(quadruple2);
Assert.IsTrue(storeIndex.Contexts.Count == 2);
Assert.IsTrue(storeIndex.Contexts[ctx1.PatternMemberID].Contains(quadruple1.QuadrupleID));
Assert.IsTrue(storeIndex.Contexts[ctx2.PatternMemberID].Contains(quadruple2.QuadrupleID));
Assert.IsTrue(storeIndex.Subjects.Count == 1);
Assert.IsTrue(storeIndex.Subjects[subj.PatternMemberID].Contains(quadruple1.QuadrupleID));
Assert.IsTrue(storeIndex.Subjects[subj.PatternMemberID].Contains(quadruple2.QuadrupleID));
Assert.IsTrue(storeIndex.Predicates.Count == 2);
Assert.IsTrue(storeIndex.Predicates[pred1.PatternMemberID].Contains(quadruple1.QuadrupleID));
Assert.IsTrue(storeIndex.Predicates[pred2.PatternMemberID].Contains(quadruple2.QuadrupleID));
Assert.IsTrue(storeIndex.Objects.Count == 2);
Assert.IsTrue(storeIndex.Objects[obj1.PatternMemberID].Contains(quadruple1.QuadrupleID));
Assert.IsTrue(storeIndex.Objects[obj2.PatternMemberID].Contains(quadruple2.QuadrupleID));
Assert.IsTrue(storeIndex.Literals.Count == 0);
}
[TestMethod]
public void ShouldAddSamePredicateMultipleTimes()
{
RDFContext ctx1 = new RDFContext("http://ctx1/");
RDFResource subj1 = new RDFResource("http://subj1/");
RDFResource pred = new RDFResource("http://pred/");
RDFResource obj1 = new RDFResource("http://obj1/");
RDFQuadruple quadruple1 = new RDFQuadruple(ctx1, subj1, pred, obj1);
RDFContext ctx2 = new RDFContext("http://ctx2/");
RDFResource subj2 = new RDFResource("http://subj2/");
RDFResource obj2 = new RDFResource("http://obj2/");
RDFQuadruple quadruple2 = new RDFQuadruple(ctx2, subj2, pred, obj2);
RDFStoreIndex storeIndex = new RDFStoreIndex().AddIndex(quadruple1).AddIndex(quadruple1).AddIndex(quadruple2);
Assert.IsTrue(storeIndex.Contexts.Count == 2);
Assert.IsTrue(storeIndex.Contexts[ctx1.PatternMemberID].Contains(quadruple1.QuadrupleID));
Assert.IsTrue(storeIndex.Contexts[ctx2.PatternMemberID].Contains(quadruple2.QuadrupleID));
Assert.IsTrue(storeIndex.Subjects.Count == 2);
Assert.IsTrue(storeIndex.Subjects[subj1.PatternMemberID].Contains(quadruple1.QuadrupleID));
Assert.IsTrue(storeIndex.Subjects[subj2.PatternMemberID].Contains(quadruple2.QuadrupleID));
Assert.IsTrue(storeIndex.Predicates.Count == 1);
Assert.IsTrue(storeIndex.Predicates[pred.PatternMemberID].Contains(quadruple1.QuadrupleID));
Assert.IsTrue(storeIndex.Predicates[pred.PatternMemberID].Contains(quadruple2.QuadrupleID));
Assert.IsTrue(storeIndex.Objects.Count == 2);
Assert.IsTrue(storeIndex.Objects[obj1.PatternMemberID].Contains(quadruple1.QuadrupleID));
Assert.IsTrue(storeIndex.Objects[obj2.PatternMemberID].Contains(quadruple2.QuadrupleID));
Assert.IsTrue(storeIndex.Literals.Count == 0);
}
[TestMethod]
public void ShouldAddSameObjectMultipleTimes()
{
RDFContext ctx1 = new RDFContext("http://ctx1/");
RDFResource subj1 = new RDFResource("http://subj1/");
RDFResource pred1 = new RDFResource("http://pred1/");
RDFResource obj = new RDFResource("http://obj/");
RDFQuadruple quadruple1 = new RDFQuadruple(ctx1, subj1, pred1, obj);
RDFContext ctx2 = new RDFContext("http://ctx2/");
RDFResource subj2 = new RDFResource("http://subj2/");
RDFResource pred2 = new RDFResource("http://pred2/");
RDFQuadruple quadruple2 = new RDFQuadruple(ctx2, subj2, pred2, obj);
RDFStoreIndex storeIndex = new RDFStoreIndex().AddIndex(quadruple1).AddIndex(quadruple1).AddIndex(quadruple2);
Assert.IsTrue(storeIndex.Contexts.Count == 2);
Assert.IsTrue(storeIndex.Contexts[ctx1.PatternMemberID].Contains(quadruple1.QuadrupleID));
Assert.IsTrue(storeIndex.Contexts[ctx2.PatternMemberID].Contains(quadruple2.QuadrupleID));
Assert.IsTrue(storeIndex.Subjects.Count == 2);
Assert.IsTrue(storeIndex.Subjects[subj1.PatternMemberID].Contains(quadruple1.QuadrupleID));
Assert.IsTrue(storeIndex.Subjects[subj2.PatternMemberID].Contains(quadruple2.QuadrupleID));
Assert.IsTrue(storeIndex.Predicates.Count == 2);
Assert.IsTrue(storeIndex.Predicates[pred1.PatternMemberID].Contains(quadruple1.QuadrupleID));
Assert.IsTrue(storeIndex.Predicates[pred2.PatternMemberID].Contains(quadruple2.QuadrupleID));
Assert.IsTrue(storeIndex.Objects.Count == 1);
Assert.IsTrue(storeIndex.Objects[obj.PatternMemberID].Contains(quadruple1.QuadrupleID));
Assert.IsTrue(storeIndex.Objects[obj.PatternMemberID].Contains(quadruple2.QuadrupleID));
Assert.IsTrue(storeIndex.Literals.Count == 0);
}
[TestMethod]
public void ShouldAddSameLiteralMultipleTimes()
{
RDFContext ctx1 = new RDFContext("http://ctx1/");
RDFResource subj1 = new RDFResource("http://subj1/");
RDFResource pred1 = new RDFResource("http://pred1/");
RDFPlainLiteral lit = new RDFPlainLiteral("lit", "en-US");
RDFQuadruple quadruple1 = new RDFQuadruple(ctx1, subj1, pred1, lit);
RDFContext ctx2 = new RDFContext("http://ctx2/");
RDFResource subj2 = new RDFResource("http://subj2/");
RDFResource pred2 = new RDFResource("http://pred2/");
RDFQuadruple quadruple2 = new RDFQuadruple(ctx2, subj2, pred2, lit);
RDFStoreIndex storeIndex = new RDFStoreIndex().AddIndex(quadruple1).AddIndex(quadruple1).AddIndex(quadruple2);
Assert.IsTrue(storeIndex.Contexts.Count == 2);
Assert.IsTrue(storeIndex.Contexts[ctx1.PatternMemberID].Contains(quadruple1.QuadrupleID));
Assert.IsTrue(storeIndex.Contexts[ctx2.PatternMemberID].Contains(quadruple2.QuadrupleID));
Assert.IsTrue(storeIndex.Subjects.Count == 2);
Assert.IsTrue(storeIndex.Subjects[subj1.PatternMemberID].Contains(quadruple1.QuadrupleID));
Assert.IsTrue(storeIndex.Subjects[subj2.PatternMemberID].Contains(quadruple2.QuadrupleID));
Assert.IsTrue(storeIndex.Predicates.Count == 2);
Assert.IsTrue(storeIndex.Predicates[pred1.PatternMemberID].Contains(quadruple1.QuadrupleID));
Assert.IsTrue(storeIndex.Predicates[pred2.PatternMemberID].Contains(quadruple2.QuadrupleID));
Assert.IsTrue(storeIndex.Objects.Count == 0);
Assert.IsTrue(storeIndex.Literals.Count == 1);
Assert.IsTrue(storeIndex.Literals[lit.PatternMemberID].Contains(quadruple1.QuadrupleID));
Assert.IsTrue(storeIndex.Literals[lit.PatternMemberID].Contains(quadruple2.QuadrupleID));
}
[TestMethod]
public void ShouldNotAddNullIndex()
{
RDFStoreIndex storeIndex = new RDFStoreIndex().AddIndex(null);
Assert.IsTrue(storeIndex.Contexts.Count == 0);
Assert.IsTrue(storeIndex.Subjects.Count == 0);
Assert.IsTrue(storeIndex.Predicates.Count == 0);
Assert.IsTrue(storeIndex.Objects.Count == 0);
Assert.IsTrue(storeIndex.Literals.Count == 0);
}
[TestMethod]
public void ShouldRemoveCSPOIndex()
{
RDFContext ctx = new RDFContext("http://ctx/");
RDFResource subj = new RDFResource("http://subj/");
RDFResource pred = new RDFResource("http://pred/");
RDFResource obj = new RDFResource("http://obj/");
RDFQuadruple quadruple = new RDFQuadruple(ctx, subj, pred, obj);
RDFStoreIndex storeIndex = new RDFStoreIndex().AddIndex(quadruple).RemoveIndex(quadruple);
Assert.IsTrue(storeIndex.Contexts.Count == 0);
Assert.IsTrue(storeIndex.Subjects.Count == 0);
Assert.IsTrue(storeIndex.Predicates.Count == 0);
Assert.IsTrue(storeIndex.Objects.Count == 0);
Assert.IsTrue(storeIndex.Literals.Count == 0);
}
[TestMethod]
public void ShouldRemoveCSPLIndex()
{
RDFContext ctx = new RDFContext("http://ctx/");
RDFResource subj = new RDFResource("http://subj/");
RDFResource pred = new RDFResource("http://pred/");
RDFTypedLiteral lit = new RDFTypedLiteral("lit", RDFModelEnums.RDFDatatypes.XSD_STRING);
RDFQuadruple quadruple = new RDFQuadruple(ctx, subj, pred, lit);
RDFStoreIndex storeIndex = new RDFStoreIndex().AddIndex(quadruple).RemoveIndex(quadruple);
Assert.IsTrue(storeIndex.Contexts.Count == 0);
Assert.IsTrue(storeIndex.Subjects.Count == 0);
Assert.IsTrue(storeIndex.Predicates.Count == 0);
Assert.IsTrue(storeIndex.Objects.Count == 0);
Assert.IsTrue(storeIndex.Literals.Count == 0);
}
[TestMethod]
public void ShouldAddSameContextMultipleTimesAndRemoveOneOccurrence()
{
RDFContext ctx = new RDFContext("http://ctx/");
RDFResource subj1 = new RDFResource("http://subj1/");
RDFResource pred1 = new RDFResource("http://pred1/");
RDFResource obj1 = new RDFResource("http://obj1/");
RDFQuadruple quadruple1 = new RDFQuadruple(ctx, subj1, pred1, obj1);
RDFResource subj2 = new RDFResource("http://subj2/");
RDFResource pred2 = new RDFResource("http://pred2/");
RDFResource obj2 = new RDFResource("http://obj2/");
RDFQuadruple quadruple2 = new RDFQuadruple(ctx, subj2, pred2, obj2);
RDFStoreIndex storeIndex = new RDFStoreIndex().AddIndex(quadruple1).AddIndex(quadruple2).RemoveIndex(quadruple2);
Assert.IsTrue(storeIndex.Contexts.Count == 1);
Assert.IsTrue(storeIndex.Contexts[ctx.PatternMemberID].Contains(quadruple1.QuadrupleID));
Assert.IsFalse(storeIndex.Contexts[ctx.PatternMemberID].Contains(quadruple2.QuadrupleID));
Assert.IsTrue(storeIndex.Subjects.Count == 1);
Assert.IsTrue(storeIndex.Subjects[subj1.PatternMemberID].Contains(quadruple1.QuadrupleID));
Assert.IsFalse(storeIndex.Subjects[subj1.PatternMemberID].Contains(quadruple2.QuadrupleID));
Assert.IsTrue(storeIndex.Predicates.Count == 1);
Assert.IsTrue(storeIndex.Predicates[pred1.PatternMemberID].Contains(quadruple1.QuadrupleID));
Assert.IsFalse(storeIndex.Predicates.ContainsKey(pred2.PatternMemberID));
Assert.IsTrue(storeIndex.Objects.Count == 1);
Assert.IsTrue(storeIndex.Objects[obj1.PatternMemberID].Contains(quadruple1.QuadrupleID));
Assert.IsFalse(storeIndex.Objects.ContainsKey(obj2.PatternMemberID));
Assert.IsTrue(storeIndex.Literals.Count == 0);
}
[TestMethod]
public void ShouldAddSameSubjectMultipleTimesAndRemoveOneOccurrence()
{
RDFContext ctx1 = new RDFContext("http://ctx1/");
RDFResource subj = new RDFResource("http://subj/");
RDFResource pred1 = new RDFResource("http://pred1/");
RDFResource obj1 = new RDFResource("http://obj1/");
RDFQuadruple quadruple1 = new RDFQuadruple(ctx1, subj, pred1, obj1);
RDFContext ctx2 = new RDFContext("http://ctx2/");
RDFResource pred2 = new RDFResource("http://pred2/");
RDFResource obj2 = new RDFResource("http://obj2/");
RDFQuadruple quadruple2 = new RDFQuadruple(ctx2, subj, pred2, obj2);
RDFStoreIndex storeIndex = new RDFStoreIndex().AddIndex(quadruple1).AddIndex(quadruple2).RemoveIndex(quadruple2);
Assert.IsTrue(storeIndex.Contexts.Count == 1);
Assert.IsTrue(storeIndex.Contexts[ctx1.PatternMemberID].Contains(quadruple1.QuadrupleID));
Assert.IsFalse(storeIndex.Contexts.ContainsKey(ctx2.PatternMemberID));
Assert.IsTrue(storeIndex.Subjects.Count == 1);
Assert.IsTrue(storeIndex.Subjects[subj.PatternMemberID].Contains(quadruple1.QuadrupleID));
Assert.IsFalse(storeIndex.Subjects[subj.PatternMemberID].Contains(quadruple2.QuadrupleID));
Assert.IsTrue(storeIndex.Predicates.Count == 1);
Assert.IsTrue(storeIndex.Predicates[pred1.PatternMemberID].Contains(quadruple1.QuadrupleID));
Assert.IsFalse(storeIndex.Predicates.ContainsKey(pred2.PatternMemberID));
Assert.IsTrue(storeIndex.Objects.Count == 1);
Assert.IsTrue(storeIndex.Objects[obj1.PatternMemberID].Contains(quadruple1.QuadrupleID));
Assert.IsFalse(storeIndex.Objects.ContainsKey(obj2.PatternMemberID));
Assert.IsTrue(storeIndex.Literals.Count == 0);
}
[TestMethod]
public void ShouldAddSameSubjectMultipleTimesAndRemoveEveryOccurrences()
{
RDFContext ctx1 = new RDFContext("http://ctx1/");
RDFResource subj = new RDFResource("http://subj/");
RDFResource pred1 = new RDFResource("http://pred1/");
RDFResource obj1 = new RDFResource("http://obj1/");
RDFQuadruple quadruple1 = new RDFQuadruple(ctx1, subj, pred1, obj1);
RDFContext ctx2 = new RDFContext("http://ctx2/");
RDFResource pred2 = new RDFResource("http://pred2/");
RDFResource obj2 = new RDFResource("http://obj2/");
RDFQuadruple quadruple2 = new RDFQuadruple(ctx2, subj, pred2, obj2);
RDFStoreIndex storeIndex = new RDFStoreIndex().AddIndex(quadruple1).AddIndex(quadruple2).RemoveIndex(quadruple2).RemoveIndex(quadruple2).RemoveIndex(quadruple1);
Assert.IsTrue(storeIndex.Contexts.Count == 0);
Assert.IsTrue(storeIndex.Subjects.Count == 0);
Assert.IsTrue(storeIndex.Predicates.Count == 0);
Assert.IsTrue(storeIndex.Objects.Count == 0);
Assert.IsTrue(storeIndex.Literals.Count == 0);
}
[TestMethod]
public void ShouldAddSamePredicateMultipleTimesAndRemoveOneOccurrence()
{
RDFContext ctx1 = new RDFContext("http://ctx1/");
RDFResource subj1 = new RDFResource("http://subj1/");
RDFResource pred = new RDFResource("http://pred/");
RDFResource obj1 = new RDFResource("http://obj1/");
RDFQuadruple quadruple1 = new RDFQuadruple(ctx1, subj1, pred, obj1);
RDFContext ctx2 = new RDFContext("http://ctx2/");
RDFResource subj2 = new RDFResource("http://subj2/");
RDFResource obj2 = new RDFResource("http://obj2/");
RDFQuadruple quadruple2 = new RDFQuadruple(ctx2, subj2, pred, obj2);
RDFStoreIndex storeIndex = new RDFStoreIndex().AddIndex(quadruple1).AddIndex(quadruple2).RemoveIndex(quadruple2);
Assert.IsTrue(storeIndex.Contexts.Count == 1);
Assert.IsTrue(storeIndex.Contexts[ctx1.PatternMemberID].Contains(quadruple1.QuadrupleID));
Assert.IsFalse(storeIndex.Contexts.ContainsKey(ctx2.PatternMemberID));
Assert.IsTrue(storeIndex.Subjects.Count == 1);
Assert.IsTrue(storeIndex.Subjects[subj1.PatternMemberID].Contains(quadruple1.QuadrupleID));
Assert.IsFalse(storeIndex.Subjects.ContainsKey(subj2.PatternMemberID));
Assert.IsTrue(storeIndex.Predicates.Count == 1);
Assert.IsTrue(storeIndex.Predicates[pred.PatternMemberID].Contains(quadruple1.QuadrupleID));
Assert.IsFalse(storeIndex.Predicates[pred.PatternMemberID].Contains(quadruple2.QuadrupleID));
Assert.IsTrue(storeIndex.Objects.Count == 1);
Assert.IsTrue(storeIndex.Objects[obj1.PatternMemberID].Contains(quadruple1.QuadrupleID));
Assert.IsFalse(storeIndex.Objects.ContainsKey(obj2.PatternMemberID));
Assert.IsTrue(storeIndex.Literals.Count == 0);
}
[TestMethod]
public void ShouldAddSamePredicateMultipleTimesAndRemoveEveryOccurrence()
{
RDFContext ctx1 = new RDFContext("http://ctx1/");
RDFResource subj1 = new RDFResource("http://subj1/");
RDFResource pred = new RDFResource("http://pred/");
RDFResource obj1 = new RDFResource("http://obj1/");
RDFQuadruple quadruple1 = new RDFQuadruple(ctx1, subj1, pred, obj1);
RDFContext ctx2 = new RDFContext("http://ctx2/");
RDFResource subj2 = new RDFResource("http://subj2/");
RDFResource obj2 = new RDFResource("http://obj2/");
RDFQuadruple quadruple2 = new RDFQuadruple(ctx2, subj2, pred, obj2);
RDFStoreIndex storeIndex = new RDFStoreIndex().AddIndex(quadruple1).AddIndex(quadruple2).RemoveIndex(quadruple2).RemoveIndex(quadruple2).RemoveIndex(quadruple1);
Assert.IsTrue(storeIndex.Contexts.Count == 0);
Assert.IsTrue(storeIndex.Subjects.Count == 0);
Assert.IsTrue(storeIndex.Predicates.Count == 0);
Assert.IsTrue(storeIndex.Objects.Count == 0);
Assert.IsTrue(storeIndex.Literals.Count == 0);
}
[TestMethod]
public void ShouldAddSameObjectMultipleTimesAndRemoveOneOccurrence()
{
RDFContext ctx1 = new RDFContext("http://ctx1/");
RDFResource subj1 = new RDFResource("http://subj1/");
RDFResource pred1 = new RDFResource("http://pred1/");
RDFResource obj = new RDFResource("http://obj/");
RDFQuadruple quadruple1 = new RDFQuadruple(ctx1, subj1, pred1, obj);
RDFContext ctx2 = new RDFContext("http://ctx2/");
RDFResource subj2 = new RDFResource("http://subj2/");
RDFResource pred2 = new RDFResource("http://pred2/");
RDFQuadruple quadruple2 = new RDFQuadruple(ctx2, subj2, pred2, obj);
RDFStoreIndex storeIndex = new RDFStoreIndex().AddIndex(quadruple1).AddIndex(quadruple2).RemoveIndex(quadruple2);
Assert.IsTrue(storeIndex.Contexts.Count == 1);
Assert.IsTrue(storeIndex.Contexts[ctx1.PatternMemberID].Contains(quadruple1.QuadrupleID));
Assert.IsFalse(storeIndex.Contexts.ContainsKey(ctx2.PatternMemberID));
Assert.IsTrue(storeIndex.Subjects.Count == 1);
Assert.IsTrue(storeIndex.Subjects[subj1.PatternMemberID].Contains(quadruple1.QuadrupleID));
Assert.IsFalse(storeIndex.Subjects.ContainsKey(subj2.PatternMemberID));
Assert.IsTrue(storeIndex.Predicates.Count == 1);
Assert.IsTrue(storeIndex.Predicates[pred1.PatternMemberID].Contains(quadruple1.QuadrupleID));
Assert.IsFalse(storeIndex.Predicates.ContainsKey(pred2.PatternMemberID));
Assert.IsTrue(storeIndex.Objects.Count == 1);
Assert.IsTrue(storeIndex.Objects[obj.PatternMemberID].Contains(quadruple1.QuadrupleID));
Assert.IsFalse(storeIndex.Objects[obj.PatternMemberID].Contains(quadruple2.QuadrupleID));
Assert.IsTrue(storeIndex.Literals.Count == 0);
}
[TestMethod]
public void ShouldAddSameObjectMultipleTimesAndRemoveEveryOccurrence()
{
RDFContext ctx1 = new RDFContext("http://ctx1/");
RDFResource subj1 = new RDFResource("http://subj1/");
RDFResource pred1 = new RDFResource("http://pred1/");
RDFResource obj = new RDFResource("http://obj/");
RDFQuadruple quadruple1 = new RDFQuadruple(ctx1, subj1, pred1, obj);
RDFContext ctx2 = new RDFContext("http://ctx2/");
RDFResource subj2 = new RDFResource("http://subj2/");
RDFResource pred2 = new RDFResource("http://pred2/");
RDFQuadruple quadruple2 = new RDFQuadruple(ctx2, subj2, pred2, obj);
RDFStoreIndex storeIndex = new RDFStoreIndex().AddIndex(quadruple1).AddIndex(quadruple2).RemoveIndex(quadruple2).RemoveIndex(quadruple2).RemoveIndex(quadruple1);
Assert.IsTrue(storeIndex.Contexts.Count == 0);
Assert.IsTrue(storeIndex.Subjects.Count == 0);
Assert.IsTrue(storeIndex.Predicates.Count == 0);
Assert.IsTrue(storeIndex.Objects.Count == 0);
Assert.IsTrue(storeIndex.Literals.Count == 0);
}
[TestMethod]
public void ShouldAddSameLiteralMultipleTimesAndRemoveOneOccurrence()
{
RDFContext ctx1 = new RDFContext("http://ctx1/");
RDFResource subj1 = new RDFResource("http://subj1/");
RDFResource pred1 = new RDFResource("http://pred1/");
RDFPlainLiteral lit = new RDFPlainLiteral("lit", "en-US");
RDFQuadruple quadruple1 = new RDFQuadruple(ctx1, subj1, pred1, lit);
RDFContext ctx2 = new RDFContext("http://ctx2/");
RDFResource subj2 = new RDFResource("http://subj2/");
RDFResource pred2 = new RDFResource("http://pred2/");
RDFQuadruple quadruple2 = new RDFQuadruple(ctx2, subj2, pred2, lit);
RDFStoreIndex storeIndex = new RDFStoreIndex().AddIndex(quadruple1).AddIndex(quadruple2).RemoveIndex(quadruple2);
Assert.IsTrue(storeIndex.Contexts.Count == 1);
Assert.IsTrue(storeIndex.Contexts[ctx1.PatternMemberID].Contains(quadruple1.QuadrupleID));
Assert.IsFalse(storeIndex.Contexts.ContainsKey(ctx2.PatternMemberID));
Assert.IsTrue(storeIndex.Subjects.Count == 1);
Assert.IsTrue(storeIndex.Subjects[subj1.PatternMemberID].Contains(quadruple1.QuadrupleID));
Assert.IsFalse(storeIndex.Subjects.ContainsKey(subj2.PatternMemberID));
Assert.IsTrue(storeIndex.Predicates.Count == 1);
Assert.IsTrue(storeIndex.Predicates[pred1.PatternMemberID].Contains(quadruple1.QuadrupleID));
Assert.IsFalse(storeIndex.Predicates.ContainsKey(pred2.PatternMemberID));
Assert.IsTrue(storeIndex.Objects.Count == 0);
Assert.IsTrue(storeIndex.Literals.Count == 1);
Assert.IsTrue(storeIndex.Literals[lit.PatternMemberID].Contains(quadruple1.QuadrupleID));
Assert.IsFalse(storeIndex.Literals[lit.PatternMemberID].Contains(quadruple2.QuadrupleID));
}
[TestMethod]
public void ShouldAddSameLiteralMultipleTimesAndRemoveEveryOccurrence()
{
RDFContext ctx1 = new RDFContext("http://ctx1/");
RDFResource subj1 = new RDFResource("http://subj1/");
RDFResource pred1 = new RDFResource("http://pred1/");
RDFPlainLiteral lit = new RDFPlainLiteral("lit", "en-US");
RDFQuadruple quadruple1 = new RDFQuadruple(ctx1, subj1, pred1, lit);
RDFContext ctx2 = new RDFContext("http://ctx2/");
RDFResource subj2 = new RDFResource("http://subj2/");
RDFResource pred2 = new RDFResource("http://pred2/");
RDFQuadruple quadruple2 = new RDFQuadruple(ctx2, subj2, pred2, lit);
RDFStoreIndex storeIndex = new RDFStoreIndex().AddIndex(quadruple1).AddIndex(quadruple2).RemoveIndex(quadruple2).RemoveIndex(quadruple2).RemoveIndex(quadruple1);
Assert.IsTrue(storeIndex.Contexts.Count == 0);
Assert.IsTrue(storeIndex.Subjects.Count == 0);
Assert.IsTrue(storeIndex.Predicates.Count == 0);
Assert.IsTrue(storeIndex.Objects.Count == 0);
Assert.IsTrue(storeIndex.Literals.Count == 0);
}
[TestMethod]
public void ShouldNotRemoveNullIndex()
{
RDFStoreIndex storeIndex = new RDFStoreIndex().RemoveIndex(null);
Assert.IsTrue(storeIndex.Contexts.Count == 0);
Assert.IsTrue(storeIndex.Subjects.Count == 0);
Assert.IsTrue(storeIndex.Predicates.Count == 0);
Assert.IsTrue(storeIndex.Objects.Count == 0);
Assert.IsTrue(storeIndex.Literals.Count == 0);
}
[TestMethod]
public void ShouldClearIndex()
{
RDFContext ctx = new RDFContext();
RDFResource subj = new RDFResource("http://subj/");
RDFResource pred = new RDFResource("http://pred/");
RDFResource obj = new RDFResource("http://obj/");
RDFPlainLiteral lit = new RDFPlainLiteral("lit");
RDFQuadruple quadruple1 = new RDFQuadruple(ctx, subj, pred, obj);
RDFQuadruple quadruple2 = new RDFQuadruple(ctx, subj, pred, lit);
RDFStoreIndex storeIndex = new RDFStoreIndex().AddIndex(quadruple1).AddIndex(quadruple2);
storeIndex.ClearIndex();
Assert.IsTrue(storeIndex.Contexts.Count == 0);
Assert.IsTrue(storeIndex.Subjects.Count == 0);
Assert.IsTrue(storeIndex.Predicates.Count == 0);
Assert.IsTrue(storeIndex.Objects.Count == 0);
Assert.IsTrue(storeIndex.Literals.Count == 0);
}
[TestMethod]
public void ShouldSelectIndexByContext()
{
RDFContext ctx = new RDFContext("http://ctx/");
RDFResource subj = new RDFResource("http://subj/");
RDFResource pred = new RDFResource("http://pred/");
RDFResource obj = new RDFResource("http://obj/");
RDFQuadruple quadruple = new RDFQuadruple(ctx, subj, pred, obj);
RDFStoreIndex storeIndex = new RDFStoreIndex().AddIndex(quadruple);
HashSet<long> quadruplesWithGivenContext = storeIndex.SelectIndexByContext(ctx);
Assert.IsNotNull(quadruplesWithGivenContext);
Assert.IsTrue(quadruplesWithGivenContext.Count == 1);
}
[TestMethod]
public void ShouldSelectEmptyIndexByNotFoundContext()
{
RDFContext ctx = new RDFContext("http://ctx/");
RDFResource subj = new RDFResource("http://subj/");
RDFResource pred = new RDFResource("http://pred/");
RDFResource obj = new RDFResource("http://obj/");
RDFQuadruple quadruple = new RDFQuadruple(ctx, subj, pred, obj);
RDFStoreIndex storeIndex = new RDFStoreIndex().AddIndex(quadruple);
HashSet<long> quadruplesWithGivenContext = storeIndex.SelectIndexByContext(new RDFContext("http://ctx2/"));
Assert.IsNotNull(quadruplesWithGivenContext);
Assert.IsTrue(quadruplesWithGivenContext.Count == 0);
}
[TestMethod]
public void ShouldSelectEmptyIndexByNullContext()
{
RDFContext ctx = new RDFContext("http://ctx/");
RDFResource subj = new RDFResource("http://subj/");
RDFResource pred = new RDFResource("http://pred/");
RDFResource obj = new RDFResource("http://obj/");
RDFQuadruple quadruple = new RDFQuadruple(ctx, subj, pred, obj);
RDFStoreIndex storeIndex = new RDFStoreIndex().AddIndex(quadruple);
HashSet<long> quadruplesWithGivenContext = storeIndex.SelectIndexByContext(null);
Assert.IsNotNull(quadruplesWithGivenContext);
Assert.IsTrue(quadruplesWithGivenContext.Count == 0);
}
[TestMethod]
public void ShouldSelectIndexBySubject()
{
RDFContext ctx = new RDFContext("http://ctx/");
RDFResource subj = new RDFResource("http://subj/");
RDFResource pred = new RDFResource("http://pred/");
RDFResource obj = new RDFResource("http://obj/");
RDFQuadruple quadruple = new RDFQuadruple(ctx, subj, pred, obj);
RDFStoreIndex storeIndex = new RDFStoreIndex().AddIndex(quadruple);
HashSet<long> quadruplesWithGivenSubject = storeIndex.SelectIndexBySubject(subj);
Assert.IsNotNull(quadruplesWithGivenSubject);
Assert.IsTrue(quadruplesWithGivenSubject.Count == 1);
}
[TestMethod]
public void ShouldSelectEmptyIndexByNotFoundSubject()
{
RDFContext ctx = new RDFContext("http://ctx/");
RDFResource subj = new RDFResource("http://subj/");
RDFResource pred = new RDFResource("http://pred/");
RDFResource obj = new RDFResource("http://obj/");
RDFQuadruple quadruple = new RDFQuadruple(ctx, subj, pred, obj);
RDFStoreIndex storeIndex = new RDFStoreIndex().AddIndex(quadruple);
HashSet<long> quadruplesWithGivenSubject = storeIndex.SelectIndexBySubject(new RDFResource("http://subj2/"));
Assert.IsNotNull(quadruplesWithGivenSubject);
Assert.IsTrue(quadruplesWithGivenSubject.Count == 0);
}
[TestMethod]
public void ShouldSelectEmptyIndexByNullSubject()
{
RDFContext ctx = new RDFContext("http://ctx/");
RDFResource subj = new RDFResource("http://subj/");
RDFResource pred = new RDFResource("http://pred/");
RDFResource obj = new RDFResource("http://obj/");
RDFQuadruple quadruple = new RDFQuadruple(ctx, subj, pred, obj);
RDFStoreIndex storeIndex = new RDFStoreIndex().AddIndex(quadruple);
HashSet<long> quadruplesWithGivenSubject = storeIndex.SelectIndexBySubject(null);
Assert.IsNotNull(quadruplesWithGivenSubject);
Assert.IsTrue(quadruplesWithGivenSubject.Count == 0);
}
[TestMethod]
public void ShouldSelectIndexByPredicate()
{
RDFContext ctx = new RDFContext("http://ctx/");
RDFResource subj = new RDFResource("http://subj/");
RDFResource pred = new RDFResource("http://pred/");
RDFResource obj = new RDFResource("http://obj/");
RDFQuadruple quadruple = new RDFQuadruple(ctx, subj, pred, obj);
RDFStoreIndex storeIndex = new RDFStoreIndex().AddIndex(quadruple);
HashSet<long> quadruplesWithGivenPredicate = storeIndex.SelectIndexByPredicate(pred);
Assert.IsNotNull(quadruplesWithGivenPredicate);
Assert.IsTrue(quadruplesWithGivenPredicate.Count == 1);
}
[TestMethod]
public void ShouldSelectEmptyIndexByNotFoundPredicate()
{
RDFContext ctx = new RDFContext("http://ctx/");
RDFResource subj = new RDFResource("http://subj/");
RDFResource pred = new RDFResource("http://pred/");
RDFResource obj = new RDFResource("http://obj/");
RDFQuadruple quadruple = new RDFQuadruple(ctx, subj, pred, obj);
RDFStoreIndex storeIndex = new RDFStoreIndex().AddIndex(quadruple);
HashSet<long> quadruplesWithGivenPredicate = storeIndex.SelectIndexByPredicate(new RDFResource("http://pred2/"));
Assert.IsNotNull(quadruplesWithGivenPredicate);
Assert.IsTrue(quadruplesWithGivenPredicate.Count == 0);
}
[TestMethod]
public void ShouldSelectEmptyIndexByNullPredicate()
{
RDFContext ctx = new RDFContext("http://ctx/");
RDFResource subj = new RDFResource("http://subj/");
RDFResource pred = new RDFResource("http://pred/");
RDFResource obj = new RDFResource("http://obj/");
RDFQuadruple quadruple = new RDFQuadruple(ctx, subj, pred, obj);
RDFStoreIndex storeIndex = new RDFStoreIndex().AddIndex(quadruple);
HashSet<long> quadruplesWithGivenPredicate = storeIndex.SelectIndexByPredicate(null);
Assert.IsNotNull(quadruplesWithGivenPredicate);
Assert.IsTrue(quadruplesWithGivenPredicate.Count == 0);
}
[TestMethod]
public void ShouldSelectIndexByObject()
{
RDFContext ctx = new RDFContext("http://ctx/");
RDFResource subj = new RDFResource("http://subj/");
RDFResource pred = new RDFResource("http://pred/");
RDFResource obj = new RDFResource("http://obj/");
RDFQuadruple quadruple = new RDFQuadruple(ctx, subj, pred, obj);
RDFStoreIndex storeIndex = new RDFStoreIndex().AddIndex(quadruple);
HashSet<long> quadruplesWithGivenObject = storeIndex.SelectIndexByObject(obj);
Assert.IsNotNull(quadruplesWithGivenObject);
Assert.IsTrue(quadruplesWithGivenObject.Count == 1);
}
[TestMethod]
public void ShouldSelectEmptyIndexByNotFoundObject()
{
RDFContext ctx = new RDFContext("http://ctx/");
RDFResource subj = new RDFResource("http://subj/");
RDFResource pred = new RDFResource("http://pred/");
RDFResource obj = new RDFResource("http://obj/");
RDFQuadruple quadruple = new RDFQuadruple(ctx, subj, pred, obj);
RDFStoreIndex storeIndex = new RDFStoreIndex().AddIndex(quadruple);
HashSet<long> quadruplesWithGivenObject = storeIndex.SelectIndexByObject(new RDFResource("http://subj2/"));
Assert.IsNotNull(quadruplesWithGivenObject);
Assert.IsTrue(quadruplesWithGivenObject.Count == 0);
}
[TestMethod]
public void ShouldSelectEmptyIndexByNullObject()
{
RDFContext ctx = new RDFContext("http://ctx/");
RDFResource subj = new RDFResource("http://subj/");
RDFResource pred = new RDFResource("http://pred/");
RDFResource obj = new RDFResource("http://obj/");
RDFQuadruple quadruple = new RDFQuadruple(ctx, subj, pred, obj);
RDFStoreIndex storeIndex = new RDFStoreIndex().AddIndex(quadruple);
HashSet<long> quadruplesWithGivenObject = storeIndex.SelectIndexByObject(null);
Assert.IsNotNull(quadruplesWithGivenObject);
Assert.IsTrue(quadruplesWithGivenObject.Count == 0);
}
[TestMethod]
public void ShouldSelectIndexByLiteral()
{
RDFContext ctx = new RDFContext("http://ctx/");
RDFResource subj = new RDFResource("http://subj/");
RDFResource pred = new RDFResource("http://pred/");
RDFPlainLiteral lit = new RDFPlainLiteral("lit", "en-US");
RDFQuadruple quadruple = new RDFQuadruple(ctx, subj, pred, lit);
RDFStoreIndex storeIndex = new RDFStoreIndex().AddIndex(quadruple);
HashSet<long> quadruplesWithGivenLiteral = storeIndex.SelectIndexByLiteral(lit);
Assert.IsNotNull(quadruplesWithGivenLiteral);
Assert.IsTrue(quadruplesWithGivenLiteral.Count == 1);
}
[TestMethod]
public void ShouldSelectEmptyIndexByNotFoundLiteral()
{
RDFContext ctx = new RDFContext("http://ctx/");
RDFResource subj = new RDFResource("http://subj/");
RDFResource pred = new RDFResource("http://pred/");
RDFPlainLiteral lit = new RDFPlainLiteral("lit", "en-US");
RDFQuadruple quadruple = new RDFQuadruple(ctx, subj, pred, lit);
RDFStoreIndex storeIndex = new RDFStoreIndex().AddIndex(quadruple);
HashSet<long> quadruplesWithGivenLiteral = storeIndex.SelectIndexByLiteral(new RDFPlainLiteral("lit2", "en-US"));
Assert.IsNotNull(quadruplesWithGivenLiteral);
Assert.IsTrue(quadruplesWithGivenLiteral.Count == 0);
}
[TestMethod]
public void ShouldSelectEmptyIndexByNullLiteral()
{
RDFContext ctx = new RDFContext("http://ctx/");
RDFResource subj = new RDFResource("http://subj/");
RDFResource pred = new RDFResource("http://pred/");
RDFPlainLiteral lit = new RDFPlainLiteral("lit", "en-US");
RDFQuadruple quadruple = new RDFQuadruple(ctx, subj, pred, lit);
RDFStoreIndex storeIndex = new RDFStoreIndex().AddIndex(quadruple);
HashSet<long> quadruplesWithGivenLiteral = storeIndex.SelectIndexByLiteral(null);
Assert.IsNotNull(quadruplesWithGivenLiteral);
Assert.IsTrue(quadruplesWithGivenLiteral.Count == 0);
}
#endregion
}
}
| |
using System;
using System.Reflection;
using NUnit.Framework;
namespace CodeBuilder.UT.Expressions
{
[TestFixture]
public class CallExpressionTests : BuilderTestBase
{
public class BaseClass
{
public string Result { get; set; }
public string Foo()
{
return Result;
}
public virtual string Virt()
{
return "base";
}
}
public class DerivedClass : BaseClass
{
public override string Virt()
{
return "derived";
}
}
public struct Counter
{
public void Count()
{
++Value;
}
public int Value { get; private set; }
}
public class CounterHolder
{
public Counter Counter;
}
public static void Foo() { }
private static readonly MethodInfo _formatInfo = ((Func<string, object, string>)string.Format).Method;
private static readonly MethodInfo _fooInfo = ((Action)Foo).Method;
private static readonly MethodInfo _toStringInfo = typeof(int).GetMethod("ToString", new Type[0]);
private static readonly MethodInfo _parseInfo = typeof(int).GetMethod("Parse", new[] { typeof(string) });
[Test]
public void VoidMethodTypeTest()
{
Assert.That(Expr.Call(_fooInfo).ExpressionType, Is.EqualTo(typeof(void)));
}
[Test]
public void NonVoidMethodTypeTest()
{
Assert.That(Expr.Call(_formatInfo, Expr.Constant("{0}"), Expr.Convert(Expr.Constant(1), typeof(object))).ExpressionType, Is.EqualTo(typeof(string)));
}
[Test]
public void Should_not_allow_null_methodInfo()
{
var ex = Assert.Throws<ArgumentNullException>(() => Expr.Call(null));
Assert.That(ex.Message, Is.StringContaining("methodInfo"));
}
[Test]
public void Should_not_allow_null_instance_for_non_static_method()
{
var ex = Assert.Throws<ArgumentNullException>(() => Expr.Call(null, _toStringInfo));
Assert.That(ex.Message, Is.StringContaining("instance"));
}
[Test]
public void Should_not_allow_not_null_instance_for_static_method()
{
var ex = Assert.Throws<ArgumentException>(() => Expr.Call(Expr.Constant(21), _parseInfo, Expr.Constant("22")));
Assert.That(ex.Message, Is.StringContaining("Static method cannot be called with instance parameter"));
}
[Test]
public void Should_not_allow_null_expression_array()
{
var ex = Assert.Throws<ArgumentNullException>(() => Expr.Call(_toStringInfo, null));
Assert.That(ex.Message, Is.StringContaining("arguments"));
}
[Test]
public void Should_not_allow_null_expression_in_array()
{
var ex = Assert.Throws<ArgumentNullException>(() => Expr.Call(_formatInfo, Expr.Constant("abs"), null));
Assert.That(ex.Message, Is.StringContaining("arguments[1]"));
}
[Test]
public void Should_not_allow_exceeding_number_of_method_parameters()
{
var ex = Assert.Throws<ArgumentException>(() => Expr.Call(_fooInfo, Expr.Constant(1)));
Assert.That(ex.Message, Is.StringContaining("Invalid amount of parameters supplied to method: Void Foo()"));
}
[Test]
public void Should_not_allow_insufficient_number_of_method_parameters()
{
var ex = Assert.Throws<ArgumentException>(() => Expr.Call(_formatInfo));
Assert.That(ex.Message, Is.StringContaining("Invalid amount of parameters supplied to method: System.String Format(System.String, System.Object)"));
}
[Test]
public void Should_not_allow_implicit_boxing_for_method_parameters()
{
var ex = Assert.Throws<ArgumentException>(() => Expr.Call(_formatInfo, Expr.Constant("{0}"), Expr.Constant(32)));
Assert.That(ex.Message, Is.StringContaining("Parameter expression of type System.Int32 does not match to type: System.Object"));
}
[Test]
public void Should_not_allow_implicit_boxing_for_instance_expression()
{
MethodInfo objToStringInfo = typeof(object).GetMethod("ToString");
var ex = Assert.Throws<ArgumentException>(() => Expr.Call(Expr.Constant(22), objToStringInfo));
Assert.That(ex.Message, Is.StringContaining("Instance expression of type System.Int32 does not match to type: System.Object"));
}
[Test]
public void Should_allow_hierarchy_conversion_for_parameter()
{
var func = CreateFunc<string, string>(Expr.Return(Expr.Call(_formatInfo, Expr.Constant("Hello {0}!"), Expr.Parameter(0, typeof(string)))));
Assert.That(func("world"), Is.EqualTo("Hello world!"));
}
[Test]
public void Should_allow_hierarchy_conversion_for_instance()
{
MethodInfo methodInfo = typeof(BaseClass).GetMethod("Foo");
var func = CreateFunc<DerivedClass, string>(Expr.Return(Expr.Call(Expr.Parameter(0, typeof(DerivedClass)), methodInfo)));
Assert.That(func(new DerivedClass { Result = "hi" }), Is.EqualTo("hi"));
}
[Test]
public void Should_call_struct_instance_method()
{
var func = CreateFunc<string>(Expr.Return(Expr.Call(Expr.Constant(21), _toStringInfo)));
Assert.That(func(), Is.EqualTo("21"));
}
[Test]
public void Should_call_virtual_method()
{
var virtualMethodInfo = typeof(BaseClass).GetMethod("Virt");
var func = CreateFunc<BaseClass, string>(Expr.Return(Expr.Call(Expr.Parameter(0, typeof(BaseClass)), virtualMethodInfo)));
Assert.That(func(new BaseClass()), Is.EqualTo("base"));
Assert.That(func(new DerivedClass()), Is.EqualTo("derived"));
}
[Test]
public void Should_call_virtual_method_in_non_virtual_way()
{
var virtualMethodInfo = typeof(BaseClass).GetMethod("Virt");
var func = CreateFunc<BaseClass, string>(Expr.Return(Expr.CallExact(Expr.Parameter(0, typeof(BaseClass)), virtualMethodInfo)));
Assert.That(func(new BaseClass()), Is.EqualTo("base"));
Assert.That(func(new DerivedClass()), Is.EqualTo("base"));
}
[Test]
public void Should_call_struct_instance_method_via_parameter()
{
var func = CreateFunc<Counter, Counter>(
Expr.Call(Expr.Parameter(0, typeof(Counter)), typeof(Counter).GetMethod("Count")),
Expr.Return(Expr.Parameter(0, typeof(Counter))));
Assert.That(func(new Counter()).Value, Is.EqualTo(1));
}
[Test]
public void Should_call_struct_instance_method_via_field()
{
var func = CreateAction<CounterHolder>(Expr.Call(
Expr.ReadField(Expr.Parameter(0, typeof(CounterHolder)), typeof(CounterHolder).GetField("Counter")),
typeof(Counter).GetMethod("Count")));
var holder = new CounterHolder();
func(holder);
Assert.That(holder.Counter.Value, Is.EqualTo(1));
}
[Test]
public void Should_call_struct_instance_method_via_local_variable()
{
var local = Expr.LocalVariable(typeof(Counter), "s");
var func = CreateFunc<Counter, Counter>(
Expr.DeclareLocal(local, Expr.Parameter(0, typeof(Counter))),
Expr.Call(Expr.ReadLocal(local), typeof(Counter).GetMethod("Count")),
Expr.Return(Expr.ReadLocal(local)));
Assert.That(func(new Counter()).Value, Is.EqualTo(1));
}
}
}
| |
// Copyright 2014-2020 Kasper B. Graversen
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
using System;
using NUnit.Framework;
using NUnit.Framework.Internal;
using StatePrinting.TestAssistance;
namespace StatePrinting.Tests.TestingAssistance
{
public class ParserTest
{
Parser sut;
[SetUp]
public void Setup()
{
sut = new Parser();
}
[Test]
public void NoEscapingOfNewExpected()
{
var r = sut.ReplaceExpected("Assert.AreEqual(\"hello\", sut.Do());", 1, "hello", "boo");
TestHelper.Assert().PrintAreAlike(@"""Assert.AreEqual(boo, sut.Do());""", r);
}
[Test]
public void Somehow_content_could_not_be_found()
{
var ex = Assert.Throws<ArgumentException>(() => sut.ReplaceExpected("aaaaaaaa", 1, "someOtherString", "boo"));
Assert.AreEqual("Did not find 'someOtherString'", ex.Message);
}
[Test]
public void Somehow_content_containing_weird_symbols_could_not_be_found()
{
var ex = Assert.Throws<ArgumentException>(() => sut.ReplaceExpected("aaaaaaaa", 1, "some.OtherString()", "boo"));
Assert.AreEqual("Did not find 'some.OtherString()'", ex.Message);
}
[Test]
public void Simple_input()
{
string program =
@" abc def
qwe ert
printer.Assert.Here(@""hello"", ...)
iu of";
var r = sut.ReplaceExpected(program, 3, "hello", "boo");
var expected = @""" abc def
qwe ert
printer.Assert.Here(boo, ...)
iu of""";
TestHelper.Assert().PrintAreAlike(expected, r);
}
[Test]
public void Expected_variable_ContainsBackslashes_WillBeEscaped()
{
string program =
@" abc def
var expected = @""FilePath =Articles\Design\MalleableCodeUsingDecorators.md"";
";
var r = sut.ReplaceExpected(program, 3, @"FilePath =Articles\Design\MalleableCodeUsingDecorators.md", "boo");
var expected = @""" abc def
var expected = boo;
""";
TestHelper.Assert().PrintAreAlike(expected, r);
}
[Test]
public void Expected_variable()
{
string program =
@" abc def
var expected = @""hello"";
qwe ert
printer.Assert.Here(...)
iu of";
var r = sut.ReplaceExpected(program, 4, "hello", "boo");
var expected = @""" abc def
var expected = boo;
qwe ert
printer.Assert.Here(...)
iu of""";
TestHelper.Assert().PrintAreAlike(expected, r);
}
[Test]
public void Expected_variable_containsNewlines()
{
string program =
@" abc def
var expected = @""hello
"";
qwe ert
printer.Assert.Here(...)
iu of";
var r = sut.ReplaceExpected(program, 4, "hello\r\n", "boo");
var expected = @""" abc def
var expected = boo;
qwe ert
printer.Assert.Here(...)
iu of""";
TestHelper.Assert().PrintAreAlike(expected, r);
}
[Test]
public void Expected_variable_contains_brackets()
{
var r = sut.ReplaceExpected("Assert.AreEqual(\"[0]\", sut.Do());", 1, "[0]", "boo");
TestHelper.Assert().PrintAreAlike(@"""Assert.AreEqual(boo, sut.Do());""", r);
}
[Test]
public void Only_last_expected_changes_normal_string()
{
string program = @"abc def
var expected = @""b"";
var expected = ""b"";
qwe ert
printer.Assert.Here(...)
iu of";
var r = sut.ReplaceExpected(program, 4, "b", "boo");
string expected = @"""abc def
var expected = @""b"";
var expected = boo;
qwe ert
printer.Assert.Here(...)
iu of""";
TestHelper.Assert().PrintAreAlike(expected, r);
}
[Test]
public void Only_last_expected_changes_verbatim_string()
{
string program = @"abc def
var expected = ""b"";
var expected = @""b"";
qwe ert
printer.Assert.Here(...)
iu of";
var r = sut.ReplaceExpected(program, 4, "b", "boo");
string expected = @"""abc def
var expected = ""b"";
var expected = boo;
qwe ert
printer.Assert.Here(...)
iu of""";
TestHelper.Assert().PrintAreAlike(expected, r);
}
/// <summary>
/// Shows that we may further improve the matching to skip lines where lines start with "//"
/// </summary>
[Test]
public void Bug_outcommented_string_is_matched_()
{
string program = @"abc def
var expected = @""a"";
// var expected = @""a"";
qwe ert
printer.Assert.Here(...)
iu of";
var r = sut.ReplaceExpected(program, 4, "a", "boo");
var expected = @"abc def
var expected = @""a"";
// var expected = boo;
qwe ert
printer.Assert.Here(...)
iu of";
Assert.AreEqual(expected, r);
}
}
}
| |
/* Copyright (c) 2007, Dr. WPF
* 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 name Dr. WPF may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY Dr. WPF ``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 Dr. WPF BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
namespace SIL.ObjectModel
{
[Serializable]
public class ObservableDictionary<TKey, TValue> :
IObservableDictionary<TKey, TValue>,
IDictionary,
ISerializable,
IDeserializationCallback
{
#region constructors
#region public
public ObservableDictionary()
{
KeyedEntryCollection = new KeyedDictionaryEntryCollection();
}
public ObservableDictionary(IDictionary<TKey, TValue> dictionary)
{
KeyedEntryCollection = new KeyedDictionaryEntryCollection();
foreach (KeyValuePair<TKey, TValue> entry in dictionary)
DoAddEntry(entry.Key, entry.Value);
}
public ObservableDictionary(IEqualityComparer<TKey> comparer)
{
KeyedEntryCollection = new KeyedDictionaryEntryCollection(comparer);
}
public ObservableDictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer)
{
KeyedEntryCollection = new KeyedDictionaryEntryCollection(comparer);
foreach (KeyValuePair<TKey, TValue> entry in dictionary)
DoAddEntry(entry.Key, entry.Value);
}
#endregion public
#region protected
protected ObservableDictionary(SerializationInfo info, StreamingContext context)
{
_siInfo = info;
}
#endregion protected
#endregion constructors
#region properties
#region public
public IEqualityComparer<TKey> Comparer
{
get { return KeyedEntryCollection.Comparer; }
}
public int Count
{
get { return KeyedEntryCollection.Count; }
}
public Dictionary<TKey, TValue>.KeyCollection Keys
{
get { return TrueDictionary.Keys; }
}
public TValue this[TKey key]
{
get { return (TValue)KeyedEntryCollection[key].Value; }
set { DoSetEntry(key, value); }
}
public Dictionary<TKey, TValue>.ValueCollection Values
{
get { return TrueDictionary.Values; }
}
#endregion public
#region private
private Dictionary<TKey, TValue> TrueDictionary
{
get
{
if (_dictionaryCacheVersion != _version)
{
_dictionaryCache.Clear();
foreach (DictionaryEntry entry in KeyedEntryCollection)
_dictionaryCache.Add((TKey)entry.Key, (TValue)entry.Value);
_dictionaryCacheVersion = _version;
}
return _dictionaryCache;
}
}
#endregion private
#endregion properties
#region methods
#region public
public void Add(TKey key, TValue value)
{
DoAddEntry(key, value);
}
public void Clear()
{
DoClearEntries();
}
public bool ContainsKey(TKey key)
{
return KeyedEntryCollection.Contains(key);
}
public bool ContainsValue(TValue value)
{
return TrueDictionary.ContainsValue(value);
}
public IEnumerator GetEnumerator()
{
return new Enumerator(this, false);
}
public bool Remove(TKey key)
{
return DoRemoveEntry(key);
}
public bool TryGetValue(TKey key, out TValue value)
{
bool result = KeyedEntryCollection.Contains(key);
value = result ? (TValue)KeyedEntryCollection[key].Value : default(TValue);
return result;
}
#endregion public
#region protected
protected virtual bool AddEntry(TKey key, TValue value)
{
KeyedEntryCollection.Add(new DictionaryEntry(key, value));
return true;
}
protected virtual bool ClearEntries()
{
// check whether there are entries to clear
bool result = (Count > 0);
if (result)
{
// if so, clear the dictionary
KeyedEntryCollection.Clear();
}
return result;
}
protected int GetIndexAndEntryForKey(TKey key, out DictionaryEntry entry)
{
entry = new DictionaryEntry();
int index = -1;
if (KeyedEntryCollection.Contains(key))
{
entry = KeyedEntryCollection[key];
index = KeyedEntryCollection.IndexOf(entry);
}
return index;
}
protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs args)
{
NotifyCollectionChangedEventHandler handler = CollectionChanged;
if (handler != null)
handler(this, args);
}
protected virtual void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(name));
}
protected virtual bool RemoveEntry(TKey key)
{
// remove the entry
return KeyedEntryCollection.Remove(key);
}
protected virtual bool SetEntry(TKey key, TValue value)
{
bool keyExists = KeyedEntryCollection.Contains(key);
// if identical key/value pair already exists, nothing to do
if (keyExists && value.Equals((TValue)KeyedEntryCollection[key].Value))
return false;
// otherwise, remove the existing entry
if (keyExists)
KeyedEntryCollection.Remove(key);
// add the new entry
KeyedEntryCollection.Add(new DictionaryEntry(key, value));
return true;
}
#endregion protected
#region private
private void DoAddEntry(TKey key, TValue value)
{
if (AddEntry(key, value))
{
_version++;
DictionaryEntry entry;
int index = GetIndexAndEntryForKey(key, out entry);
FireEntryAddedNotifications(entry, index);
}
}
private void DoClearEntries()
{
if (ClearEntries())
{
_version++;
FireResetNotifications();
}
}
private bool DoRemoveEntry(TKey key)
{
DictionaryEntry entry;
int index = GetIndexAndEntryForKey(key, out entry);
bool result = RemoveEntry(key);
if (result)
{
_version++;
if (index > -1)
FireEntryRemovedNotifications(entry, index);
}
return result;
}
private void DoSetEntry(TKey key, TValue value)
{
DictionaryEntry entry;
int index = GetIndexAndEntryForKey(key, out entry);
if (SetEntry(key, value))
{
_version++;
// if prior entry existed for this key, fire the removed notifications
if (index > -1)
{
FireEntryRemovedNotifications(entry, index);
// force the property change notifications to fire for the modified entry
_countCache--;
}
// then fire the added notifications
index = GetIndexAndEntryForKey(key, out entry);
FireEntryAddedNotifications(entry, index);
}
}
private void FireEntryAddedNotifications(DictionaryEntry entry, int index)
{
// fire the relevant PropertyChanged notifications
FirePropertyChangedNotifications();
// fire CollectionChanged notification
if (index > -1)
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, new KeyValuePair<TKey, TValue>((TKey)entry.Key, (TValue)entry.Value), index));
else
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
private void FireEntryRemovedNotifications(DictionaryEntry entry, int index)
{
// fire the relevant PropertyChanged notifications
FirePropertyChangedNotifications();
// fire CollectionChanged notification
if (index > -1)
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, new KeyValuePair<TKey, TValue>((TKey)entry.Key, (TValue)entry.Value), index));
else
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
private void FirePropertyChangedNotifications()
{
if (Count != _countCache)
{
_countCache = Count;
OnPropertyChanged("Count");
OnPropertyChanged("Item[]");
OnPropertyChanged("Keys");
OnPropertyChanged("Values");
}
}
private void FireResetNotifications()
{
// fire the relevant PropertyChanged notifications
FirePropertyChangedNotifications();
// fire CollectionChanged notification
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
#endregion private
#endregion methods
#region interfaces
#region IDictionary<TKey, TValue>
void IDictionary<TKey, TValue>.Add(TKey key, TValue value)
{
DoAddEntry(key, value);
}
bool IDictionary<TKey, TValue>.Remove(TKey key)
{
return DoRemoveEntry(key);
}
bool IDictionary<TKey, TValue>.ContainsKey(TKey key)
{
return KeyedEntryCollection.Contains(key);
}
bool IDictionary<TKey, TValue>.TryGetValue(TKey key, out TValue value)
{
return TryGetValue(key, out value);
}
ICollection<TKey> IDictionary<TKey, TValue>.Keys
{
get { return Keys; }
}
ICollection<TValue> IDictionary<TKey, TValue>.Values
{
get { return Values; }
}
TValue IDictionary<TKey, TValue>.this[TKey key]
{
get { return (TValue)KeyedEntryCollection[key].Value; }
set { DoSetEntry(key, value); }
}
#endregion IDictionary<TKey, TValue>
#region IDictionary
void IDictionary.Add(object key, object value)
{
DoAddEntry((TKey)key, (TValue)value);
}
void IDictionary.Clear()
{
DoClearEntries();
}
bool IDictionary.Contains(object key)
{
return KeyedEntryCollection.Contains((TKey)key);
}
IDictionaryEnumerator IDictionary.GetEnumerator()
{
return new Enumerator(this, true);
}
bool IDictionary.IsFixedSize
{
get { return false; }
}
bool IDictionary.IsReadOnly
{
get { return false; }
}
object IDictionary.this[object key]
{
get { return KeyedEntryCollection[(TKey)key].Value; }
set { DoSetEntry((TKey)key, (TValue)value); }
}
ICollection IDictionary.Keys
{
get { return Keys; }
}
void IDictionary.Remove(object key)
{
DoRemoveEntry((TKey)key);
}
ICollection IDictionary.Values
{
get { return Values; }
}
#endregion IDictionary
#region ICollection<KeyValuePair<TKey, TValue>>
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> kvp)
{
DoAddEntry(kvp.Key, kvp.Value);
}
void ICollection<KeyValuePair<TKey, TValue>>.Clear()
{
DoClearEntries();
}
bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> kvp)
{
return KeyedEntryCollection.Contains(kvp.Key);
}
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int index)
{
if (array == null)
{
throw new ArgumentNullException("array");
}
if ((index < 0) || (index > array.Length))
{
throw new ArgumentOutOfRangeException("index");
}
if ((array.Length - index) < KeyedEntryCollection.Count)
{
throw new ArgumentException("supplied array was too small", "array");
}
foreach (DictionaryEntry entry in KeyedEntryCollection)
array[index++] = new KeyValuePair<TKey, TValue>((TKey)entry.Key, (TValue)entry.Value);
}
int ICollection<KeyValuePair<TKey, TValue>>.Count
{
get { return KeyedEntryCollection.Count; }
}
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
{
get { return false; }
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> kvp)
{
return DoRemoveEntry(kvp.Key);
}
#endregion ICollection<KeyValuePair<TKey, TValue>>
#region ICollection
void ICollection.CopyTo(Array array, int index)
{
((ICollection)KeyedEntryCollection).CopyTo(array, index);
}
int ICollection.Count
{
get { return KeyedEntryCollection.Count; }
}
bool ICollection.IsSynchronized
{
get { return ((ICollection)KeyedEntryCollection).IsSynchronized; }
}
object ICollection.SyncRoot
{
get { return ((ICollection)KeyedEntryCollection).SyncRoot; }
}
#endregion ICollection
#region IEnumerable<KeyValuePair<TKey, TValue>>
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
return new Enumerator(this, false);
}
#endregion IEnumerable<KeyValuePair<TKey, TValue>>
#region IEnumerable
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion IEnumerable
#region ISerializable
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException("info");
}
var entries = new Collection<DictionaryEntry>();
foreach (DictionaryEntry entry in KeyedEntryCollection)
entries.Add(entry);
info.AddValue("entries", entries);
}
#endregion ISerializable
#region IDeserializationCallback
public virtual void OnDeserialization(object sender)
{
if (_siInfo != null)
{
var entries = (Collection<DictionaryEntry>)
_siInfo.GetValue("entries", typeof(Collection<DictionaryEntry>));
foreach (DictionaryEntry entry in entries)
AddEntry((TKey)entry.Key, (TValue)entry.Value);
}
}
#endregion IDeserializationCallback
#region INotifyCollectionChanged
public virtual event NotifyCollectionChangedEventHandler CollectionChanged;
#endregion INotifyCollectionChanged
#region INotifyPropertyChanged
event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged
{
add { PropertyChanged += value; }
remove { PropertyChanged -= value; }
}
protected virtual event PropertyChangedEventHandler PropertyChanged;
#endregion INotifyPropertyChanged
#endregion interfaces
#region protected classes
#region KeyedDictionaryEntryCollection<TKey>
protected class KeyedDictionaryEntryCollection : KeyedList<TKey, DictionaryEntry>
{
#region constructors
#region public
public KeyedDictionaryEntryCollection()
{ }
public KeyedDictionaryEntryCollection(IEqualityComparer<TKey> comparer) : base(comparer) { }
#endregion public
#endregion constructors
#region methods
#region protected
protected override TKey GetKeyForItem(DictionaryEntry entry)
{
return (TKey)entry.Key;
}
#endregion protected
#endregion methods
}
#endregion KeyedDictionaryEntryCollection<TKey>
#endregion protected classes
#region public structures
#region Enumerator
[Serializable, StructLayout(LayoutKind.Sequential)]
public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>, IDictionaryEnumerator
{
#region constructors
internal Enumerator(ObservableDictionary<TKey, TValue> dictionary, bool isDictionaryEntryEnumerator)
{
_dictionary = dictionary;
_version = dictionary._version;
_index = -1;
_isDictionaryEntryEnumerator = isDictionaryEntryEnumerator;
_current = new KeyValuePair<TKey, TValue>();
}
#endregion constructors
#region properties
#region public
public KeyValuePair<TKey, TValue> Current
{
get
{
ValidateCurrent();
return _current;
}
}
#endregion public
#endregion properties
#region methods
#region public
public void Dispose()
{
}
public bool MoveNext()
{
ValidateVersion();
_index++;
if (_index < _dictionary.KeyedEntryCollection.Count)
{
_current = new KeyValuePair<TKey, TValue>((TKey)_dictionary.KeyedEntryCollection[_index].Key, (TValue)_dictionary.KeyedEntryCollection[_index].Value);
return true;
}
_index = -2;
_current = new KeyValuePair<TKey, TValue>();
return false;
}
#endregion public
#region private
private void ValidateCurrent()
{
if (_index == -1)
{
throw new InvalidOperationException("The enumerator has not been started.");
}
if (_index == -2)
{
throw new InvalidOperationException("The enumerator has reached the end of the collection.");
}
}
private void ValidateVersion()
{
if (_version != _dictionary._version)
{
throw new InvalidOperationException("The enumerator is not valid because the dictionary changed.");
}
}
#endregion private
#endregion methods
#region IEnumerator implementation
object IEnumerator.Current
{
get
{
ValidateCurrent();
if (_isDictionaryEntryEnumerator)
{
return new DictionaryEntry(_current.Key, _current.Value);
}
return new KeyValuePair<TKey, TValue>(_current.Key, _current.Value);
}
}
void IEnumerator.Reset()
{
ValidateVersion();
_index = -1;
_current = new KeyValuePair<TKey, TValue>();
}
#endregion IEnumerator implemenation
#region IDictionaryEnumerator implemenation
DictionaryEntry IDictionaryEnumerator.Entry
{
get
{
ValidateCurrent();
return new DictionaryEntry(_current.Key, _current.Value);
}
}
object IDictionaryEnumerator.Key
{
get
{
ValidateCurrent();
return _current.Key;
}
}
object IDictionaryEnumerator.Value
{
get
{
ValidateCurrent();
return _current.Value;
}
}
#endregion
#region fields
private readonly ObservableDictionary<TKey, TValue> _dictionary;
private readonly int _version;
private int _index;
private KeyValuePair<TKey, TValue> _current;
private readonly bool _isDictionaryEntryEnumerator;
#endregion fields
}
#endregion Enumerator
#endregion public structures
#region fields
protected KeyedDictionaryEntryCollection KeyedEntryCollection;
private int _countCache;
private readonly Dictionary<TKey, TValue> _dictionaryCache = new Dictionary<TKey, TValue>();
private int _dictionaryCacheVersion;
private int _version;
[NonSerialized]
private readonly SerializationInfo _siInfo;
#endregion fields
}
}
| |
using System;
using NUnit.Framework;
#if FX1_1
using IList_ServiceElement = System.Collections.IList;
using List_ServiceElement = System.Collections.ArrayList;
using IList_ServiceAttribute = System.Collections.IList;
using List_ServiceAttribute = System.Collections.ArrayList;
#else
using IList_ServiceElement = System.Collections.Generic.IList<InTheHand.Net.Bluetooth.ServiceElement>;
using List_ServiceElement = System.Collections.Generic.List<InTheHand.Net.Bluetooth.ServiceElement>;
using IList_ServiceAttribute = System.Collections.Generic.IList<InTheHand.Net.Bluetooth.ServiceAttribute>;
using List_ServiceAttribute = System.Collections.Generic.List<InTheHand.Net.Bluetooth.ServiceAttribute>;
#endif
using System.Text;
using System.Net;
using InTheHand.Net.Bluetooth;
namespace InTheHand.Net.Tests.Sdp2
{
[TestFixture]
public class ElementTests
{
//------------------------------
[Test]
public void Nil() { new ServiceElement(ElementType.Nil, null); }
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = "CLR type 'Int32' not valid type for element type 'Nil'.")]
public void NilNonNullVal() { new ServiceElement(ElementType.Nil, 5); }
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = "CLR type 'String' not valid type for element type 'Nil'.")]
public void NilNonNullObj() { new ServiceElement(ElementType.Nil, "fooo"); }
//------------------------------
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void List_NullLiteral()
{
new ServiceElement(ElementType.ElementSequence, null);
}
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void List_Null()
{
#if FX1_1
System.Collections.IList list = null;
#else
System.Collections.Generic.IList<ServiceElement> list = null;
#endif
new ServiceElement(ElementType.ElementSequence, list);
}
[Test]
public void List_EmptyArray()
{
ServiceElement[] array = new ServiceElement[0];
ServiceElement element = new ServiceElement(ElementType.ElementSequence, array);
IList_ServiceElement list = element.GetValueAsElementList();
Assert.AreEqual(0, list.Count);
}
//------------------------------
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void ParamsArray_ExplicitNull()
{
ServiceElement[] array = null;
ServiceElement element = new ServiceElement(ElementType.ElementSequence, array);
}
[Test]
public void ParamsArray_None()
{
ServiceElement element = new ServiceElement(ElementType.ElementSequence);
IList_ServiceElement list = element.GetValueAsElementList();
Assert.AreEqual(0, list.Count);
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = ServiceElement.ErrorMsgSeqAltTypeNeedElementArray)]
public void ParamsArray_None_BadNoSeqOrAlt()
{
ServiceElement element = new ServiceElement(ElementType.Uuid16);
}
[Test]
public void ParamsArray_ExplicitNone()
{
ServiceElement[] array = new ServiceElement[0];
ServiceElement element = new ServiceElement(ElementType.ElementSequence, array);
IList_ServiceElement list = element.GetValueAsElementList();
Assert.AreEqual(0, list.Count);
}
[Test]
public void ParamsArray_Some()
{
ServiceElement e0 = new ServiceElement(ElementType.UInt8, (byte)5);
ServiceElement e1 = new ServiceElement(ElementType.Uuid16, (UInt16)0x1105);
ServiceElement e2 = new ServiceElement(ElementType.UInt16, (UInt16)0x5555);
ServiceElement element = new ServiceElement(ElementType.ElementSequence,
e0, e1, e2);
IList_ServiceElement list = element.GetValueAsElementList();
Assert.AreEqual(3, list.Count);
Assert.AreSame(e0, list[0]);
Assert.AreSame(e1, list[1]);
Assert.AreSame(e2, list[2]);
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = ServiceElement.ErrorMsgSeqAltTypeNeedElementArray)]
public void ParamsArray_Some_BadNoSeqOrAlt()
{
ServiceElement e0 = new ServiceElement(ElementType.UInt8, (byte)5);
ServiceElement e1 = new ServiceElement(ElementType.Uuid16, (UInt16)0x1105);
ServiceElement e2 = new ServiceElement(ElementType.UInt16, (UInt16)0x5555);
ServiceElement element = new ServiceElement(ElementType.Uuid16,
e0, e1, e2);
}
//------------------------------
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void Url_NullLiteral()
{
new ServiceElement(ElementType.Url, null);
}
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void String_NullLiteral()
{
new ServiceElement(ElementType.TextString, null);
}
//--------------------------------------------------------------
// [Test]
// [ExpectedException(typeof(ProtocolViolationException),
// "ElementType 'Boolean' is not of given TypeDescriptor 'ElementAlternative'.")]
// public void BadTypeTypePair()
// {
//#pragma warning disable 618
// new ServiceElement(ElementTypeDescriptor.ElementAlternative, ElementType.Boolean, 0);
//#pragma warning restore 618
// }
//--------------------------------------------------------------
[Test]
public void TestingPropertiesWithTypeBoolean()
{
ServiceElement element = new ServiceElement(ElementType.Boolean, true);
Assert.AreEqual(ElementTypeDescriptor.Boolean, element.ElementTypeDescriptor);
Assert.AreEqual(ElementType.Boolean, element.ElementType);
Assert.AreEqual(true, element.Value);
element = new ServiceElement(ElementType.Boolean, false);
Assert.AreEqual(ElementTypeDescriptor.Boolean, element.ElementTypeDescriptor);
Assert.AreEqual(ElementType.Boolean, element.ElementType);
Assert.AreEqual(false, element.Value);
}
[Test]
public void TestingPropertiesWithTypeInt32()
{
ServiceElement element = new ServiceElement(ElementType.Int32, 5);
Assert.AreEqual(ElementTypeDescriptor.TwosComplementInteger, element.ElementTypeDescriptor);
Assert.AreEqual(ElementType.Int32, element.ElementType);
Assert.AreEqual(5, element.Value);
element = new ServiceElement(ElementType.Int32, 0x01000);
Assert.AreEqual(ElementTypeDescriptor.TwosComplementInteger, element.ElementTypeDescriptor);
Assert.AreEqual(ElementType.Int32, element.ElementType);
Assert.AreEqual(0x01000, element.Value);
}
[Test]
public void TestingPropertiesWithTypeInt64()
{
ServiceElement element = new ServiceElement(ElementType.Int64, (Int64)5);
Assert.AreEqual(ElementTypeDescriptor.TwosComplementInteger, element.ElementTypeDescriptor);
Assert.AreEqual(ElementType.Int64, element.ElementType);
Assert.AreEqual(5, element.Value);
element = new ServiceElement(ElementType.Int64, (Int64)0x01000);
Assert.AreEqual(ElementTypeDescriptor.TwosComplementInteger, element.ElementTypeDescriptor);
Assert.AreEqual(ElementType.Int64, element.ElementType);
Assert.AreEqual(0x01000, element.Value);
}
[Test]
public void TestingPropertiesWithTypeInt128()
{
byte[] input1 = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
byte[] inputOneShort = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /*16*/ };
//
try {
ServiceElement element = new ServiceElement(ElementType.Int128, input1);
Assert.Fail("should have thrown!");
} catch (ArgumentOutOfRangeException ex) {
Assert.AreEqual("Unknown ElementType 'Int128'." + "\r\nParameter name: type",
ex.Message, "ex.Message");
}
//TO-DOAssert.AreEqual(ElementTypeDescriptor.TwosComplementInteger, element.ElementTypeDescriptor);
//Assert.AreEqual(ElementType.Int128, element.ElementType);
//Assert.AreEqual(input1, element.Value);
//
//element = new ServiceElement(ElementType.Int128, inputOneShort);
//Assert.AreEqual(ElementTypeDescriptor.TwosComplementInteger, element.ElementTypeDescriptor);
//Assert.AreEqual(ElementType.Int128, element.ElementType);
//Assert.AreEqual(0x01000, element.Value);
}
[Test]
public void TestingPropertiesWithTypeUri()
{
String str = "http://example.com/foo.html";
Uri value = new Uri(str);
ServiceElement element = new ServiceElement(ElementType.Url, value);
Assert.AreEqual(ElementTypeDescriptor.Url, element.ElementTypeDescriptor);
Assert.AreEqual(ElementType.Url, element.ElementType);
Assert.AreEqual(new Uri(str), element.Value);
Assert.AreEqual(new Uri(str), element.GetValueAsUri());
}
[Test]
public void TestingPropertiesWithTypeUriLazyCreation()
{
String str = "ftp://ftp.example.com/foo/bar.txt";
byte[] valueBytes = Encoding.ASCII.GetBytes(str);
ServiceElement element = new ServiceElement(ElementType.Url, valueBytes);
Assert.AreEqual(ElementTypeDescriptor.Url, element.ElementTypeDescriptor);
Assert.AreEqual(ElementType.Url, element.ElementType);
Assert.IsInstanceOfType(typeof(byte[]), element.Value);
Assert.AreEqual(new Uri(str), element.GetValueAsUri());
}
//--------------------------------------------------------------
[Test]
public void StringUtf8Empty()
{
byte[] bytes = new byte[0];
ServiceElement element = new ServiceElement(ElementType.TextString, bytes);
Assert.AreEqual(ElementTypeDescriptor.TextString, element.ElementTypeDescriptor);
Assert.AreEqual(ElementType.TextString, element.ElementType);
Assert.IsInstanceOfType(typeof(byte[]), element.Value);
Assert.AreEqual(String.Empty, element.GetValueAsStringUtf8());
Assert.AreEqual(0, element.GetValueAsStringUtf8().Length);
}
[Test]
public void StringUtf8AllAscii()
{
String str = "ambdsanbdasdlkaslkda";
byte[] bytes = Encoding.UTF8.GetBytes(str);
ServiceElement element = new ServiceElement(ElementType.TextString, bytes);
Assert.AreEqual(ElementTypeDescriptor.TextString, element.ElementTypeDescriptor);
Assert.AreEqual(ElementType.TextString, element.ElementType);
Assert.IsInstanceOfType(typeof(byte[]), element.Value);
Assert.AreEqual(str, element.GetValueAsStringUtf8());
}
[Test]
public void StringUtf8AllAsciiWithANullTerminationByte()
{
String str = "ambdsanbdasdlkaslkda";
byte[] bytes_ = Encoding.UTF8.GetBytes(str);
// Add a null-termination byte
byte[] bytes = new byte[bytes_.Length + 1];
bytes_.CopyTo(bytes, 0);
ServiceElement element = new ServiceElement(ElementType.TextString, bytes);
Assert.AreEqual(ElementTypeDescriptor.TextString, element.ElementTypeDescriptor);
Assert.AreEqual(ElementType.TextString, element.ElementType);
Assert.IsInstanceOfType(typeof(byte[]), element.Value);
Assert.AreEqual(str, element.GetValueAsStringUtf8());
}
[Test]
public void StringUtf8WithVariousHighChars()
{
String str = "ambds\u2022nbdas\u00FEdlka\U00012004slkda";
byte[] bytes = Encoding.UTF8.GetBytes(str);
ServiceElement element = new ServiceElement(ElementType.TextString, bytes);
Assert.AreEqual(ElementTypeDescriptor.TextString, element.ElementTypeDescriptor);
Assert.AreEqual(ElementType.TextString, element.ElementType);
Assert.IsInstanceOfType(typeof(byte[]), element.Value);
Assert.AreEqual(str, element.GetValueAsStringUtf8());
}
//--------------------------------------------------------------
[Test]
public void StringGivenString()
{
String str = "ambds\u2022nbdas\u00FEdlka\U00012004slkda";
ServiceElement element = new ServiceElement(ElementType.TextString, str);
//
Assert.AreEqual(ElementTypeDescriptor.TextString, element.ElementTypeDescriptor);
Assert.AreEqual(ElementType.TextString, element.ElementType);
Assert.IsInstanceOfType(typeof(String), element.Value);
Assert.AreEqual(str, element.GetValueAsStringUtf8());
Assert.AreEqual(str, element.GetValueAsString(Encoding.ASCII));
Assert.AreEqual(str, element.GetValueAsString(Encoding.Unicode));
}
//--------------------------------------------------------------
//[Test]
//public void SequenceZeroItems()
//{
// ServiceElement element = new
//}
//--------------------------------------------------------------
Guid CreateBluetoothBasedUuid(UInt32 shortForm)
{
return new Guid(
#if NETCF
unchecked((int)shortForm)
#else
shortForm
#endif
, 0x0000, 0x1000, 0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB);
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = "CLR type 'Guid' not valid type for element type 'Uuid16'.")]
public void BadUuid16ButUuid128()
{
new ServiceElement(ElementType.Uuid16, CreateBluetoothBasedUuid(0x1105));
}
[Test]
public void Uuid16As128()
{
ServiceElement element = new ServiceElement(ElementType.Uuid16, (UInt16)0x1105);
Assert.AreEqual(ElementTypeDescriptor.Uuid, element.ElementTypeDescriptor);
Assert.AreEqual(ElementType.Uuid16, element.ElementType);
//Assert.IsInstanceOfType(typeof(UInt16), element.Value);
Guid expected = CreateBluetoothBasedUuid(0x1105);
Assert.AreEqual(expected, element.GetValueAsUuid());
}
[Test]
public void Uuid32As128()
{
ServiceElement element = new ServiceElement(ElementType.Uuid32, (UInt32)0x1105);
Assert.AreEqual(ElementTypeDescriptor.Uuid, element.ElementTypeDescriptor);
Assert.AreEqual(ElementType.Uuid32, element.ElementType);
//Assert.IsInstanceOfType(typeof(UInt32), element.Value);
Guid expected = CreateBluetoothBasedUuid(0x1105);
Assert.AreEqual(expected, element.GetValueAsUuid());
}
[Test]
public void Uuid128As128()
{
ServiceElement element = new ServiceElement(ElementType.Uuid128, CreateBluetoothBasedUuid(0x1105));
Assert.AreEqual(ElementTypeDescriptor.Uuid, element.ElementTypeDescriptor);
Assert.AreEqual(ElementType.Uuid128, element.ElementType);
//Assert.IsInstanceOfType(typeof(Guid), element.Value);
Guid expected = CreateBluetoothBasedUuid(0x1105);
Assert.AreEqual(expected, element.GetValueAsUuid());
}
}//class
}
| |
// 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.
/*============================================================
**
**
**
** Object is the root class for all CLR objects. This class
** defines only the basics.
**
**
===========================================================*/
namespace System {
using System;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
using CultureInfo = System.Globalization.CultureInfo;
using FieldInfo = System.Reflection.FieldInfo;
using BindingFlags = System.Reflection.BindingFlags;
#if FEATURE_REMOTING
using RemotingException = System.Runtime.Remoting.RemotingException;
#endif
// The Object is the root class for all object in the CLR System. Object
// is the super class for all other CLR objects and provide a set of methods and low level
// services to subclasses. These services include object synchronization and support for clone
// operations.
//
//This class contains no data and does not need to be serializable
[Serializable]
[ClassInterface(ClassInterfaceType.AutoDual)]
[System.Runtime.InteropServices.ComVisible(true)]
public class Object
{
// Creates a new instance of an Object.
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
[System.Runtime.Versioning.NonVersionable]
public Object()
{
}
// Returns a String which represents the object instance. The default
// for an object is to return the fully qualified name of the class.
//
public virtual String ToString()
{
return GetType().ToString();
}
// Returns a boolean indicating if the passed in object obj is
// Equal to this. Equality is defined as object equality for reference
// types and bitwise equality for value types using a loader trick to
// replace Equals with EqualsValue for value types).
//
public virtual bool Equals(Object obj)
{
return RuntimeHelpers.Equals(this, obj);
}
public static bool Equals(Object objA, Object objB)
{
if (objA==objB) {
return true;
}
if (objA==null || objB==null) {
return false;
}
return objA.Equals(objB);
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public static bool ReferenceEquals (Object objA, Object objB) {
return objA == objB;
}
// GetHashCode is intended to serve as a hash function for this object.
// Based on the contents of the object, the hash function will return a suitable
// value with a relatively random distribution over the various inputs.
//
// The default implementation returns the sync block index for this instance.
// Calling it on the same object multiple times will return the same value, so
// it will technically meet the needs of a hash function, but it's less than ideal.
// Objects (& especially value classes) should override this method.
//
public virtual int GetHashCode()
{
return RuntimeHelpers.GetHashCode(this);
}
// Returns a Type object which represent this object instance.
//
[System.Security.SecuritySafeCritical] // auto-generated
[Pure]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern Type GetType();
// Allow an object to free resources before the object is reclaimed by the GC.
//
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
~Object()
{
}
// Returns a new object instance that is a memberwise copy of this
// object. This is always a shallow copy of the instance. The method is protected
// so that other object may only call this method on themselves. It is entended to
// support the ICloneable interface.
//
[System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
protected extern Object MemberwiseClone();
// Sets the value specified in the variant on the field
//
[System.Security.SecurityCritical] // auto-generated
private void FieldSetter(String typeName, String fieldName, Object val)
{
Contract.Requires(typeName != null);
Contract.Requires(fieldName != null);
// Extract the field info object
FieldInfo fldInfo = GetFieldInfo(typeName, fieldName);
if (fldInfo.IsInitOnly)
throw new FieldAccessException(Environment.GetResourceString("FieldAccess_InitOnly"));
// Make sure that the value is compatible with the type
// of field
#if FEATURE_REMOTING
System.Runtime.Remoting.Messaging.Message.CoerceArg(val, fldInfo.FieldType);
#else
Type pt=fldInfo.FieldType;
if (pt.IsByRef)
{
pt = pt.GetElementType();
}
if (!pt.IsInstanceOfType(val))
{
val = Convert.ChangeType(val, pt, CultureInfo.InvariantCulture);
}
#endif
// Set the value
fldInfo.SetValue(this, val);
}
// Gets the value specified in the variant on the field
//
private void FieldGetter(String typeName, String fieldName, ref Object val)
{
Contract.Requires(typeName != null);
Contract.Requires(fieldName != null);
// Extract the field info object
FieldInfo fldInfo = GetFieldInfo(typeName, fieldName);
// Get the value
val = fldInfo.GetValue(this);
}
// Gets the field info object given the type name and field name.
//
private FieldInfo GetFieldInfo(String typeName, String fieldName)
{
Contract.Requires(typeName != null);
Contract.Requires(fieldName != null);
Contract.Ensures(Contract.Result<FieldInfo>() != null);
Type t = GetType();
while(null != t)
{
if(t.FullName.Equals(typeName))
{
break;
}
t = t.BaseType;
}
if (null == t)
{
#if FEATURE_REMOTING
throw new RemotingException(String.Format(
CultureInfo.CurrentCulture, Environment.GetResourceString("Remoting_BadType"),
typeName));
#else
throw new ArgumentException();
#endif
}
FieldInfo fldInfo = t.GetField(fieldName, BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.IgnoreCase);
if(null == fldInfo)
{
#if FEATURE_REMOTING
throw new RemotingException(String.Format(
CultureInfo.CurrentCulture, Environment.GetResourceString("Remoting_BadField"),
fieldName, typeName));
#else
throw new ArgumentException();
#endif
}
return fldInfo;
}
}
// Internal methodtable used to instantiate the "canonical" methodtable for generic instantiations.
// The name "__Canon" will never been seen by users but it will appear a lot in debugger stack traces
// involving generics so it is kept deliberately short as to avoid being a nuisance.
[Serializable]
[ClassInterface(ClassInterfaceType.AutoDual)]
[System.Runtime.InteropServices.ComVisible(true)]
internal class __Canon
{
}
}
| |
using System;
using System.IO;
using System.Text.RegularExpressions;
#if ASYNC
using System.Threading.Tasks;
#endif
namespace FluentFTP.Proxy {
/// <summary> A FTP client with a HTTP 1.1 proxy implementation. </summary>
public class FtpClientHttp11Proxy : FtpClientProxy {
/// <summary> A FTP client with a HTTP 1.1 proxy implementation </summary>
/// <param name="proxy">Proxy information</param>
public FtpClientHttp11Proxy(ProxyInfo proxy)
: base(proxy) {
ConnectionType = "HTTP 1.1 Proxy";
}
/// <summary> Redefine the first dialog: HTTP Frame for the HTTP 1.1 Proxy </summary>
protected override void Handshake() {
var proxyConnectionReply = GetReply();
if (!proxyConnectionReply.Success)
throw new FtpException("Can't connect " + Host + " via proxy " + Proxy.Host + ".\nMessage : " +
proxyConnectionReply.ErrorMessage);
// TO TEST: if we are able to detect the actual FTP server software from this reply
HandshakeReply = proxyConnectionReply;
}
/// <summary>
/// Creates a new instance of this class. Useful in FTP proxy classes.
/// </summary>
protected override FtpClient Create() {
return new FtpClientHttp11Proxy(Proxy);
}
/// <summary>
/// Connects to the server using an existing <see cref="FtpSocketStream"/>
/// </summary>
/// <param name="stream">The existing socket stream</param>
protected override void Connect(FtpSocketStream stream) {
Connect(stream, Host, Port, FtpIpVersion.ANY);
}
#if ASYNC
/// <summary>
/// Connects to the server using an existing <see cref="FtpSocketStream"/>
/// </summary>
/// <param name="stream">The existing socket stream</param>
protected override Task ConnectAsync(FtpSocketStream stream)
{
return ConnectAsync(stream, Host, Port, FtpIpVersion.ANY);
}
#endif
/// <summary>
/// Connects to the server using an existing <see cref="FtpSocketStream"/>
/// </summary>
/// <param name="stream">The existing socket stream</param>
/// <param name="host">Host name</param>
/// <param name="port">Port number</param>
/// <param name="ipVersions">IP version to use</param>
protected override void Connect(FtpSocketStream stream, string host, int port, FtpIpVersion ipVersions) {
base.Connect(stream);
var writer = new StreamWriter(stream);
writer.WriteLine("CONNECT {0}:{1} HTTP/1.1", host, port);
writer.WriteLine("Host: {0}:{1}", host, port);
if (Proxy.Credentials != null) {
var credentialsHash = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(Proxy.Credentials.UserName + ":"+ Proxy.Credentials.Password));
writer.WriteLine("Proxy-Authorization: Basic "+ credentialsHash);
}
writer.WriteLine("User-Agent: custom-ftp-client");
writer.WriteLine();
writer.Flush();
ProxyHandshake(stream);
}
#if ASYNC
/// <summary>
/// Connects to the server using an existing <see cref="FtpSocketStream"/>
/// </summary>
/// <param name="stream">The existing socket stream</param>
/// <param name="host">Host name</param>
/// <param name="port">Port number</param>
/// <param name="ipVersions">IP version to use</param>
protected override async Task ConnectAsync(FtpSocketStream stream, string host, int port, FtpIpVersion ipVersions)
{
await base.ConnectAsync(stream);
var writer = new StreamWriter(stream);
await writer.WriteLineAsync(string.Format("CONNECT {0}:{1} HTTP/1.1", host, port));
await writer.WriteLineAsync(string.Format("Host: {0}:{1}", host, port));
if (Proxy.Credentials != null)
{
var credentialsHash = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(Proxy.Credentials.UserName + ":" + Proxy.Credentials.Password));
await writer.WriteLineAsync("Proxy-Authorization: Basic " + credentialsHash);
}
await writer.WriteLineAsync("User-Agent: custom-ftp-client");
await writer.WriteLineAsync();
await writer.FlushAsync();
await ProxyHandshakeAsync(stream);
}
#endif
private void ProxyHandshake(FtpSocketStream stream) {
var proxyConnectionReply = GetProxyReply(stream);
if (!proxyConnectionReply.Success)
throw new FtpException("Can't connect " + Host + " via proxy " + Proxy.Host + ".\nMessage : " + proxyConnectionReply.ErrorMessage);
}
#if ASYNC
private async Task ProxyHandshakeAsync(FtpSocketStream stream)
{
var proxyConnectionReply = await GetProxyReplyAsync(stream);
if (!proxyConnectionReply.Success)
throw new FtpException("Can't connect " + Host + " via proxy " + Proxy.Host + ".\nMessage : " + proxyConnectionReply.ErrorMessage);
}
#endif
private FtpReply GetProxyReply( FtpSocketStream stream ) {
FtpReply reply = new FtpReply();
string buf;
#if !CORE14
lock ( Lock ) {
#endif
if( !IsConnected )
throw new InvalidOperationException( "No connection to the server has been established." );
stream.ReadTimeout = ReadTimeout;
while( ( buf = stream.ReadLine( Encoding ) ) != null ) {
Match m;
this.LogLine(FtpTraceLevel.Info, buf);
if( ( m = Regex.Match( buf, @"^HTTP/.*\s(?<code>[0-9]{3}) (?<message>.*)$" ) ).Success ) {
reply.Code = m.Groups[ "code" ].Value;
reply.Message = m.Groups[ "message" ].Value;
break;
}
reply.InfoMessages += ( buf+"\n" );
}
// fixes #84 (missing bytes when downloading/uploading files through proxy)
while( ( buf = stream.ReadLine( Encoding ) ) != null ) {
this.LogLine(FtpTraceLevel.Info, buf);
if (FtpExtensions.IsNullOrWhiteSpace(buf)) {
break;
}
reply.InfoMessages += ( buf+"\n" );
}
#if !CORE14
}
#endif
return reply;
}
#if ASYNC
private async Task<FtpReply> GetProxyReplyAsync(FtpSocketStream stream)
{
FtpReply reply = new FtpReply();
string buf;
if (!IsConnected)
throw new InvalidOperationException("No connection to the server has been established.");
stream.ReadTimeout = ReadTimeout;
while ((buf = await stream.ReadLineAsync(Encoding)) != null)
{
Match m;
this.LogLine(FtpTraceLevel.Info, buf);
if ((m = Regex.Match(buf, @"^HTTP/.*\s(?<code>[0-9]{3}) (?<message>.*)$")).Success)
{
reply.Code = m.Groups["code"].Value;
reply.Message = m.Groups["message"].Value;
break;
}
reply.InfoMessages += (buf + "\n");
}
// fixes #84 (missing bytes when downloading/uploading files through proxy)
while ((buf = await stream.ReadLineAsync(Encoding)) != null)
{
this.LogLine(FtpTraceLevel.Info, buf);
if (FtpExtensions.IsNullOrWhiteSpace(buf))
{
break;
}
reply.InfoMessages += (buf + "\n");
}
return reply;
}
#endif
}
}
| |
using System;
using System.Collections.Generic;
using CocosSharp;
using Random = CocosSharp.CCRandom;
namespace tests
{
public class ParticleTestScene : TestScene
{
#region eIDClick enum
public enum eIDClick
{
IDC_NEXT = 100,
IDC_BACK,
IDC_RESTART,
IDC_TOGGLE
};
#endregion
internal static int TagLabelAtlas = 1;
internal static int SceneIdx = -1;
internal static int MAX_LAYER = 43;
public static CCLayer CreateParticleLayer(int nIndex)
{
switch (nIndex)
{
case 0:
return new ParticleReorder();
case 1:
return new ParticleBatchHybrid();
case 2:
return new ParticleBatchMultipleEmitters();
case 3:
return new DemoFlower();
case 4:
return new DemoGalaxy();
case 5:
return new DemoFirework();
case 6:
return new DemoSpiral();
case 7:
return new DemoSun();
case 8:
return new DemoMeteor();
case 9:
return new DemoFire();
case 10:
return new DemoSmoke();
case 11:
return new DemoExplosion();
case 12:
return new DemoSnow();
case 13:
return new DemoRain();
case 14:
return new DemoBigFlower();
case 15:
return new DemoRotFlower();
case 16:
return new DemoModernArt();
case 17:
return new DemoRing();
case 18:
return new ParallaxParticle();
case 19:
return new DemoParticleFromFile("BoilingFoam");
case 20:
return new DemoParticleFromFile("BurstPipe");
case 21:
return new DemoParticleFromFile("Comet");
case 22:
return new DemoParticleFromFile("debian");
case 23:
return new DemoParticleFromFile("ExplodingRing");
case 24:
return new DemoParticleFromFile("LavaFlow");
case 25:
return new DemoParticleFromFile("SpinningPeas");
case 26:
return new DemoParticleFromFile("SpookyPeas");
case 27:
return new DemoParticleFromFile("Upsidedown");
case 28:
return new DemoParticleFromFile("Flower");
case 29:
return new DemoParticleFromFile("Spiral");
case 30:
return new DemoParticleFromFile("Galaxy");
case 31:
return new DemoParticleFromFile("Phoenix");
case 32:
return new RadiusMode1();
case 33:
return new RadiusMode2();
case 34:
return new Issue704();
case 35:
return new Issue870();
case 36:
return new Issue1201();
// v1.1 tests
case 37:
return new MultipleParticleSystems();
case 38:
return new MultipleParticleSystemsBatched();
case 39:
return new AddAndDeleteParticleSystems();
case 40:
return new ReorderParticleSystems();
case 41:
return new PremultipliedAlphaTest();
case 42:
return new PremultipliedAlphaTest2();
}
return null;
}
public static CCLayer NextParticleAction()
{
SceneIdx++;
SceneIdx = SceneIdx % MAX_LAYER;
CCLayer layer = CreateParticleLayer(SceneIdx);
return layer;
}
public static CCLayer BackParticleAction()
{
SceneIdx--;
int total = MAX_LAYER;
if (SceneIdx < 0)
SceneIdx += total;
CCLayer layer = CreateParticleLayer(SceneIdx);
return layer;
}
public static CCLayer RestartParticleAction()
{
CCLayer layer = CreateParticleLayer(SceneIdx);
return layer;
}
protected override void NextTestCase()
{
NextParticleAction();
}
protected override void PreviousTestCase()
{
BackParticleAction();
}
protected override void RestTestCase()
{
RestartParticleAction();
}
public override void runThisTest()
{
AddChild(NextParticleAction());
Director.ReplaceScene(this);
}
};
//public class ParticleDemo : CCLayerColor
public class ParticleDemo : TestNavigationLayer
{
const int labelTag = 9000;
protected CCPoint MidWindowPoint;
protected CCSize WindowSize;
protected CCParticleSystem Emitter;
protected CCSprite Background;
CCLabelAtlas particleCounter;
CCMenu particleMenu;
CCMenuItemToggle toggleParticleMovMenuItem;
CCLayerColor coloredBackground;
#region Constructors
public ParticleDemo()
{
toggleParticleMovMenuItem = new CCMenuItemToggle(ToggleCallback,
new CCMenuItemFont("Free Movement"),
new CCMenuItemFont("Relative Movement"),
new CCMenuItemFont("Grouped Movement"));
particleMenu = new CCMenu(toggleParticleMovMenuItem);
AddChild(particleMenu, 100);
particleCounter = new CCLabelAtlas("0000", "Images/fps_Images", 16, 64, '.');
AddChild(particleCounter, 100, ParticleTestScene.TagLabelAtlas);
Background = new CCSprite(TestResource.s_back3);
AddChild(Background, 5);
// Add event listeners
var listener = new CCEventListenerTouchAllAtOnce();
listener.OnTouchesBegan = OnTouchesBegan;
listener.OnTouchesMoved = OnTouchesMoved;
listener.OnTouchesEnded = OnTouchesEnded;
AddEventListener(listener);
coloredBackground = new CCLayerColor(new CCColor4B(127, 127, 127, 255));
AddChild(coloredBackground, 4);
}
#endregion Constructors
#region Setup content
static CCMoveBy move = new CCMoveBy (4, new CCPoint(300, 0));
static CCFiniteTimeAction move_back = move.Reverse();
protected override void AddedToScene()
{
base.AddedToScene();
CCSize windowSize = Layer.VisibleBoundsWorldspace.Size;
WindowSize = windowSize;
MidWindowPoint = windowSize.Center;
// Laying out content based on window size
particleMenu.Position = CCPoint.Zero;
toggleParticleMovMenuItem.Position = new CCPoint(10, 100);
toggleParticleMovMenuItem.AnchorPoint = CCPoint.AnchorLowerLeft;
particleCounter.Position = new CCPoint(windowSize.Width - 70, 50);
// Background could have been removed by overriding class
if (Background != null)
{
Background.Position = new CCPoint(windowSize.Width / 2, windowSize.Height - 180);
// Run background animation
Background.RepeatForever(move, move_back);
}
Schedule(Step);
}
#endregion Setup content
#region Properties
public override CCColor3B Color
{
get { return coloredBackground.Color; }
set
{
coloredBackground.Color = value;
}
}
#endregion Properties
#region Titles
public override string Title
{
get
{
return base.Title;
}
}
public override string Subtitle
{
get
{
return base.Subtitle;
}
}
#endregion Titles
#region Callbacks
public override void RestartCallback(object sender)
{
if (Emitter != null)
{
Emitter.ResetSystem();
}
}
public override void NextCallback(object sender)
{
var s = new ParticleTestScene();
s.AddChild(ParticleTestScene.NextParticleAction());
Director.ReplaceScene(s);
}
public override void BackCallback(object sender)
{
var s = new ParticleTestScene();
s.AddChild(ParticleTestScene.BackParticleAction());
Director.ReplaceScene(s);
}
void ToggleCallback(object sender)
{
if (Emitter != null)
{
if (Emitter.PositionType == CCPositionType.Grouped)
Emitter.PositionType = CCPositionType.Free;
else if (Emitter.PositionType == CCPositionType.Free)
Emitter.PositionType = CCPositionType.Relative;
else if (Emitter.PositionType == CCPositionType.Relative)
Emitter.PositionType = CCPositionType.Grouped;
}
}
#endregion Callbacks
#region Event handling
void OnTouchesBegan(List<CCTouch> touches, CCEvent touchEvent)
{
OnTouchesEnded(touches, touchEvent);
}
void OnTouchesMoved(List<CCTouch> touches, CCEvent touchEvent)
{
OnTouchesEnded(touches, touchEvent);
}
void OnTouchesEnded(List<CCTouch> touches, CCEvent touchEvent)
{
var touch = touches [0];
var convertedLocation = touch.LocationOnScreen;
var pos = new CCPoint(0, 0);
if (Background != null)
{
pos = Background.Layer.ScreenToWorldspace(CCPoint.Zero);
}
if (Emitter != null)
{
Emitter.Position = convertedLocation - pos;
}
}
#endregion Event handling
void Step(float dt)
{
var atlas = (CCLabelAtlas) GetChildByTag(ParticleTestScene.TagLabelAtlas);
if (Emitter != null)
{
string str = string.Format("{0:0000}", Emitter.ParticleCount);
atlas.Text = (str);
}
else
{
int count = 0;
for (int i = 0; i < Children.Count; i++)
{
if (Children[i] is CCParticleSystem)
{
count += ((CCParticleSystem) Children[i]).ParticleCount;
}
else if (Children[i] is CCParticleBatchNode)
{
var bn = (CCParticleBatchNode) Children[i];
for (int j = 0; j < bn.ChildrenCount; j++)
{
if (bn.Children[j] is CCParticleSystem)
{
count += ((CCParticleSystem) bn.Children[j]).ParticleCount;
}
}
}
}
string str = string.Format("{0:0000}", count);
atlas.Text = (str);
}
}
protected void SetEmitterPosition()
{
if (Emitter != null)
{
Emitter.Position = new CCPoint(WindowSize.Width / 2, WindowSize.Height / 2 - 30);
}
}
}
//------------------------------------------------------------------
//
// DemoFirework
//
//------------------------------------------------------------------
public class DemoFirework : ParticleDemo
{
public override void OnEnter()
{
base.OnEnter(); CCSize windowSize = Layer.VisibleBoundsWorldspace.Size;
Emitter = new CCParticleFireworks(MidWindowPoint);
Background.AddChild(Emitter, 10);
Emitter.Texture = CCTextureCache.SharedTextureCache.AddImage(TestResource.s_stars1);
SetEmitterPosition();
}
public override string Title
{
get { return "ParticleFireworks"; }
}
}
//------------------------------------------------------------------
//
// DemoFire
//
//------------------------------------------------------------------
public class DemoFire : ParticleDemo
{
public override void OnEnter()
{
base.OnEnter(); CCSize windowSize = Layer.VisibleBoundsWorldspace.Size;
CCPoint emitterPos = new CCPoint(windowSize.Width / 2, 100);
Emitter = new CCParticleFire(emitterPos);
Background.AddChild(Emitter, 10);
Emitter.Texture = CCTextureCache.SharedTextureCache.AddImage(TestResource.s_fire); //.pvr"];
SetEmitterPosition();
}
public override string Title
{
get
{
return "ParticleFire";
}
}
};
//------------------------------------------------------------------
//
// DemoSun
//
//------------------------------------------------------------------
public class DemoSun : ParticleDemo
{
public override void OnEnter()
{
base.OnEnter(); CCSize windowSize = Layer.VisibleBoundsWorldspace.Size;
Emitter = new CCParticleSun(MidWindowPoint);
Background.AddChild(Emitter, 10);
Emitter.Texture = CCTextureCache.SharedTextureCache.AddImage(TestResource.s_fire);
SetEmitterPosition();
}
public override string Title
{
get
{
return "ParticleSun";
}
}
}
//------------------------------------------------------------------
//
// DemoGalaxy
//
//------------------------------------------------------------------
public class DemoGalaxy : ParticleDemo
{
public override void OnEnter()
{
base.OnEnter(); CCSize windowSize = Layer.VisibleBoundsWorldspace.Size;
Emitter = new CCParticleGalaxy(MidWindowPoint);
Background.AddChild(Emitter, 10);
Emitter.Texture = CCTextureCache.SharedTextureCache.AddImage(TestResource.s_fire);
SetEmitterPosition();
}
public override string Title
{
get
{
return "ParticleGalaxy";
}
}
};
//------------------------------------------------------------------
//
// DemoFlower
//
//------------------------------------------------------------------
public class DemoFlower : ParticleDemo
{
public override void OnEnter()
{
base.OnEnter(); CCSize windowSize = Layer.VisibleBoundsWorldspace.Size;
Emitter = new CCParticleFlower(MidWindowPoint);
Background.AddChild(Emitter, 10);
Emitter.Texture = CCTextureCache.SharedTextureCache.AddImage(TestResource.s_stars1);
SetEmitterPosition();
}
public override string Title
{
get
{
return "ParticleFlower";
}
}
};
//------------------------------------------------------------------
//
// DemoBigFlower
//
//------------------------------------------------------------------
public class DemoBigFlower : ParticleDemo
{
public override void OnEnter()
{
base.OnEnter(); CCSize windowSize = Layer.VisibleBoundsWorldspace.Size;
Emitter = new CCParticleSystemQuad(50);
//Emitter.autorelease();
Background.AddChild(Emitter, 10);
////Emitter.release(); // win32 : use this line or remove this line and use autorelease()
Emitter.Texture = CCTextureCache.SharedTextureCache.AddImage(TestResource.s_stars1);
Emitter.Duration = -1;
// gravity
Emitter.Gravity = (new CCPoint(0, 0));
// angle
Emitter.Angle = 90;
Emitter.AngleVar = 360;
// speed of particles
Emitter.Speed = (160);
Emitter.SpeedVar = (20);
// radial
Emitter.RadialAccel = (-120);
Emitter.RadialAccelVar = (0);
// tagential
Emitter.TangentialAccel = (30);
Emitter.TangentialAccelVar = (0);
// emitter position
Emitter.Position = new CCPoint(160, 240);
Emitter.PositionVar = new CCPoint(0, 0);
// life of particles
Emitter.Life = 4;
Emitter.LifeVar = 1;
// spin of particles
Emitter.StartSpin = 0;
Emitter.StartSizeVar = 0;
Emitter.EndSpin = 0;
Emitter.EndSpinVar = 0;
// color of particles
var startColor = new CCColor4F(0.5f, 0.5f, 0.5f, 1.0f);
Emitter.StartColor = startColor;
var startColorVar = new CCColor4F(0.5f, 0.5f, 0.5f, 1.0f);
Emitter.StartColorVar = startColorVar;
var endColor = new CCColor4F(0.1f, 0.1f, 0.1f, 0.2f);
Emitter.EndColor = endColor;
var endColorVar = new CCColor4F(0.1f, 0.1f, 0.1f, 0.2f);
Emitter.EndColorVar = endColorVar;
// size, in pixels
Emitter.StartSize = 80.0f;
Emitter.StartSizeVar = 40.0f;
Emitter.EndSize = CCParticleSystem.ParticleStartSizeEqualToEndSize;
// emits per second
Emitter.EmissionRate = Emitter.TotalParticles / Emitter.Life;
// additive
Emitter.BlendAdditive = true;
SetEmitterPosition();
}
public override string Title
{
get
{
return "ParticleBigFlower";
}
}
};
//------------------------------------------------------------------
//
// DemoRotFlower
//
//------------------------------------------------------------------
public class DemoRotFlower : ParticleDemo
{
public override void OnEnter()
{
base.OnEnter(); CCSize windowSize = Layer.VisibleBoundsWorldspace.Size;
Emitter = new CCParticleSystemQuad(300);
//Emitter.autorelease();
Background.AddChild(Emitter, 10);
////Emitter.release(); // win32 : Remove this line
Emitter.Texture = CCTextureCache.SharedTextureCache.AddImage(TestResource.s_stars2);
// duration
Emitter.Duration = -1;
// gravity
Emitter.Gravity = (new CCPoint(0, 0));
// angle
Emitter.Angle = 90;
Emitter.AngleVar = 360;
// speed of particles
Emitter.Speed = (160);
Emitter.SpeedVar = (20);
// radial
Emitter.RadialAccel = (-120);
Emitter.RadialAccelVar = (0);
// tagential
Emitter.TangentialAccel = (30);
Emitter.TangentialAccelVar = (0);
// emitter position
Emitter.Position = new CCPoint(160, 240);
Emitter.PositionVar = new CCPoint(0, 0);
// life of particles
Emitter.Life = 3;
Emitter.LifeVar = 1;
// spin of particles
Emitter.StartSpin = 0;
Emitter.StartSpinVar = 0;
Emitter.EndSpin = 0;
Emitter.EndSpinVar = 2000;
// color of particles
var startColor = new CCColor4F(0.5f, 0.5f, 0.5f, 1.0f);
Emitter.StartColor = startColor;
var startColorVar = new CCColor4F(0.5f, 0.5f, 0.5f, 1.0f);
Emitter.StartColorVar = startColorVar;
var endColor = new CCColor4F(0.1f, 0.1f, 0.1f, 0.2f);
Emitter.EndColor = endColor;
var endColorVar = new CCColor4F(0.1f, 0.1f, 0.1f, 0.2f);
Emitter.EndColorVar = endColorVar;
// size, in pixels
Emitter.StartSize = 30.0f;
Emitter.StartSizeVar = 00.0f;
Emitter.EndSize = CCParticleSystem.ParticleStartSizeEqualToEndSize;
// emits per second
Emitter.EmissionRate = Emitter.TotalParticles / Emitter.Life;
// additive
Emitter.BlendAdditive = false;
SetEmitterPosition();
}
public override string Title
{
get
{
return "ParticleRotFlower";
}
}
};
public class DemoMeteor : ParticleDemo
{
public override void OnEnter()
{
base.OnEnter(); CCSize windowSize = Layer.VisibleBoundsWorldspace.Size;
Emitter = new CCParticleMeteor(MidWindowPoint);
Background.AddChild(Emitter, 10);
Emitter.Texture = CCTextureCache.SharedTextureCache.AddImage(TestResource.s_fire);
SetEmitterPosition();
}
public override string Title
{
get
{
return "ParticleMeteor";
}
}
};
public class DemoSpiral : ParticleDemo
{
public override void OnEnter()
{
base.OnEnter(); CCSize windowSize = Layer.VisibleBoundsWorldspace.Size;
Emitter = new CCParticleSpiral(MidWindowPoint);
Background.AddChild(Emitter, 10);
Emitter.Texture = CCTextureCache.SharedTextureCache.AddImage(TestResource.s_fire);
SetEmitterPosition();
}
public override string Title
{
get
{
return "ParticleSpiral";
}
}
};
public class DemoExplosion : ParticleDemo
{
public override void OnEnter()
{
base.OnEnter(); CCSize windowSize = Layer.VisibleBoundsWorldspace.Size;
Emitter = new CCParticleExplosion(MidWindowPoint);
Background.AddChild(Emitter, 10);
Emitter.Texture = CCTextureCache.SharedTextureCache.AddImage(TestResource.s_stars1);
Emitter.AutoRemoveOnFinish = true;
SetEmitterPosition();
}
public override string Title
{
get
{
return "ParticleExplosion";
}
}
};
public class DemoSmoke : ParticleDemo
{
public override void OnEnter()
{
base.OnEnter(); CCSize windowSize = Layer.VisibleBoundsWorldspace.Size;
Emitter = new CCParticleSmoke(new CCPoint(windowSize.Width / 2.0f, 0));
Background.AddChild(Emitter, 10);
Emitter.Texture = CCTextureCache.SharedTextureCache.AddImage(TestResource.s_fire);
CCPoint p = Emitter.Position;
Emitter.Position = new CCPoint(p.X, 100);
SetEmitterPosition();
}
public override string Title
{
get
{
return "ParticleSmoke";
}
}
};
public class DemoSnow : ParticleDemo
{
public override void OnEnter()
{
base.OnEnter(); CCSize windowSize = Layer.VisibleBoundsWorldspace.Size;
Emitter = new CCParticleSnow(new CCPoint(windowSize.Width / 2, windowSize.Height + 10));
Background.AddChild(Emitter, 10);
CCPoint p = Emitter.Position;
Emitter.Position = new CCPoint(p.X, p.Y - 110);
Emitter.Life = 3;
Emitter.LifeVar = 1;
// gravity
Emitter.Gravity = (new CCPoint(0, -10));
// speed of particles
Emitter.Speed = (130);
Emitter.SpeedVar = (30);
var startColor = Emitter.StartColor;
startColor.R = 0.9f;
startColor.G = 0.9f;
startColor.B = 0.9f;
Emitter.StartColor = startColor;
var startColorVar = Emitter.StartColorVar;
startColorVar.B = 0.1f;
Emitter.StartColorVar = startColorVar;
Emitter.EmissionRate = Emitter.TotalParticles / Emitter.Life;
Emitter.Texture = CCTextureCache.SharedTextureCache.AddImage(TestResource.s_snow);
SetEmitterPosition();
}
public override string Title
{
get
{
return "ParticleSnow";
}
}
};
public class DemoRain : ParticleDemo
{
public override void OnEnter()
{
base.OnEnter(); CCSize windowSize = Layer.VisibleBoundsWorldspace.Size;
Emitter = new CCParticleRain(new CCPoint (windowSize.Width / 2.0f, windowSize.Height));
Background.AddChild(Emitter, 10);
CCPoint p = Emitter.Position;
Emitter.Position = new CCPoint(p.X, p.Y - 100);
Emitter.Life = 4;
Emitter.Texture = CCTextureCache.SharedTextureCache.AddImage(TestResource.s_fire);
}
public override string Title
{
get
{
return "ParticleRain";
}
}
};
// todo: CCParticleSystemPoint::draw() hasn't been implemented.
public class DemoModernArt : ParticleDemo
{
public override void OnEnter()
{
base.OnEnter();
CCSize windowSize = Layer.VisibleBoundsWorldspace.Size;
Emitter = new CCParticleSystemQuad(1000);
Background.AddChild(Emitter, 10);
CCSize s = windowSize;
// duration
Emitter.Duration = -1;
// gravity
Emitter.Gravity = (new CCPoint(0, 0));
// angle
Emitter.Angle = 0;
Emitter.AngleVar = 360;
// radial
Emitter.RadialAccel = (70);
Emitter.RadialAccelVar = (10);
// tagential
Emitter.TangentialAccel = (80);
Emitter.TangentialAccelVar = (0);
// speed of particles
Emitter.Speed = (50);
Emitter.SpeedVar = (10);
// emitter position
Emitter.Position = new CCPoint(s.Width / 2, s.Height / 2);
Emitter.PositionVar = new CCPoint(0, 0);
// life of particles
Emitter.Life = 2.0f;
Emitter.LifeVar = 0.3f;
// emits per frame
Emitter.EmissionRate = Emitter.TotalParticles / Emitter.Life;
// color of particles
var startColor = new CCColor4F(0.5f, 0.5f, 0.5f, 1.0f);
Emitter.StartColor = startColor;
var startColorVar = new CCColor4F(0.5f, 0.5f, 0.5f, 1.0f);
Emitter.StartColorVar = startColorVar;
var endColor = new CCColor4F(0.1f, 0.1f, 0.1f, 0.2f);
Emitter.EndColor = endColor;
var endColorVar = new CCColor4F(0.1f, 0.1f, 0.1f, 0.2f);
Emitter.EndColorVar = endColorVar;
// size, in pixels
Emitter.StartSize = 1.0f;
Emitter.StartSizeVar = 1.0f;
Emitter.EndSize = 32.0f;
Emitter.EndSizeVar = 8.0f;
// texture
Emitter.Texture = CCTextureCache.SharedTextureCache.AddImage(TestResource.s_fire);
// additive
Emitter.BlendAdditive = false;
SetEmitterPosition();
}
public override string Title
{
get
{
return "Varying size";
}
}
};
public class DemoRing : ParticleDemo
{
public override void OnEnter()
{
base.OnEnter(); CCSize windowSize = Layer.VisibleBoundsWorldspace.Size;
Emitter = new CCParticleFlower(MidWindowPoint);
Background.AddChild(Emitter, 10);
Emitter.Texture = CCTextureCache.SharedTextureCache.AddImage(TestResource.s_stars1);
Emitter.LifeVar = 0;
Emitter.Life = 10;
Emitter.Speed = (100);
Emitter.SpeedVar = (0);
Emitter.EmissionRate = 10000;
SetEmitterPosition();
}
public override string Title
{
get
{
return "Ring Demo";
}
}
};
public class ParallaxParticle : ParticleDemo
{
public override void OnEnter()
{
base.OnEnter(); CCSize windowSize = Layer.VisibleBoundsWorldspace.Size;
Background.Parent.RemoveChild(Background, true);
Background = null;
CCParallaxNode p = new CCParallaxNode();
AddChild(p, 5);
CCSprite p1 = new CCSprite(TestResource.s_back3);
CCSprite p2 = new CCSprite(TestResource.s_back3);
p.AddChild(p1, 1, new CCPoint(0.5f, 1), new CCPoint(0, 250));
p.AddChild(p2, 2, new CCPoint(1.5f, 1), new CCPoint(0, 50));
Emitter = new CCParticleFlower(MidWindowPoint);
Emitter.Texture = CCTextureCache.SharedTextureCache.AddImage(TestResource.s_fire);
p1.AddChild(Emitter, 10);
Emitter.Position = new CCPoint(250, 200);
CCParticleSun par = new CCParticleSun(MidWindowPoint);
p2.AddChild(par, 10);
par.Texture = CCTextureCache.SharedTextureCache.AddImage(TestResource.s_fire);
CCFiniteTimeAction move = new CCMoveBy (4, new CCPoint(300, 0));
CCFiniteTimeAction move_back = move.Reverse();
CCFiniteTimeAction seq = new CCSequence(move, move_back);
p.RunAction(new CCRepeatForever ((CCFiniteTimeAction) seq));
}
public override string Title
{
get
{
return "Parallax + Particles";
}
}
};
public class DemoParticleFromFile : ParticleDemo
{
readonly string title;
static Dictionary<string, CCParticleSystemConfig> particleConfigManager;
public DemoParticleFromFile()
{
if (particleConfigManager == null)
particleConfigManager = new Dictionary<string, CCParticleSystemConfig> ();
}
public DemoParticleFromFile(string file) : base()
{
if (particleConfigManager == null)
particleConfigManager = new Dictionary<string, CCParticleSystemConfig> ();
title = file;
}
public override void OnEnter()
{
base.OnEnter(); CCSize windowSize = Layer.VisibleBoundsWorldspace.Size;
Color = new CCColor3B(0, 0, 0);
RemoveChild(Background, true);
Background = null;
string filename = "Particles/" + title;
CCParticleSystemConfig config;
if (particleConfigManager.ContainsKey (filename))
config = particleConfigManager [filename];
else
{
config = new CCParticleSystemConfig(filename, null);
particleConfigManager.Add (filename, config);
}
Emitter = new CCParticleSystemQuad(config);
AddChild(Emitter, 10);
Emitter.BlendAdditive = true;
SetEmitterPosition();
}
public override string Title
{
get
{
if (null != title)
{
return title;
}
else
{
return "ParticleFromFile";
}
}
}
};
public class RadiusMode1 : ParticleDemo
{
public override void OnEnter()
{
base.OnEnter();
CCSize windowSize = Layer.VisibleBoundsWorldspace.Size;
Color = new CCColor3B(0, 0, 0);
RemoveChild(Background, true);
Background = null;
Emitter = new CCParticleSystemQuad(200, CCEmitterMode.Radius);
AddChild(Emitter, 10);
Emitter.Texture = CCTextureCache.SharedTextureCache.AddImage("Images/stars-grayscale");
// duration
Emitter.Duration = CCParticleSystem.ParticleDurationInfinity;
// radius mode: start and end radius in pixels
Emitter.StartRadius = (0);
Emitter.StartRadiusVar = (0);
Emitter.EndRadius = (160);
Emitter.EndRadiusVar = (0);
// radius mode: degrees per second
Emitter.RotatePerSecond = (180);
Emitter.RotatePerSecondVar = (0);
// angle
Emitter.Angle = 90;
Emitter.AngleVar = 0;
// emitter position
CCSize size = WindowSize;
Emitter.Position = new CCPoint(size.Width / 2, size.Height / 2);
Emitter.PositionVar = new CCPoint(0, 0);
// life of particles
Emitter.Life = 5;
Emitter.LifeVar = 0;
// spin of particles
Emitter.StartSpin = 0;
Emitter.StartSpinVar = 0;
Emitter.EndSpin = 0;
Emitter.EndSpinVar = 0;
// color of particles
var startColor = new CCColor4F(0.5f, 0.5f, 0.5f, 1.0f);
Emitter.StartColor = startColor;
var startColorVar = new CCColor4F(0.5f, 0.5f, 0.5f, 1.0f);
Emitter.StartColorVar = startColorVar;
var endColor = new CCColor4F(0.1f, 0.1f, 0.1f, 0.2f);
Emitter.EndColor = endColor;
var endColorVar = new CCColor4F(0.1f, 0.1f, 0.1f, 0.2f);
Emitter.EndColorVar = endColorVar;
// size, in pixels
Emitter.StartSize = 32;
Emitter.StartSizeVar = 0;
Emitter.EndSize = CCParticleSystem.ParticleStartSizeEqualToEndSize;
// emits per second
Emitter.EmissionRate = Emitter.TotalParticles / Emitter.Life;
// additive
Emitter.BlendAdditive = false;
}
public override string Title
{
get
{
return "Radius Mode: Spiral";
}
}
};
public class RadiusMode2 : ParticleDemo
{
public override void OnEnter()
{
base.OnEnter(); CCSize windowSize = Layer.VisibleBoundsWorldspace.Size;
Color = new CCColor3B(0, 0, 0);
RemoveChild(Background, true);
Background = null;
Emitter = new CCParticleSystemQuad(200, CCEmitterMode.Radius);
AddChild(Emitter, 10);
Emitter.Texture = CCTextureCache.SharedTextureCache.AddImage("Images/stars-grayscale");
// duration
Emitter.Duration = CCParticleSystem.ParticleDurationInfinity;
// radius mode: start and end radius in pixels
Emitter.StartRadius = (100);
Emitter.StartRadiusVar = (0);
Emitter.EndRadius = (CCParticleSystem.ParticleStartRadiusEqualToEndRadius);
Emitter.EndRadiusVar = (0);
// radius mode: degrees per second
Emitter.RotatePerSecond = (45);
Emitter.RotatePerSecondVar = (0);
// angle
Emitter.Angle = 90;
Emitter.AngleVar = 0;
// emitter position
CCSize size = WindowSize;
Emitter.Position = new CCPoint(size.Width / 2, size.Height / 2);
Emitter.PositionVar = new CCPoint(0, 0);
// life of particles
Emitter.Life = 4;
Emitter.LifeVar = 0;
// spin of particles
Emitter.StartSpin = 0;
Emitter.StartSpinVar = 0;
Emitter.EndSpin = 0;
Emitter.EndSpinVar = 0;
// color of particles
var startColor = new CCColor4F(0.5f, 0.5f, 0.5f, 1.0f);
Emitter.StartColor = startColor;
var startColorVar = new CCColor4F(0.5f, 0.5f, 0.5f, 1.0f);
Emitter.StartColorVar = startColorVar;
var endColor = new CCColor4F(0.1f, 0.1f, 0.1f, 0.2f);
Emitter.EndColor = endColor;
var endColorVar = new CCColor4F(0.1f, 0.1f, 0.1f, 0.2f);
Emitter.EndColorVar = endColorVar;
// size, in pixels
Emitter.StartSize = 32;
Emitter.StartSizeVar = 0;
Emitter.EndSize = CCParticleSystem.ParticleStartSizeEqualToEndSize;
// emits per second
Emitter.EmissionRate = Emitter.TotalParticles / Emitter.Life;
// additive
Emitter.BlendAdditive = false;
}
public override string Title
{
get
{
return "Radius Mode: Semi Circle";
}
}
}
public class Issue704 : ParticleDemo
{
public override void OnEnter()
{
base.OnEnter(); CCSize windowSize = Layer.VisibleBoundsWorldspace.Size;
Color = new CCColor3B(0, 0, 0);
RemoveChild(Background, true);
Background = null;
Emitter = new CCParticleSystemQuad(100, CCEmitterMode.Radius);
AddChild(Emitter, 10);
Emitter.Texture = CCTextureCache.SharedTextureCache.AddImage("Images/fire");
// duration
Emitter.Duration = CCParticleSystem.ParticleDurationInfinity;
// radius mode: start and end radius in pixels
Emitter.StartRadius = (50);
Emitter.StartRadiusVar = (0);
Emitter.EndRadius = (CCParticleSystem.ParticleStartRadiusEqualToEndRadius);
Emitter.EndRadiusVar = (0);
// radius mode: degrees per second
Emitter.RotatePerSecond = (0);
Emitter.RotatePerSecondVar = (0);
// angle
Emitter.Angle = 90;
Emitter.AngleVar = 0;
// emitter position
CCSize size = WindowSize;
Emitter.Position = new CCPoint(size.Width / 2, size.Height / 2);
Emitter.PositionVar = new CCPoint(0, 0);
// life of particles
Emitter.Life = 5;
Emitter.LifeVar = 0;
// spin of particles
Emitter.StartSpin = 0;
Emitter.StartSpinVar = 0;
Emitter.EndSpin = 0;
Emitter.EndSpinVar = 0;
// color of particles
var startColor = new CCColor4F(0.5f, 0.5f, 0.5f, 1.0f);
Emitter.StartColor = startColor;
var startColorVar = new CCColor4F(0.5f, 0.5f, 0.5f, 1.0f);
Emitter.StartColorVar = startColorVar;
var endColor = new CCColor4F(0.1f, 0.1f, 0.1f, 0.2f);
Emitter.EndColor = endColor;
var endColorVar = new CCColor4F(0.1f, 0.1f, 0.1f, 0.2f);
Emitter.EndColorVar = endColorVar;
// size, in pixels
Emitter.StartSize = 16;
Emitter.StartSizeVar = 0;
Emitter.EndSize = CCParticleSystem.ParticleStartSizeEqualToEndSize;
// emits per second
Emitter.EmissionRate = Emitter.TotalParticles / Emitter.Life;
// additive
Emitter.BlendAdditive = false;
CCRotateBy rot = new CCRotateBy (16, 360);
Emitter.RunAction(new CCRepeatForever (rot));
}
public override string Title
{
get
{
return "Issue 704. Free + Rot";
}
}
public override string Subtitle
{
get
{
return "Emitted particles should not rotate";
}
}
}
public class Issue870 : ParticleDemo
{
int index;
public override void OnEnter()
{
base.OnEnter(); CCSize windowSize = Layer.VisibleBoundsWorldspace.Size;
Color = new CCColor3B(0, 0, 0);
RemoveChild(Background, true);
Background = null;
var system = new CCParticleSystemQuad("Particles/SpinningPeas");
system.Texture = (CCTextureCache.SharedTextureCache.AddImage ("Images/particles"));
system.TextureRect = new CCRect(0, 0, 32, 32);
AddChild(system, 10);
Emitter = system;
index = 0;
Schedule(UpdateQuads, 2.0f);
}
void UpdateQuads(float dt)
{
index = (index + 1) % 4;
var rect = new CCRect(index * 32, 0, 32, 32);
var system = (CCParticleSystemQuad) Emitter;
system.Texture = Emitter.Texture;
system.TextureRect = rect;
}
public override string Title
{
get
{
return "Issue 870. SubRect";
}
}
public override string Subtitle
{
get
{
return "Every 2 seconds the particle should change";
}
}
}
public class LoadingLabel : CCLabelTtf
{
static CCScaleBy scale = new CCScaleBy(0.3f, 2);
static CCSequence textThrob = new CCSequence(scale, scale.Reverse());
static CCSequence delayedShow = new CCSequence(new CCDelayTime (2.0f), new CCShow ());
public LoadingLabel() : base ("Loading...", "Marker Felt", 32)
{
Visible = false;
}
protected override void AddedToScene()
{
base.AddedToScene();
Position = Layer.VisibleBoundsWorldspace.Center;
RunActions (delayedShow);
RepeatForever (textThrob);
}
}
public class ParticleReorder : ParticleDemo
{
int order;
LoadingLabel label;
public ParticleReorder ()
{
order = 0;
Color = CCColor3B.Black;
RemoveChild(Background, true);
Background = null;
label = new LoadingLabel();
AddChild(label, 10);
}
public override void OnEnter()
{
base.OnEnter(); CCSize windowSize = Layer.VisibleBoundsWorldspace.Size;
label.Position = windowSize.Center;
ScheduleOnce(LoadParticleSystem, 0.0f);
}
void LoadParticleSystem(float dt)
{
CCParticleSystemCache.SharedParticleSystemCache.AddParticleSystemAsync("Particles/SmallSun", ParticleSystemLoaded);
}
void ParticleSystemLoaded(CCParticleSystemConfig psConfig)
{
label.RemoveFromParent(true);
CCParticleSystemQuad ignore = new CCParticleSystemQuad (psConfig);
//ignore.TotalParticles = 200;
CCNode parent1 = new CCNode ();
CCParticleBatchNode parent2 = new CCParticleBatchNode (ignore.Texture);
parent1.ContentSize = new CCSize (300.0f, 300.0f);
for (int i = 0; i < 2; i++) {
CCNode parent = (i == 0 ? parent1 : parent2);
CCParticleSystemQuad emitter1 = new CCParticleSystemQuad (psConfig);
//emitter1.TotalParticles = 200;
emitter1.StartColor = (new CCColor4F (1, 0, 0, 1));
emitter1.BlendAdditive = (false);
CCParticleSystemQuad emitter2 = new CCParticleSystemQuad (psConfig);
//emitter2.TotalParticles = 200;
emitter2.StartColor = (new CCColor4F (0, 1, 0, 1));
emitter2.BlendAdditive = (false);
CCParticleSystemQuad emitter3 = new CCParticleSystemQuad (psConfig);
//emitter3.TotalParticles = 200;
emitter3.StartColor = (new CCColor4F (0, 0, 1, 1));
emitter3.BlendAdditive = (false);
CCSize s = Layer.VisibleBoundsWorldspace.Size;
int neg = (i == 0 ? 1 : -1);
emitter1.Position = (new CCPoint (s.Width / 2 - 30, s.Height / 2 + 60 * neg));
emitter2.Position = (new CCPoint (s.Width / 2, s.Height / 2 + 60 * neg));
emitter3.Position = (new CCPoint (s.Width / 2 + 30, s.Height / 2 + 60 * neg));
parent.AddChild (emitter1, 0, 1);
parent.AddChild (emitter2, 0, 2);
parent.AddChild (emitter3, 0, 3);
AddChild (parent, 10, 1000 + i);
}
Schedule(ReorderParticles, 1.0f);
}
public override string Title
{
get
{
return "Reordering particles";
}
}
public override string Subtitle
{
get
{
return "Reordering particles with and without batches batches";
}
}
void ReorderParticles(float dt)
{
for (int i = 0; i < 2; i++)
{
CCNode parent = GetChildByTag(1000 + i);
CCNode child1 = parent.GetChildByTag(1);
CCNode child2 = parent.GetChildByTag(2);
CCNode child3 = parent.GetChildByTag(3);
if (order % 3 == 0)
{
parent.ReorderChild(child1, 1);
parent.ReorderChild(child2, 2);
parent.ReorderChild(child3, 3);
}
else if (order % 3 == 1)
{
parent.ReorderChild(child1, 3);
parent.ReorderChild(child2, 1);
parent.ReorderChild(child3, 2);
}
else if (order % 3 == 2)
{
parent.ReorderChild(child1, 2);
parent.ReorderChild(child2, 3);
parent.ReorderChild(child3, 1);
}
}
order++;
}
}
public class ParticleBatchHybrid : ParticleDemo
{
CCNode parent1;
CCNode parent2;
const int NODE_ZORDER = 10;
public override void OnEnter()
{
base.OnEnter(); CCSize windowSize = Layer.VisibleBoundsWorldspace.Size;
Color = CCColor3B.Black;
RemoveChild(Background, true);
Background = null;
Emitter = new CCParticleSystemQuad("Particles/LavaFlow");
Emitter.Texture = CCTextureCache.SharedTextureCache.AddImage("Images/fire");
CCParticleBatchNode batch = new CCParticleBatchNode(Emitter.Texture);
batch.AddChild(Emitter);
AddChild(batch, NODE_ZORDER);
Schedule(SwitchRender, 2.0f);
CCLayer node = new CCLayer();
AddChild(node, NODE_ZORDER);
parent1 = batch;
parent2 = node;
}
void SwitchRender(float dt)
{
bool usingBatch = (Emitter.BatchNode != null);
Emitter.RemoveFromParent(false);
CCNode newParent = (usingBatch ? parent2 : parent1);
newParent.AddChild(Emitter);
CCLog.Log("Particle: Using new parent: {0}", usingBatch ? "CCNode" : "CCParticleBatchNode");
}
public override string Title
{
get
{
return "Paticle Batch";
}
}
public override string Subtitle
{
get
{
return "Hybrid: batched and non batched every 2 seconds";
}
}
}
public class ParticleBatchMultipleEmitters : ParticleDemo
{
public override void OnEnter()
{
base.OnEnter();
CCSize windowSize = Layer.VisibleBoundsWorldspace.Size;
Color = CCColor3B.Black;
RemoveChild(Background, true);
Background = null;
CCParticleSystemQuad emitter1 = new CCParticleSystemQuad("Particles/LavaFlow");
emitter1.StartColor = (new CCColor4F(1, 0, 0, 1));
CCParticleSystemQuad emitter2 = new CCParticleSystemQuad("Particles/LavaFlow");
emitter2.StartColor = (new CCColor4F(0, 1, 0, 1));
CCParticleSystemQuad emitter3 = new CCParticleSystemQuad("Particles/LavaFlow");
emitter3.StartColor = (new CCColor4F(0, 0, 1, 1));
CCSize s = WindowSize;
emitter1.Position = (new CCPoint(s.Width / 1.25f, s.Height / 1.25f));
emitter2.Position = (new CCPoint(s.Width / 2, s.Height / 2));
emitter3.Position = (new CCPoint(s.Width / 4, s.Height / 4));
emitter1.Texture = CCTextureCache.SharedTextureCache.AddImage("Images/fire");
emitter2.Texture = emitter1.Texture;
emitter3.Texture = emitter1.Texture;
CCParticleBatchNode batch = new CCParticleBatchNode(emitter1.Texture);
batch.AddChild(emitter1, 0);
batch.AddChild(emitter2, 0);
batch.AddChild(emitter3, 0);
AddChild(batch, 10);
}
public override string Title
{
get
{
return "Paticle Batch";
}
}
public override string Subtitle
{
get
{
return "Multiple emitters. One Batch";
}
}
}
public class RainbowEffect : CCParticleSystemQuad
{
public bool init()
{
return true;
}
public RainbowEffect(int numOfParticles) : base(numOfParticles)
{
// additive
BlendAdditive = (false);
// duration
Duration = (ParticleDurationInfinity);;
// Gravity Mode: gravity
Gravity = (new CCPoint(0, 0));
// Gravity mode: radial acceleration
RadialAccel = (0);
RadialAccelVar = (0);
// Gravity mode: speed of particles
Speed = (120);
SpeedVar = (0);
// angle
Angle = (180);
AngleVar = (0);
// life of particles
Life = (0.5f);
LifeVar = (0);
// size, in pixels
StartSize = (25.0f);
StartSizeVar = (0);
EndSize = (ParticleStartSizeEqualToEndSize);
// emits per seconds
EmissionRate = (TotalParticles / Life);
// color of particles
StartColor = (new CCColor4F(50, 50, 50, 50));
EndColor = (new CCColor4F(0, 0, 0, 0));
StartColorVar = new CCColor4F();
EndColorVar = new CCColor4F();
Texture = (CCTextureCache.SharedTextureCache.AddImage("Images/particles"));
}
public override void OnEnter()
{
base.OnEnter(); CCSize windowSize = Layer.VisibleBoundsWorldspace.Size;
// emitter position
Position = windowSize.Center;
PositionVar = (CCPoint.Zero);
}
public override void Update(float dt)
{
EmitCounter = 0;
base.Update(dt);
}
}
public class Issue1201 : ParticleDemo
{
public override void OnEnter()
{
base.OnEnter(); CCSize windowSize = Layer.VisibleBoundsWorldspace.Size;
Color = CCColor3B.Black;
RemoveChild(Background, true);
Background = null;
var particle = new RainbowEffect(50);
AddChild(particle);
particle.Position = (MidWindowPoint);
Emitter = particle;
}
public override string Title
{
get
{
return "Issue 1201. Unfinished";
}
}
public override string Subtitle
{
get
{
return "Unfinished test. Ignore it";
}
}
}
public class MultipleParticleSystems : ParticleDemo
{
public override void OnEnter()
{
base.OnEnter(); CCSize windowSize = Layer.VisibleBoundsWorldspace.Size;
Color = CCColor3B.Black;
RemoveChild(Background, true);
Background = null;
CCTextureCache.SharedTextureCache.AddImage("Images/particles");
for (int i = 0; i < 5; i++)
{
CCParticleSystemQuad particleSystem = new CCParticleSystemQuad("Particles/SpinningPeas");
particleSystem.Position = (new CCPoint(i * 50, i * 50));
particleSystem.PositionType = CCPositionType.Grouped;
AddChild(particleSystem);
}
Emitter = null;
}
public override string Title
{
get
{
return "Multiple particle systems";
}
}
public override string Subtitle
{
get
{
return "v1.1 test: FPS should be lower than next test";
}
}
}
public class MultipleParticleSystemsBatched : ParticleDemo
{
public override void OnEnter()
{
base.OnEnter(); CCSize windowSize = Layer.VisibleBoundsWorldspace.Size;
Color = CCColor3B.Black;
RemoveChild(Background, true);
Background = null;
CCParticleBatchNode batchNode = new CCParticleBatchNode("Images/fire", 3000);
AddChild(batchNode, 1, 2);
for (int i = 0; i < 5; i++)
{
CCParticleSystemQuad particleSystem = new CCParticleSystemQuad("Particles/SpinningPeas");
particleSystem.PositionType = CCPositionType.Grouped;
particleSystem.Position = (new CCPoint(i * 50, i * 50));
particleSystem.Texture = batchNode.Texture;
batchNode.AddChild(particleSystem);
}
Emitter = null;
}
public override string Title
{
get
{
return "Multiple particle systems";
}
}
public override string Subtitle
{
get
{
return "v1.1 test: FPS should be lower than next test";
}
}
}
public class AddAndDeleteParticleSystems : ParticleDemo
{
CCParticleBatchNode batchNode;
public override void OnEnter()
{
base.OnEnter(); CCSize windowSize = Layer.VisibleBoundsWorldspace.Size;
Color = CCColor3B.Black;
RemoveChild(Background, true);
Background = null;
//adds the texture inside the plist to the texture cache
batchNode = new CCParticleBatchNode("Images/fire", 16000);
AddChild(batchNode, 1, 2);
for (int i = 0; i < 6; i++)
{
CCParticleSystemQuad particleSystem = new CCParticleSystemQuad("Particles/Spiral");
particleSystem.Texture = batchNode.Texture;
particleSystem.PositionType = CCPositionType.Grouped;
particleSystem.TotalParticles = (200);
particleSystem.Position = (new CCPoint(i * 15 + 100, i * 15 + 100));
int randZ = CCRandom.Next(100);
batchNode.AddChild(particleSystem, randZ, -1);
}
Schedule(RemoveSystem, 0.5f);
Emitter = null;
}
void RemoveSystem(float dt)
{
int nChildrenCount = batchNode.ChildrenCount;
if (nChildrenCount > 0)
{
CCLog.Log("remove random system");
int uRand = CCRandom.Next(nChildrenCount - 1);
batchNode.RemoveChild(batchNode.Children[uRand], true);
CCParticleSystemQuad particleSystem = new CCParticleSystemQuad("Particles/Spiral");
//add new
particleSystem.PositionType = CCPositionType.Grouped;
particleSystem.TotalParticles = (200);
particleSystem.Position = (new CCPoint(CCRandom.Next(300), CCRandom.Next(400)));
CCLog.Log("add a new system");
int randZ = CCRandom.Next(100);
particleSystem.Texture = batchNode.Texture;
batchNode.AddChild(particleSystem, randZ, -1);
}
}
public override string Title
{
get
{
return "Add and remove Particle System";
}
}
public override string Subtitle
{
get
{
return "v1.1 test: every 2 sec 1 system disappear, 1 appears";
}
}
}
public class ReorderParticleSystems : ParticleDemo
{
CCParticleBatchNode batchNode;
public override void OnEnter()
{
base.OnEnter(); CCSize windowSize = Layer.VisibleBoundsWorldspace.Size;
Color = CCColor3B.Black;
RemoveChild(Background, true);
Background = null;
batchNode = new CCParticleBatchNode("Images/stars-grayscale", 3000);
AddChild(batchNode, 1, 2);
for (int i = 0; i < 3; i++)
{
var particleSystem = new CCParticleSystemQuad(200, CCEmitterMode.Radius);
particleSystem.Texture = (batchNode.Texture);
// duration
particleSystem.Duration = CCParticleSystem.ParticleDurationInfinity;
// radius mode: 100 pixels from center
particleSystem.StartRadius = (100);
particleSystem.StartRadiusVar = (0);
particleSystem.EndRadius = (CCParticleSystem.ParticleStartRadiusEqualToEndRadius);
particleSystem.EndRadiusVar = (0); // not used when start == end
// radius mode: degrees per second
// 45 * 4 seconds of life = 180 degrees
particleSystem.RotatePerSecond = (45);
particleSystem.RotatePerSecondVar = (0);
// angle
particleSystem.Angle = (90);
particleSystem.AngleVar = (0);
// emitter position
particleSystem.PositionVar = (CCPoint.Zero);
// life of particles
particleSystem.Life = (4);
particleSystem.LifeVar = (0);
// spin of particles
particleSystem.StartSpin = (0);
particleSystem.StartSpinVar = (0);
particleSystem.EndSpin = (0);
particleSystem.EndSpinVar = (0);
// color of particles
var color = new float[3] {0, 0, 0};
color[i] = 1;
var startColor = new CCColor4F(color[0], color[1], color[2], 1.0f);
particleSystem.StartColor = (startColor);
var startColorVar = new CCColor4F(0, 0, 0, 0);
particleSystem.StartColorVar = (startColorVar);
CCColor4F endColor = startColor;
particleSystem.EndColor = (endColor);
CCColor4F endColorVar = startColorVar;
particleSystem.EndColorVar = (endColorVar);
// size, in pixels
particleSystem.StartSize = (32);
particleSystem.StartSizeVar = (0);
particleSystem.EndSize = CCParticleSystem.ParticleStartSizeEqualToEndSize;
// emits per second
particleSystem.EmissionRate = (particleSystem.TotalParticles / particleSystem.Life);
// additive
particleSystem.Position = (new CCPoint(i * 10 + 120, 200));
batchNode.AddChild(particleSystem);
particleSystem.PositionType = CCPositionType.Free;
}
Schedule(ReorderSystem, 2.0f);
Emitter = null;
}
void ReorderSystem(float dt)
{
var system = (CCParticleSystem) batchNode.Children[1];
batchNode.ReorderChild(system, system.ZOrder - 1);
}
public override string Title
{
get
{
return "reorder systems";
}
}
public override string Subtitle
{
get
{
return "changes every 2 seconds";
}
}
}
public class PremultipliedAlphaTest : ParticleDemo
{
public override void OnEnter()
{
base.OnEnter();
Color = CCColor3B.Black;
RemoveChild(Background, true);
Background = null;
Emitter = new CCParticleSystemQuad("Particles/BoilingFoam");
// Particle Designer "normal" blend func causes black halo on premul textures (ignores multiplication)
//this->emitter.blendFunc = (ccBlendFunc){ GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA };
// Cocos2d "normal" blend func for premul causes alpha to be ignored (oversaturates colors)
var tBlendFunc = new CCBlendFunc(CCOGLES.GL_ONE, CCOGLES.GL_ONE_MINUS_SRC_ALPHA);
Emitter.BlendFunc = tBlendFunc;
//Debug.Assert(Emitter.OpacityModifyRGB, "Particle texture does not have premultiplied alpha, test is useless");
// Toggle next line to see old behavior
// this->emitter.opacityModifyRGB = NO;
Emitter.StartColor = new CCColor4F(1, 1, 1, 1);
Emitter.EndColor = new CCColor4F(1, 1, 1, 0);
Emitter.StartColorVar = new CCColor4F(0, 0, 0, 0);
Emitter.EndColorVar = new CCColor4F(0, 0, 0, 0);
AddChild(Emitter, 10);
}
public override string Title
{
get
{
return "premultiplied alpha";
}
}
public override string Subtitle
{
get
{
return "no black halo, particles should fade out";
}
}
}
public class PremultipliedAlphaTest2 : ParticleDemo
{
public override void OnEnter()
{
base.OnEnter(); CCSize windowSize = Layer.VisibleBoundsWorldspace.Size;
Color = CCColor3B.Black;
RemoveChild(Background, true);
Background = null;
Emitter = new CCParticleSystemQuad("Particles/TestPremultipliedAlpha");
AddChild(Emitter, 10);
}
public override string Title
{
get
{
return "premultiplied alpha 2";
}
}
public override string Subtitle
{
get
{
return "Arrows should be faded";
}
}
}
}
| |
// 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 Xunit;
namespace System.Linq.Tests
{
public class TakeTests : EnumerableTests
{
private static IEnumerable<T> GuaranteeNotIList<T>(IEnumerable<T> source)
{
foreach (T element in source)
yield return element;
}
[Fact]
public void SameResultsRepeatCallsIntQuery()
{
var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 }
where x > Int32.MinValue
select x;
Assert.Equal(q.Take(9), q.Take(9));
}
[Fact]
public void SameResultsRepeatCallsIntQueryIList()
{
var q = (from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 }
where x > Int32.MinValue
select x).ToList();
Assert.Equal(q.Take(9), q.Take(9));
}
[Fact]
public void SameResultsRepeatCallsStringQuery()
{
var q = from x in new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", "SoS", String.Empty }
where !String.IsNullOrEmpty(x)
select x;
Assert.Equal(q.Take(7), q.Take(7));
}
[Fact]
public void SameResultsRepeatCallsStringQueryIList()
{
var q = (from x in new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", "SoS", String.Empty }
where !String.IsNullOrEmpty(x)
select x).ToList();
Assert.Equal(q.Take(7), q.Take(7));
}
[Fact]
public void SourceEmptyCountPositive()
{
int[] source = { };
Assert.Empty(source.Take(5));
}
[Fact]
public void SourceEmptyCountPositiveNotIList()
{
var source = NumberRangeGuaranteedNotCollectionType(0, 0);
Assert.Empty(source.Take(5));
}
[Fact]
public void SourceNonEmptyCountNegative()
{
int[] source = { 2, 5, 9, 1 };
Assert.Empty(source.Take(-5));
}
[Fact]
public void SourceNonEmptyCountNegativeNotIList()
{
var source = GuaranteeNotIList(new[] { 2, 5, 9, 1 });
Assert.Empty(source.Take(-5));
}
[Fact]
public void SourceNonEmptyCountZero()
{
int[] source = { 2, 5, 9, 1 };
Assert.Empty(source.Take(0));
}
[Fact]
public void SourceNonEmptyCountZeroNotIList()
{
var source = GuaranteeNotIList(new[] { 2, 5, 9, 1 });
Assert.Empty(source.Take(0));
}
[Fact]
public void SourceNonEmptyCountOne()
{
int[] source = { 2, 5, 9, 1 };
int[] expected = { 2 };
Assert.Equal(expected, source.Take(1));
}
[Fact]
public void SourceNonEmptyCountOneNotIList()
{
var source = GuaranteeNotIList(new[] { 2, 5, 9, 1 });
int[] expected = { 2 };
Assert.Equal(expected, source.Take(1));
}
[Fact]
public void SourceNonEmptyTakeAllExactly()
{
int[] source = { 2, 5, 9, 1 };
Assert.Equal(source, source.Take(source.Length));
}
[Fact]
public void SourceNonEmptyTakeAllExactlyNotIList()
{
var source = GuaranteeNotIList(new[] { 2, 5, 9, 1 });
Assert.Equal(source, source.Take(source.Count()));
}
[Fact]
public void SourceNonEmptyTakeAllButOne()
{
int[] source = { 2, 5, 9, 1 };
int[] expected = { 2, 5, 9 };
Assert.Equal(expected, source.Take(3));
}
[Fact]
public void RunOnce()
{
int[] source = { 2, 5, 9, 1 };
int[] expected = { 2, 5, 9 };
Assert.Equal(expected, source.RunOnce().Take(3));
}
[Fact]
public void SourceNonEmptyTakeAllButOneNotIList()
{
var source = GuaranteeNotIList(new[] { 2, 5, 9, 1 });
int[] expected = { 2, 5, 9 };
Assert.Equal(expected, source.Take(3));
}
[Fact]
public void SourceNonEmptyTakeExcessive()
{
int?[] source = { 2, 5, null, 9, 1 };
Assert.Equal(source, source.Take(source.Length + 1));
}
[Fact]
public void SourceNonEmptyTakeExcessiveNotIList()
{
var source = GuaranteeNotIList(new int?[] { 2, 5, null, 9, 1 });
Assert.Equal(source, source.Take(source.Count() + 1));
}
[Fact]
public void ThrowsOnNullSource()
{
int[] source = null;
AssertExtensions.Throws<ArgumentNullException>("source", () => source.Take(5));
}
[Fact]
public void ForcedToEnumeratorDoesntEnumerate()
{
var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).Take(2);
// Don't insist on this behaviour, but check it's correct if it happens
var en = iterator as IEnumerator<int>;
Assert.False(en != null && en.MoveNext());
}
[Fact]
public void Count()
{
Assert.Equal(2, NumberRangeGuaranteedNotCollectionType(0, 3).Take(2).Count());
Assert.Equal(2, new[] { 1, 2, 3 }.Take(2).Count());
Assert.Equal(0, NumberRangeGuaranteedNotCollectionType(0, 3).Take(0).Count());
}
[Fact]
public void ForcedToEnumeratorDoesntEnumerateIList()
{
var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).ToList().Take(2);
// Don't insist on this behaviour, but check it's correct if it happens
var en = iterator as IEnumerator<int>;
Assert.False(en != null && en.MoveNext());
}
[Fact]
public void FollowWithTake()
{
var source = new[] { 5, 6, 7, 8 };
var expected = new[] { 5, 6 };
Assert.Equal(expected, source.Take(5).Take(3).Take(2).Take(40));
}
[Fact]
public void FollowWithTakeNotIList()
{
var source = NumberRangeGuaranteedNotCollectionType(5, 4);
var expected = new[] { 5, 6 };
Assert.Equal(expected, source.Take(5).Take(3).Take(2));
}
[Fact]
public void FollowWithSkip()
{
var source = new[] { 1, 2, 3, 4, 5, 6 };
var expected = new[] { 3, 4, 5 };
Assert.Equal(expected, source.Take(5).Skip(2).Skip(-4));
}
[Fact]
public void FollowWithSkipNotIList()
{
var source = NumberRangeGuaranteedNotCollectionType(1, 6);
var expected = new[] { 3, 4, 5 };
Assert.Equal(expected, source.Take(5).Skip(2).Skip(-4));
}
[Fact]
public void ElementAt()
{
var source = new[] { 1, 2, 3, 4, 5, 6 };
var taken = source.Take(3);
Assert.Equal(1, taken.ElementAt(0));
Assert.Equal(3, taken.ElementAt(2));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => taken.ElementAt(-1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => taken.ElementAt(3));
}
[Fact]
public void ElementAtNotIList()
{
var source = GuaranteeNotIList(new[] { 1, 2, 3, 4, 5, 6 });
var taken = source.Take(3);
Assert.Equal(1, taken.ElementAt(0));
Assert.Equal(3, taken.ElementAt(2));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => taken.ElementAt(-1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => taken.ElementAt(3));
}
[Fact]
public void ElementAtOrDefault()
{
var source = new[] { 1, 2, 3, 4, 5, 6 };
var taken = source.Take(3);
Assert.Equal(1, taken.ElementAtOrDefault(0));
Assert.Equal(3, taken.ElementAtOrDefault(2));
Assert.Equal(0, taken.ElementAtOrDefault(-1));
Assert.Equal(0, taken.ElementAtOrDefault(3));
}
[Fact]
public void ElementAtOrDefaultNotIList()
{
var source = GuaranteeNotIList(new[] { 1, 2, 3, 4, 5, 6 });
var taken = source.Take(3);
Assert.Equal(1, taken.ElementAtOrDefault(0));
Assert.Equal(3, taken.ElementAtOrDefault(2));
Assert.Equal(0, taken.ElementAtOrDefault(-1));
Assert.Equal(0, taken.ElementAtOrDefault(3));
}
[Fact]
public void First()
{
var source = new[] { 1, 2, 3, 4, 5 };
Assert.Equal(1, source.Take(1).First());
Assert.Equal(1, source.Take(4).First());
Assert.Equal(1, source.Take(40).First());
Assert.Throws<InvalidOperationException>(() => source.Take(0).First());
Assert.Throws<InvalidOperationException>(() => source.Skip(5).Take(10).First());
}
[Fact]
public void FirstNotIList()
{
var source = GuaranteeNotIList(new[] { 1, 2, 3, 4, 5 });
Assert.Equal(1, source.Take(1).First());
Assert.Equal(1, source.Take(4).First());
Assert.Equal(1, source.Take(40).First());
Assert.Throws<InvalidOperationException>(() => source.Take(0).First());
Assert.Throws<InvalidOperationException>(() => source.Skip(5).Take(10).First());
}
[Fact]
public void FirstOrDefault()
{
var source = new[] { 1, 2, 3, 4, 5 };
Assert.Equal(1, source.Take(1).FirstOrDefault());
Assert.Equal(1, source.Take(4).FirstOrDefault());
Assert.Equal(1, source.Take(40).FirstOrDefault());
Assert.Equal(0, source.Take(0).FirstOrDefault());
Assert.Equal(0, source.Skip(5).Take(10).FirstOrDefault());
}
[Fact]
public void FirstOrDefaultNotIList()
{
var source = GuaranteeNotIList(new[] { 1, 2, 3, 4, 5 });
Assert.Equal(1, source.Take(1).FirstOrDefault());
Assert.Equal(1, source.Take(4).FirstOrDefault());
Assert.Equal(1, source.Take(40).FirstOrDefault());
Assert.Equal(0, source.Take(0).FirstOrDefault());
Assert.Equal(0, source.Skip(5).Take(10).FirstOrDefault());
}
[Fact]
public void Last()
{
var source = new[] { 1, 2, 3, 4, 5 };
Assert.Equal(1, source.Take(1).Last());
Assert.Equal(5, source.Take(5).Last());
Assert.Equal(5, source.Take(40).Last());
Assert.Throws<InvalidOperationException>(() => source.Take(0).Last());
Assert.Throws<InvalidOperationException>(() => Array.Empty<int>().Take(40).Last());
}
[Fact]
public void LastNotIList()
{
var source = GuaranteeNotIList(new[] { 1, 2, 3, 4, 5 });
Assert.Equal(1, source.Take(1).Last());
Assert.Equal(5, source.Take(5).Last());
Assert.Equal(5, source.Take(40).Last());
Assert.Throws<InvalidOperationException>(() => source.Take(0).Last());
Assert.Throws<InvalidOperationException>(() => GuaranteeNotIList(Array.Empty<int>()).Take(40).Last());
}
[Fact]
public void LastOrDefault()
{
var source = new[] { 1, 2, 3, 4, 5 };
Assert.Equal(1, source.Take(1).LastOrDefault());
Assert.Equal(5, source.Take(5).LastOrDefault());
Assert.Equal(5, source.Take(40).LastOrDefault());
Assert.Equal(0, source.Take(0).LastOrDefault());
Assert.Equal(0, Array.Empty<int>().Take(40).LastOrDefault());
}
[Fact]
public void LastOrDefaultNotIList()
{
var source = GuaranteeNotIList(new[] { 1, 2, 3, 4, 5 });
Assert.Equal(1, source.Take(1).LastOrDefault());
Assert.Equal(5, source.Take(5).LastOrDefault());
Assert.Equal(5, source.Take(40).LastOrDefault());
Assert.Equal(0, source.Take(0).LastOrDefault());
Assert.Equal(0, GuaranteeNotIList(Array.Empty<int>()).Take(40).LastOrDefault());
}
[Fact]
public void ToArray()
{
var source = new[] { 1, 2, 3, 4, 5 };
Assert.Equal(new[] { 1, 2, 3, 4, 5 }, source.Take(5).ToArray());
Assert.Equal(new[] { 1, 2, 3, 4, 5 }, source.Take(6).ToArray());
Assert.Equal(new[] { 1, 2, 3, 4, 5 }, source.Take(40).ToArray());
Assert.Equal(new[] { 1, 2, 3, 4 }, source.Take(4).ToArray());
Assert.Equal(1, source.Take(1).ToArray().Single());
Assert.Empty(source.Take(0).ToArray());
Assert.Empty(source.Take(-10).ToArray());
}
[Fact]
public void ToArrayNotList()
{
var source = GuaranteeNotIList(new[] { 1, 2, 3, 4, 5 });
Assert.Equal(new[] { 1, 2, 3, 4, 5 }, source.Take(5).ToArray());
Assert.Equal(new[] { 1, 2, 3, 4, 5 }, source.Take(6).ToArray());
Assert.Equal(new[] { 1, 2, 3, 4, 5 }, source.Take(40).ToArray());
Assert.Equal(new[] { 1, 2, 3, 4 }, source.Take(4).ToArray());
Assert.Equal(1, source.Take(1).ToArray().Single());
Assert.Empty(source.Take(0).ToArray());
Assert.Empty(source.Take(-10).ToArray());
}
[Fact]
public void ToList()
{
var source = new[] { 1, 2, 3, 4, 5 };
Assert.Equal(new[] { 1, 2, 3, 4, 5 }, source.Take(5).ToList());
Assert.Equal(new[] { 1, 2, 3, 4, 5 }, source.Take(6).ToList());
Assert.Equal(new[] { 1, 2, 3, 4, 5 }, source.Take(40).ToList());
Assert.Equal(new[] { 1, 2, 3, 4 }, source.Take(4).ToList());
Assert.Equal(1, source.Take(1).ToList().Single());
Assert.Empty(source.Take(0).ToList());
Assert.Empty(source.Take(-10).ToList());
}
[Fact]
public void ToListNotList()
{
var source = GuaranteeNotIList(new[] { 1, 2, 3, 4, 5 });
Assert.Equal(new[] { 1, 2, 3, 4, 5 }, source.Take(5).ToList());
Assert.Equal(new[] { 1, 2, 3, 4, 5 }, source.Take(6).ToList());
Assert.Equal(new[] { 1, 2, 3, 4, 5 }, source.Take(40).ToList());
Assert.Equal(new[] { 1, 2, 3, 4 }, source.Take(4).ToList());
Assert.Equal(1, source.Take(1).ToList().Single());
Assert.Empty(source.Take(0).ToList());
Assert.Empty(source.Take(-10).ToList());
}
[Fact]
public void TakeCanOnlyBeOneList()
{
var source = new[] { 2, 4, 6, 8, 10 };
Assert.Equal(new[] { 2 }, source.Take(1));
Assert.Equal(new[] { 4 }, source.Skip(1).Take(1));
Assert.Equal(new[] { 6 }, source.Take(3).Skip(2));
Assert.Equal(new[] { 2 }, source.Take(3).Take(1));
}
[Fact]
public void TakeCanOnlyBeOneNotList()
{
var source = GuaranteeNotIList(new[] { 2, 4, 6, 8, 10 });
Assert.Equal(new[] { 2 }, source.Take(1));
Assert.Equal(new[] { 4 }, source.Skip(1).Take(1));
Assert.Equal(new[] { 6 }, source.Take(3).Skip(2));
Assert.Equal(new[] { 2 }, source.Take(3).Take(1));
}
[Fact]
public void RepeatEnumerating()
{
var source = new[] { 1, 2, 3, 4, 5 };
var taken = source.Take(3);
Assert.Equal(taken, taken);
}
[Fact]
public void RepeatEnumeratingNotList()
{
var source = GuaranteeNotIList(new[] { 1, 2, 3, 4, 5 });
var taken = source.Take(3);
Assert.Equal(taken, taken);
}
[Theory]
[InlineData(1000)]
[InlineData(1000000)]
[InlineData(int.MaxValue)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, ".NET Core optimizes Take(...).Skip(...) on lazy sequences to avoid unecessary allocation. Without this optimization this test takes many minutes. See https://github.com/dotnet/corefx/pull/13628.")]
public void LazySkipAllTakenForLargeNumbers(int largeNumber)
{
Assert.Empty(new FastInfiniteEnumerator<int>().Take(largeNumber).Skip(largeNumber));
Assert.Empty(new FastInfiniteEnumerator<int>().Take(largeNumber).Skip(largeNumber).Skip(42));
Assert.Empty(new FastInfiniteEnumerator<int>().Take(largeNumber).Skip(largeNumber / 2).Skip(largeNumber / 2 + 1));
}
[Fact]
public void LazyOverflowRegression()
{
var range = NumberRangeGuaranteedNotCollectionType(1, 100);
var skipped = range.Skip(42); // Min index is 42.
var taken = skipped.Take(int.MaxValue); // May try to calculate max index as 42 + int.MaxValue, leading to integer overflow.
Assert.Equal(Enumerable.Range(43, 100 - 42), taken);
Assert.Equal(100 - 42, taken.Count());
Assert.Equal(Enumerable.Range(43, 100 - 42), taken.ToArray());
Assert.Equal(Enumerable.Range(43, 100 - 42), taken.ToList());
}
[Theory]
[InlineData(0, 0, 0)]
[InlineData(1, 1, 1)]
[InlineData(0, int.MaxValue, 100)]
[InlineData(int.MaxValue, 0, 0)]
[InlineData(0xffff, 1, 0)]
[InlineData(1, 0xffff, 99)]
[InlineData(int.MaxValue, int.MaxValue, 0)]
[InlineData(1, int.MaxValue, 99)] // Regression test: The max index is precisely int.MaxValue.
[InlineData(0, 100, 100)]
[InlineData(10, 100, 90)]
public void CountOfLazySkipTakeChain(int skip, int take, int expected)
{
var partition = NumberRangeGuaranteedNotCollectionType(1, 100).Skip(skip).Take(take);
Assert.Equal(expected, partition.Count());
Assert.Equal(expected, partition.Select(i => i).Count());
Assert.Equal(expected, partition.Select(i => i).ToArray().Length);
}
[Theory]
[InlineData(new[] { 1, 2, 3, 4 }, 1, 3, 2, 4)]
[InlineData(new[] { 1 }, 0, 1, 1, 1)]
[InlineData(new[] { 1, 2, 3, 5, 8, 13 }, 1, int.MaxValue, 2, 13)] // Regression test: The max index is precisely int.MaxValue.
[InlineData(new[] { 1, 2, 3, 5, 8, 13 }, 0, 2, 1, 2)]
[InlineData(new[] { 1, 2, 3, 5, 8, 13 }, 500, 2, 0, 0)]
[InlineData(new int[] { }, 10, 8, 0, 0)]
public void FirstAndLastOfLazySkipTakeChain(IEnumerable<int> source, int skip, int take, int first, int last)
{
var partition = ForceNotCollection(source).Skip(skip).Take(take);
Assert.Equal(first, partition.FirstOrDefault());
Assert.Equal(first, partition.ElementAtOrDefault(0));
Assert.Equal(last, partition.LastOrDefault());
Assert.Equal(last, partition.ElementAtOrDefault(partition.Count() - 1));
}
[Theory]
[InlineData(new[] { 1, 2, 3, 4, 5 }, 1, 3, new[] { -1, 0, 1, 2 }, new[] { 0, 2, 3, 4 })]
[InlineData(new[] { 0xfefe, 7000, 123 }, 0, 3, new[] { -1, 0, 1, 2 }, new[] { 0, 0xfefe, 7000, 123 })]
[InlineData(new[] { 0xfefe }, 100, 100, new[] { -1, 0, 1, 2 }, new[] { 0, 0, 0, 0 })]
[InlineData(new[] { 0xfefe, 123, 456, 7890, 5555, 55 }, 1, 10, new[] { -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }, new[] { 0, 123, 456, 7890, 5555, 55, 0, 0, 0, 0, 0, 0, 0 })]
public void ElementAtOfLazySkipTakeChain(IEnumerable<int> source, int skip, int take, int[] indices, int[] expectedValues)
{
var partition = ForceNotCollection(source).Skip(skip).Take(take);
Assert.Equal(indices.Length, expectedValues.Length);
for (int i = 0; i < indices.Length; i++)
{
Assert.Equal(expectedValues[i], partition.ElementAtOrDefault(indices[i]));
}
}
[Theory]
[InlineData(0, -1)]
[InlineData(0, 0)]
[InlineData(1, 0)]
[InlineData(2, 1)]
[InlineData(2, 2)]
[InlineData(2, 3)]
public void DisposeSource(int sourceCount, int count)
{
int state = 0;
var source = new DelegateIterator<int>(
moveNext: () => ++state <= sourceCount,
current: () => 0,
dispose: () => state = -1);
IEnumerator<int> iterator = source.Take(count).GetEnumerator();
int iteratorCount = Math.Min(sourceCount, Math.Max(0, count));
Assert.All(Enumerable.Range(0, iteratorCount), _ => Assert.True(iterator.MoveNext()));
Assert.False(iterator.MoveNext());
// Unlike Skip, Take can tell straightaway that it can return a sequence with no elements if count <= 0.
// The enumerable it returns is a specialized empty iterator that has no connections to the source. Hence,
// after MoveNext returns false under those circumstances, it won't invoke Dispose on our enumerator.
int expected = count <= 0 ? 0 : -1;
Assert.Equal(expected, state);
}
}
}
| |
// <copyright file=ReplaceGameObjects company=Hydra>
// Copyright (c) 2015 All Rights Reserved
// </copyright>
// <author>Christopher Cameron</author>
using System.Collections.Generic;
using Hydra.HydraCommon.Editor.Utils;
using Hydra.HydraCommon.Extensions;
using UnityEditor;
using UnityEngine;
namespace Hydra.HydraCommon.Editor.Windows
{
/// <summary>
/// ReplaceGameObjects allows for batch replacement of scene instances with
/// a prefab reference, keeping transform data and names.
///
/// Based on -
/// CopyComponents - by Michael L. Croswell for Colorado Game Coders, LLC
/// http://forum.unity3d.com/threads/replace-game-object-with-prefab.24311/
/// </summary>
public class ReplaceGameObjects : HydraEditorWindow
{
public const string TITLE = "Replace GameObjects";
private static GameObject s_Prefab;
private static List<GameObject> s_ObjectsToReplace;
private static bool s_KeepOriginalNames = true;
private static Vector2 s_ScrollPosition;
/// <summary>
/// Initializes the ReplaceGameObjects class.
/// </summary>
static ReplaceGameObjects()
{
s_ObjectsToReplace = new List<GameObject>();
}
/// <summary>
/// Shows the window.
/// </summary>
[MenuItem(MENU + TITLE)]
public static void Init()
{
GetWindow<ReplaceGameObjects>(false, TITLE, true);
UpdateSelection();
}
#region Messages
/// <summary>
/// Called whenever the selection changes.
/// </summary>
protected override void OnSelectionChange()
{
base.OnSelectionChange();
UpdateSelection();
}
/// <summary>
/// Called to draw the window contents.
/// </summary>
protected override void OnGUI()
{
base.OnGUI();
s_KeepOriginalNames = GUILayout.Toggle(s_KeepOriginalNames, "Keep names");
GUILayout.Space(5);
s_Prefab = EditorGUILayout.ObjectField("Prefab", s_Prefab, typeof(GameObject), false) as GameObject;
GUILayout.Space(5);
HydraEditorLayoutUtils.BeginBox(false);
{
s_ScrollPosition = GUILayout.BeginScrollView(s_ScrollPosition);
{
for (int index = 0; index < s_ObjectsToReplace.Count; index++)
{
GameObject original = s_ObjectsToReplace[index];
GUIStyle style = HydraEditorGUIStyles.ArrayElementStyle(index);
GUILayout.BeginHorizontal(style);
GUILayout.Label(original.name);
GUILayout.EndHorizontal();
}
}
GUILayout.EndScrollView();
}
HydraEditorLayoutUtils.EndBox(false);
GUILayout.Space(5);
GUILayout.BeginHorizontal();
{
bool oldEnabled = GUI.enabled;
GUI.enabled = s_Prefab != null;
if (GUILayout.Button("Apply"))
Replace();
GUI.enabled = oldEnabled;
}
GUILayout.EndHorizontal();
}
#endregion
/// <summary>
/// Updates the selection.
/// </summary>
private static void UpdateSelection()
{
s_ObjectsToReplace.Clear();
GameObject[] selection = Selection.gameObjects;
for (int index = 0; index < selection.Length; index++)
{
GameObject gameObject = selection[index];
if (IgnoreGameObject(gameObject))
continue;
s_ObjectsToReplace.Add(gameObject);
}
//s_ObjectsToReplace = Selection.gameObjects;
s_ObjectsToReplace.Sort(delegate(GameObject x, GameObject y) { return x.name.CompareTo(y.name); });
}
/// <summary>
/// Returns true if the target GameObject should be ignored for replacement.
/// </summary>
/// <returns><c>true</c>, if game object is ignored, <c>false</c> otherwise.</returns>
/// <param name="gameObject">Game object.</param>
private static bool IgnoreGameObject(GameObject gameObject)
{
if (gameObject == null)
return true;
// Don't allow replacing prefabs with prefabs.
if (PrefabUtility.GetPrefabType(gameObject) == PrefabType.Prefab)
return true;
return false;
}
/// <summary>
/// Replaces the selected instances with the selected prefab.
/// </summary>
private static void Replace()
{
Replace(s_ObjectsToReplace, s_Prefab, s_KeepOriginalNames);
}
/// <summary>
/// Replaces the original instances with the given prefab.
/// </summary>
/// <param name="originals">Originals.</param>
/// <param name="prefab">Prefab.</param>
/// <param name="keepNames">If set to <c>true</c> keep names.</param>
public static void Replace(List<GameObject> originals, GameObject prefab, bool keepNames)
{
Undo.IncrementCurrentGroup();
Undo.SetCurrentGroupName(typeof(ReplaceGameObjects).Name);
int undoIndex = Undo.GetCurrentGroup();
for (int index = 0; index < originals.Count; index++)
{
Replace(originals[index], prefab, keepNames);
originals[index] = null;
}
Undo.CollapseUndoOperations(undoIndex);
}
/// <summary>
/// Replaces the original instance with the given prefab.
/// </summary>
/// <param name="original">Original.</param>
/// <param name="prefab">Prefab.</param>
/// <param name="keepNames">If set to <c>true</c> keep names.</param>
public static GameObject Replace(GameObject original, GameObject prefab, bool keepNames)
{
if (IgnoreGameObject(original))
return null;
GameObject newObject = PrefabUtility.InstantiatePrefab(prefab) as GameObject;
newObject.transform.Copy(original);
if (keepNames)
newObject.name = original.name;
Undo.RegisterCreatedObjectUndo(newObject, original.name + "replaced");
Undo.DestroyObjectImmediate(original);
return newObject;
}
}
}
| |
///////////////////////////////////////////////////////////////////////////
// Description: Data Access class for the table 'RS_JenisRegistrasi'
// Generated by LLBLGen v1.21.2003.712 Final on: Thursday, October 11, 2007, 2:03:11 AM
// Because the Base Class already implements IDispose, this class doesn't.
///////////////////////////////////////////////////////////////////////////
using System;
using System.Data;
using System.Data.SqlTypes;
using System.Data.SqlClient;
namespace SIMRS.DataAccess
{
/// <summary>
/// Purpose: Data Access class for the table 'RS_JenisRegistrasi'.
/// </summary>
public class RS_JenisRegistrasi : DBInteractionBase
{
#region Class Member Declarations
private SqlBoolean _published;
private SqlDateTime _createdDate, _modifiedDate;
private SqlInt32 _createdBy, _modifiedBy, _ordering, _id;
private SqlString _kode, _nama, _keterangan;
#endregion
/// <summary>
/// Purpose: Class constructor.
/// </summary>
public RS_JenisRegistrasi()
{
// Nothing for now.
}
/// <summary>
/// Purpose: IsExist method. This method will check Exsisting data from database.
/// </summary>
/// <returns></returns>
public bool IsExist()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[RS_JenisRegistrasi_IsExist]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _id));
cmdToExecute.Parameters.Add(new SqlParameter("@Kode", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _kode));
cmdToExecute.Parameters.Add(new SqlParameter("@Nama", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _nama));
cmdToExecute.Parameters.Add(new SqlParameter("@IsExist", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, false, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
_rowsAffected = cmdToExecute.ExecuteNonQuery();
int IsExist = int.Parse(cmdToExecute.Parameters["@IsExist"].Value.ToString());
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if (_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'RS_JenisRegistrasi_IsExist' reported the ErrorCode: " + _errorCode);
}
return IsExist == 1;
}
catch (Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("RS_JenisRegistrasi::IsExist::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
}
}
/// <summary>
/// Purpose: Insert method. This method will insert one new row into the database.
/// </summary>
/// <returns>True if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties needed for this method:
/// <UL>
/// <LI>Id</LI>
/// <LI>Kode</LI>
/// <LI>Nama</LI>
/// <LI>Keterangan. May be SqlString.Null</LI>
/// <LI>Published</LI>
/// <LI>Ordering</LI>
/// <LI>CreatedBy</LI>
/// <LI>CreatedDate</LI>
/// <LI>ModifiedBy. May be SqlInt32.Null</LI>
/// <LI>ModifiedDate. May be SqlDateTime.Null</LI>
/// </UL>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public override bool Insert()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[RS_JenisRegistrasi_Insert]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _id));
cmdToExecute.Parameters.Add(new SqlParameter("@Kode", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _kode));
cmdToExecute.Parameters.Add(new SqlParameter("@Nama", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _nama));
cmdToExecute.Parameters.Add(new SqlParameter("@Keterangan", SqlDbType.VarChar, 255, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _keterangan));
cmdToExecute.Parameters.Add(new SqlParameter("@Published", SqlDbType.Bit, 1, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _published));
cmdToExecute.Parameters.Add(new SqlParameter("@Ordering", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _ordering));
cmdToExecute.Parameters.Add(new SqlParameter("@CreatedBy", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _createdBy));
cmdToExecute.Parameters.Add(new SqlParameter("@CreatedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _createdDate));
cmdToExecute.Parameters.Add(new SqlParameter("@ModifiedBy", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _modifiedBy));
cmdToExecute.Parameters.Add(new SqlParameter("@ModifiedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _modifiedDate));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
_rowsAffected = cmdToExecute.ExecuteNonQuery();
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if (_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'RS_JenisRegistrasi_Insert' reported the ErrorCode: " + _errorCode);
}
return true;
}
catch (Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("RS_JenisRegistrasi::Insert::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
}
}
/// <summary>
/// Purpose: Update method. This method will Update one existing row in the database.
/// </summary>
/// <returns>True if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties needed for this method:
/// <UL>
/// <LI>Id</LI>
/// <LI>Kode</LI>
/// <LI>Nama</LI>
/// <LI>Keterangan. May be SqlString.Null</LI>
/// <LI>Published</LI>
/// <LI>Ordering</LI>
/// <LI>CreatedBy</LI>
/// <LI>CreatedDate</LI>
/// <LI>ModifiedBy. May be SqlInt32.Null</LI>
/// <LI>ModifiedDate. May be SqlDateTime.Null</LI>
/// </UL>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public override bool Update()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[RS_JenisRegistrasi_Update]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _id));
cmdToExecute.Parameters.Add(new SqlParameter("@Kode", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _kode));
cmdToExecute.Parameters.Add(new SqlParameter("@Nama", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _nama));
cmdToExecute.Parameters.Add(new SqlParameter("@Keterangan", SqlDbType.VarChar, 255, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _keterangan));
cmdToExecute.Parameters.Add(new SqlParameter("@Published", SqlDbType.Bit, 1, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _published));
cmdToExecute.Parameters.Add(new SqlParameter("@Ordering", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _ordering));
cmdToExecute.Parameters.Add(new SqlParameter("@CreatedBy", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _createdBy));
cmdToExecute.Parameters.Add(new SqlParameter("@CreatedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _createdDate));
cmdToExecute.Parameters.Add(new SqlParameter("@ModifiedBy", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _modifiedBy));
cmdToExecute.Parameters.Add(new SqlParameter("@ModifiedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _modifiedDate));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
_rowsAffected = cmdToExecute.ExecuteNonQuery();
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if (_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'RS_JenisRegistrasi_Update' reported the ErrorCode: " + _errorCode);
}
return true;
}
catch (Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("RS_JenisRegistrasi::Update::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
}
}
/// <summary>
/// Purpose: Delete method. This method will Delete one existing row in the database, based on the Primary Key.
/// </summary>
/// <returns>True if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties needed for this method:
/// <UL>
/// <LI>Id</LI>
/// </UL>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public override bool Delete()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[RS_JenisRegistrasi_Delete]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _id));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
_rowsAffected = cmdToExecute.ExecuteNonQuery();
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if (_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'RS_JenisRegistrasi_Delete' reported the ErrorCode: " + _errorCode);
}
return true;
}
catch (Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("RS_JenisRegistrasi::Delete::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
}
}
/// <summary>
/// Purpose: Select method. This method will Select one existing row from the database, based on the Primary Key.
/// </summary>
/// <returns>DataTable object if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties needed for this method:
/// <UL>
/// <LI>Id</LI>
/// </UL>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// <LI>Id</LI>
/// <LI>Kode</LI>
/// <LI>Nama</LI>
/// <LI>Keterangan</LI>
/// <LI>Published</LI>
/// <LI>Ordering</LI>
/// <LI>CreatedBy</LI>
/// <LI>CreatedDate</LI>
/// <LI>ModifiedBy</LI>
/// <LI>ModifiedDate</LI>
/// </UL>
/// Will fill all properties corresponding with a field in the table with the value of the row selected.
/// </remarks>
public override DataTable SelectOne()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[RS_JenisRegistrasi_SelectOne]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
DataTable toReturn = new DataTable("RS_JenisRegistrasi");
SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute);
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _id));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
adapter.Fill(toReturn);
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if (_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'RS_JenisRegistrasi_SelectOne' reported the ErrorCode: " + _errorCode);
}
if (toReturn.Rows.Count > 0)
{
_id = (Int32)toReturn.Rows[0]["Id"];
_kode = (string)toReturn.Rows[0]["Kode"];
_nama = (string)toReturn.Rows[0]["Nama"];
_keterangan = toReturn.Rows[0]["Keterangan"] == System.DBNull.Value ? SqlString.Null : (string)toReturn.Rows[0]["Keterangan"];
_published = (bool)toReturn.Rows[0]["Published"];
_ordering = (Int32)toReturn.Rows[0]["Ordering"];
_createdBy = (Int32)toReturn.Rows[0]["CreatedBy"];
_createdDate = (DateTime)toReturn.Rows[0]["CreatedDate"];
_modifiedBy = toReturn.Rows[0]["ModifiedBy"] == System.DBNull.Value ? SqlInt32.Null : (Int32)toReturn.Rows[0]["ModifiedBy"];
_modifiedDate = toReturn.Rows[0]["ModifiedDate"] == System.DBNull.Value ? SqlDateTime.Null : (DateTime)toReturn.Rows[0]["ModifiedDate"];
}
return toReturn;
}
catch (Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("RS_JenisRegistrasi::SelectOne::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
adapter.Dispose();
}
}
/// <summary>
/// Purpose: SelectAll method. This method will Select all rows from the table.
/// </summary>
/// <returns>DataTable object if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public override DataTable SelectAll()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[RS_JenisRegistrasi_SelectAll]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
DataTable toReturn = new DataTable("RS_JenisRegistrasi");
SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute);
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
adapter.Fill(toReturn);
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if (_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'RS_JenisRegistrasi_SelectAll' reported the ErrorCode: " + _errorCode);
}
return toReturn;
}
catch (Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("RS_JenisRegistrasi::SelectAll::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
adapter.Dispose();
}
}
/// <summary>
/// Purpose: GetList method. This method will Select all rows from the table where is active.
/// </summary>
/// <returns>DataTable object if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public DataTable GetList()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[RS_JenisRegistrasi_GetList]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
DataTable toReturn = new DataTable("RS_JenisRegistrasi");
SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute);
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
adapter.Fill(toReturn);
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if (_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'RS_JenisRegistrasi_GetList' reported the ErrorCode: " + _errorCode);
}
return toReturn;
}
catch (Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("RS_JenisRegistrasi::GetList::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
adapter.Dispose();
}
}
#region Class Property Declarations
public SqlInt32 Id
{
get
{
return _id;
}
set
{
SqlInt32 idTmp = (SqlInt32)value;
if (idTmp.IsNull)
{
throw new ArgumentOutOfRangeException("Id", "Id can't be NULL");
}
_id = value;
}
}
public SqlString Kode
{
get
{
return _kode;
}
set
{
SqlString kodeTmp = (SqlString)value;
if (kodeTmp.IsNull)
{
throw new ArgumentOutOfRangeException("Kode", "Kode can't be NULL");
}
_kode = value;
}
}
public SqlString Nama
{
get
{
return _nama;
}
set
{
SqlString namaTmp = (SqlString)value;
if (namaTmp.IsNull)
{
throw new ArgumentOutOfRangeException("Nama", "Nama can't be NULL");
}
_nama = value;
}
}
public SqlString Keterangan
{
get
{
return _keterangan;
}
set
{
_keterangan = value;
}
}
public SqlBoolean Published
{
get
{
return _published;
}
set
{
_published = value;
}
}
public SqlInt32 Ordering
{
get
{
return _ordering;
}
set
{
SqlInt32 orderingTmp = (SqlInt32)value;
if (orderingTmp.IsNull)
{
throw new ArgumentOutOfRangeException("Ordering", "Ordering can't be NULL");
}
_ordering = value;
}
}
public SqlInt32 CreatedBy
{
get
{
return _createdBy;
}
set
{
SqlInt32 createdByTmp = (SqlInt32)value;
if (createdByTmp.IsNull)
{
throw new ArgumentOutOfRangeException("CreatedBy", "CreatedBy can't be NULL");
}
_createdBy = value;
}
}
public SqlDateTime CreatedDate
{
get
{
return _createdDate;
}
set
{
SqlDateTime createdDateTmp = (SqlDateTime)value;
if (createdDateTmp.IsNull)
{
throw new ArgumentOutOfRangeException("CreatedDate", "CreatedDate can't be NULL");
}
_createdDate = value;
}
}
public SqlInt32 ModifiedBy
{
get
{
return _modifiedBy;
}
set
{
_modifiedBy = value;
}
}
public SqlDateTime ModifiedDate
{
get
{
return _modifiedDate;
}
set
{
_modifiedDate = value;
}
}
#endregion
}
}
| |
//TODO - object initialization syntax cleanup
using System;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Collections.Generic;
//http://digitalx.org/cue-sheet/index.html "all cue sheet information is a straight 1:1 copy from the cdrwin helpfile"
//http://www.gnu.org/software/libcdio/libcdio.html#Sectors
//this is actually a great reference. they use LSN instead of LBA.. maybe a good idea for us
namespace BizHawk.Emulation.DiscSystem.CUE
{
/// <summary>
/// Performs minimum parse processing on a cue file
/// </summary>
class ParseCueJob : DiscJob
{
/// <summary>
/// input: the cue string to parse
/// </summary>
public string IN_CueString;
/// <summary>
/// output: the resulting minimally-processed cue file
/// </summary>
public CUE_File OUT_CueFile;
/// <summary>
/// Indicates whether parsing will be strict or lenient
/// </summary>
public bool IN_Strict = false;
class CueLineParser
{
int index;
string str;
public bool EOF;
public CueLineParser(string line)
{
str = line;
}
public string ReadPath() { return ReadToken(Mode.Quotable); }
public string ReadToken() { return ReadToken(Mode.Normal); }
public string ReadLine()
{
int len = str.Length;
string ret = str.Substring(index, len - index);
index = len;
EOF = true;
return ret;
}
enum Mode
{
Normal, Quotable
}
string ReadToken(Mode mode)
{
if (EOF) return null;
bool isPath = mode == Mode.Quotable;
int startIndex = index;
bool inToken = false;
bool inQuote = false;
for (; ; )
{
bool done = false;
char c = str[index];
bool isWhiteSpace = (c == ' ' || c == '\t');
if (isWhiteSpace)
{
if (inQuote)
index++;
else
{
if (inToken)
done = true;
else
index++;
}
}
else
{
bool startedQuote = false;
if (!inToken)
{
startIndex = index;
if (isPath && c == '"')
startedQuote = inQuote = true;
inToken = true;
}
switch (str[index])
{
case '"':
index++;
if (inQuote && !startedQuote)
{
done = true;
}
break;
case '\\':
index++;
break;
default:
index++;
break;
}
}
if (index == str.Length)
{
EOF = true;
done = true;
}
if (done) break;
}
string ret = str.Substring(startIndex, index - startIndex);
if (mode == Mode.Quotable)
ret = ret.Trim('"');
return ret;
}
}
void LoadFromString(ParseCueJob job)
{
string cueString = job.IN_CueString;
TextReader tr = new StringReader(cueString);
for (; ; )
{
job.CurrentLine++;
string line = tr.ReadLine();
if (line == null) break;
line = line.Trim();
if (line == "") continue;
var clp = new CueLineParser(line);
string key = clp.ReadToken().ToUpperInvariant();
//remove nonsense at beginning
if (!IN_Strict)
{
while (key.Length > 0)
{
char c = key[0];
if(c == ';') break;
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) break;
key = key.Substring(1);
}
}
bool startsWithSemicolon = key.StartsWith(";");
if (startsWithSemicolon)
{
clp.EOF = true;
OUT_CueFile.Commands.Add(new CUE_File.Command.COMMENT() { Value = line });
}
else switch (key)
{
default:
job.Warn($"Unknown command: {key}");
break;
case "CATALOG":
if (OUT_CueFile.GlobalDiscInfo.Catalog != null)
job.Warn("Multiple CATALOG commands detected. Subsequent ones are ignored.");
else if (clp.EOF)
job.Warn("Ignoring empty CATALOG command");
else OUT_CueFile.Commands.Add(OUT_CueFile.GlobalDiscInfo.Catalog = new CUE_File.Command.CATALOG() { Value = clp.ReadToken() });
break;
case "CDTEXTFILE":
if (OUT_CueFile.GlobalDiscInfo.CDTextFile != null)
job.Warn("Multiple CDTEXTFILE commands detected. Subsequent ones are ignored.");
else if (clp.EOF)
job.Warn("Ignoring empty CDTEXTFILE command");
else OUT_CueFile.Commands.Add(OUT_CueFile.GlobalDiscInfo.CDTextFile = new CUE_File.Command.CDTEXTFILE() { Path = clp.ReadPath() });
break;
case "FILE":
{
var path = clp.ReadPath();
CueFileType ft;
if (clp.EOF)
{
job.Error("FILE command is missing file type.");
ft = CueFileType.Unspecified;
}
else
{
var strType = clp.ReadToken().ToUpperInvariant();
switch (strType)
{
default:
job.Error($"Unknown FILE type: {strType}");
ft = CueFileType.Unspecified;
break;
case "BINARY": ft = CueFileType.BINARY; break;
case "MOTOROLA": ft = CueFileType.MOTOROLA; break;
case "BINARAIFF": ft = CueFileType.AIFF; break;
case "WAVE": ft = CueFileType.WAVE; break;
case "MP3": ft = CueFileType.MP3; break;
}
}
OUT_CueFile.Commands.Add(new CUE_File.Command.FILE() { Path = path, Type = ft });
}
break;
case "FLAGS":
{
var cmd = new CUE_File.Command.FLAGS();
OUT_CueFile.Commands.Add(cmd);
while (!clp.EOF)
{
var flag = clp.ReadToken().ToUpperInvariant();
switch (flag)
{
case "DATA":
default:
job.Warn($"Unknown FLAG: {flag}");
break;
case "DCP": cmd.Flags |= CueTrackFlags.DCP; break;
case "4CH": cmd.Flags |= CueTrackFlags._4CH; break;
case "PRE": cmd.Flags |= CueTrackFlags.PRE; break;
case "SCMS": cmd.Flags |= CueTrackFlags.SCMS; break;
}
}
if (cmd.Flags == CueTrackFlags.None)
job.Warn("Empty FLAG command");
}
break;
case "INDEX":
{
if (clp.EOF)
{
job.Error("Incomplete INDEX command");
break;
}
string strindexnum = clp.ReadToken();
int indexnum;
if (!int.TryParse(strindexnum, out indexnum) || indexnum < 0 || indexnum > 99)
{
job.Error($"Invalid INDEX number: {strindexnum}");
break;
}
string str_timestamp = clp.ReadToken();
var ts = new Timestamp(str_timestamp);
if (!ts.Valid && !IN_Strict)
{
//try cleaning it up
str_timestamp = Regex.Replace(str_timestamp, "[^0-9:]", "");
ts = new Timestamp(str_timestamp);
}
if (!ts.Valid)
{
if (IN_Strict)
job.Error($"Invalid INDEX timestamp: {str_timestamp}");
break;
}
OUT_CueFile.Commands.Add(new CUE_File.Command.INDEX() { Number = indexnum, Timestamp = ts });
}
break;
case "ISRC":
if (OUT_CueFile.GlobalDiscInfo.ISRC != null)
job.Warn("Multiple ISRC commands detected. Subsequent ones are ignored.");
else if (clp.EOF)
job.Warn("Ignoring empty ISRC command");
else
{
var isrc = clp.ReadToken();
if (isrc.Length != 12)
job.Warn($"Invalid ISRC code ignored: {isrc}");
else
{
OUT_CueFile.Commands.Add(OUT_CueFile.GlobalDiscInfo.ISRC = new CUE_File.Command.ISRC() { Value = isrc });
}
}
break;
case "PERFORMER":
OUT_CueFile.Commands.Add(new CUE_File.Command.PERFORMER() { Value = clp.ReadPath() ?? "" });
break;
case "POSTGAP":
case "PREGAP":
{
var str_msf = clp.ReadToken();
var msf = new Timestamp(str_msf);
if (!msf.Valid)
job.Error($"Ignoring {{0}} with invalid length MSF: {str_msf}", key);
else
{
if (key == "POSTGAP")
OUT_CueFile.Commands.Add(new CUE_File.Command.POSTGAP() { Length = msf });
else
OUT_CueFile.Commands.Add(new CUE_File.Command.PREGAP() { Length = msf });
}
}
break;
case "REM":
OUT_CueFile.Commands.Add(new CUE_File.Command.REM() { Value = clp.ReadLine() });
break;
case "SONGWRITER":
OUT_CueFile.Commands.Add(new CUE_File.Command.SONGWRITER() { Value = clp.ReadPath() ?? "" });
break;
case "TITLE":
OUT_CueFile.Commands.Add(new CUE_File.Command.TITLE() { Value = clp.ReadPath() ?? "" });
break;
case "TRACK":
{
if (clp.EOF)
{
job.Error("Incomplete TRACK command");
break;
}
string str_tracknum = clp.ReadToken();
int tracknum;
if (!int.TryParse(str_tracknum, out tracknum) || tracknum < 1 || tracknum > 99)
{
job.Error($"Invalid TRACK number: {str_tracknum}");
break;
}
//TODO - check sequentiality? maybe as a warning
CueTrackType tt;
var str_trackType = clp.ReadToken();
switch (str_trackType.ToUpperInvariant())
{
default:
job.Error($"Unknown TRACK type: {str_trackType}");
tt = CueTrackType.Unknown;
break;
case "AUDIO": tt = CueTrackType.Audio; break;
case "CDG": tt = CueTrackType.CDG; break;
case "MODE1/2048": tt = CueTrackType.Mode1_2048; break;
case "MODE1/2352": tt = CueTrackType.Mode1_2352; break;
case "MODE2/2336": tt = CueTrackType.Mode2_2336; break;
case "MODE2/2352": tt = CueTrackType.Mode2_2352; break;
case "CDI/2336": tt = CueTrackType.CDI_2336; break;
case "CDI/2352": tt = CueTrackType.CDI_2352; break;
}
OUT_CueFile.Commands.Add(new CUE_File.Command.TRACK() { Number = tracknum, Type = tt });
}
break;
}
if (!clp.EOF)
{
var remainder = clp.ReadLine();
if (remainder.TrimStart().StartsWith(";"))
{
//add a comment
OUT_CueFile.Commands.Add(new CUE_File.Command.COMMENT() { Value = remainder });
}
else job.Warn($"Unknown text at end of line after processing command: {key}");
}
} //end cue parsing loop
job.FinishLog();
} //LoadFromString
public void Run(ParseCueJob job)
{
job.OUT_CueFile = new CUE_File();
job.LoadFromString(job);
}
}
} //namespace
| |
//-----------------------------------------------------------------------------
// Torque
// Copyright GarageGames, LLC 2011
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Misc. server commands avialable to clients
//-----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// Debug commands
//----------------------------------------------------------------------------
function serverCmdNetSimulateLag( %client, %msDelay, %packetLossPercent )
{
if ( %client.isAdmin )
%client.setSimulatedNetParams( %packetLossPercent / 100.0, %msDelay );
}
//----------------------------------------------------------------------------
// Camera commands
//----------------------------------------------------------------------------
function serverCmdTogglePathCamera(%client, %val)
{
if(%val)
{
%control = %client.PathCamera;
}
else
{
%control = %client.camera;
}
%client.setControlObject(%control);
clientCmdSyncEditorGui();
}
function serverCmdToggleCamera(%client)
{
if (%client.getControlObject() == %client.player)
{
%client.camera.setVelocity("0 0 0");
%control = %client.camera;
}
else
{
%client.player.setVelocity("0 0 0");
%control = %client.player;
}
%client.setControlObject(%control);
clientCmdSyncEditorGui();
}
function serverCmdSetEditorCameraPlayer(%client)
{
// Switch to Player Mode
%client.player.setVelocity("0 0 0");
%client.setControlObject(%client.player);
ServerConnection.setFirstPerson(1);
$isFirstPersonVar = 1;
clientCmdSyncEditorGui();
}
function serverCmdSetEditorCameraPlayerThird(%client)
{
// Swith to Player Mode
%client.player.setVelocity("0 0 0");
%client.setControlObject(%client.player);
ServerConnection.setFirstPerson(0);
$isFirstPersonVar = 0;
clientCmdSyncEditorGui();
}
function serverCmdDropPlayerAtCamera(%client)
{
// If the player is mounted to something (like a vehicle) drop that at the
// camera instead. The player will remain mounted.
%obj = %client.player.getObjectMount();
if (!isObject(%obj))
%obj = %client.player;
%obj.setTransform(%client.camera.getTransform());
%obj.setVelocity("0 0 0");
%client.setControlObject(%client.player);
clientCmdSyncEditorGui();
}
function serverCmdDropCameraAtPlayer(%client)
{
%client.camera.setTransform(%client.player.getEyeTransform());
%client.camera.setVelocity("0 0 0");
%client.setControlObject(%client.camera);
clientCmdSyncEditorGui();
}
function serverCmdCycleCameraFlyType(%client)
{
if(%client.camera.getMode() $= "Fly")
{
if(%client.camera.newtonMode == false) // Fly Camera
{
// Switch to Newton Fly Mode without rotation damping
%client.camera.newtonMode = "1";
%client.camera.newtonRotation = "0";
%client.camera.setVelocity("0 0 0");
}
else if(%client.camera.newtonRotation == false) // Newton Camera without rotation damping
{
// Switch to Newton Fly Mode with damped rotation
%client.camera.newtonMode = "1";
%client.camera.newtonRotation = "1";
%client.camera.setAngularVelocity("0 0 0");
}
else // Newton Camera with rotation damping
{
// Switch to Fly Mode
%client.camera.newtonMode = "0";
%client.camera.newtonRotation = "0";
}
%client.setControlObject(%client.camera);
clientCmdSyncEditorGui();
}
}
function serverCmdSetEditorCameraStandard(%client)
{
// Switch to Fly Mode
%client.camera.setFlyMode();
%client.camera.newtonMode = "0";
%client.camera.newtonRotation = "0";
%client.setControlObject(%client.camera);
clientCmdSyncEditorGui();
}
function serverCmdSetEditorCameraNewton(%client)
{
// Switch to Newton Fly Mode without rotation damping
%client.camera.setFlyMode();
%client.camera.newtonMode = "1";
%client.camera.newtonRotation = "0";
%client.camera.setVelocity("0 0 0");
%client.setControlObject(%client.camera);
clientCmdSyncEditorGui();
}
function serverCmdSetEditorCameraNewtonDamped(%client)
{
// Switch to Newton Fly Mode with damped rotation
%client.camera.setFlyMode();
%client.camera.newtonMode = "1";
%client.camera.newtonRotation = "1";
%client.camera.setAngularVelocity("0 0 0");
%client.setControlObject(%client.camera);
clientCmdSyncEditorGui();
}
function serverCmdSetEditorOrbitCamera(%client)
{
%client.camera.setEditOrbitMode();
%client.setControlObject(%client.camera);
clientCmdSyncEditorGui();
}
function serverCmdSetEditorFlyCamera(%client)
{
%client.camera.setFlyMode();
%client.setControlObject(%client.camera);
clientCmdSyncEditorGui();
}
function serverCmdEditorOrbitCameraSelectChange(%client, %size, %center)
{
if(%size > 0)
{
%client.camera.setValidEditOrbitPoint(true);
%client.camera.setEditOrbitPoint(%center);
}
else
{
%client.camera.setValidEditOrbitPoint(false);
}
}
function serverCmdEditorCameraAutoFit(%client, %radius)
{
%client.camera.autoFitRadius(%radius);
%client.setControlObject(%client.camera);
clientCmdSyncEditorGui();
}
//----------------------------------------------------------------------------
// Server admin
//----------------------------------------------------------------------------
function serverCmdSAD( %client, %password )
{
if( %password !$= "" && %password $= $Pref::Server::AdminPassword)
{
%client.isAdmin = true;
%client.isSuperAdmin = true;
%name = getTaggedString( %client.playerName );
MessageAll( 'MsgAdminForce', "\c2" @ %name @ " has become Admin by force.", %client );
}
}
function serverCmdSADSetPassword(%client, %password)
{
if(%client.isSuperAdmin)
$Pref::Server::AdminPassword = %password;
}
//----------------------------------------------------------------------------
// Server chat message handlers
//----------------------------------------------------------------------------
function serverCmdTeamMessageSent(%client, %text)
{
if(strlen(%text) >= $Pref::Server::MaxChatLen)
%text = getSubStr(%text, 0, $Pref::Server::MaxChatLen);
chatMessageTeam(%client, %client.team, '\c3%1: %2', %client.playerName, %text);
}
function serverCmdMessageSent(%client, %text)
{
if(strlen(%text) >= $Pref::Server::MaxChatLen)
%text = getSubStr(%text, 0, $Pref::Server::MaxChatLen);
chatMessageAll(%client, '\c4%1: %2', %client.playerName, %text);
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Internal;
namespace System.ComponentModel.Composition.Hosting
{
/// <summary>
/// AtomicComposition provides lightweight atomicCompositional semantics to enable temporary
/// state to be managed for a series of nested atomicCompositions. Each atomicComposition maintains
/// queryable state along with a sequence of actions necessary to complete the state when
/// the atomicComposition is no longer in danger of being rolled back. State is completed or
/// rolled back when the atomicComposition is disposed, depending on the state of the
/// CompleteOnDipose property which defaults to false. The using(...) pattern in C# is a
/// convenient mechanism for defining atomicComposition scopes.
///
/// The least obvious aspects of AtomicComposition deal with nesting.
///
/// Firstly, no complete actions are actually performed until the outermost atomicComposition is
/// completed. Completeting or rolling back nested atomicCompositions serves only to change which
/// actions would be completed the outer atomicComposition.
///
/// Secondly, state is added in the form of queries associated with an object key. The
/// key represents a unique object the state is being held on behalf of. The quieries are
/// accessed throught the Query methods which provide automatic chaining to execute queries
/// across the target atomicComposition and its inner atomicComposition as appropriate.
///
/// Lastly, when a nested atomicComposition is created for a given outer the outer atomicComposition is locked.
/// It remains locked until the inner atomicComposition is disposed or completeed preventing the addition of
/// state, actions or other inner atomicCompositions.
/// </summary>
public class AtomicComposition : IDisposable
{
private readonly AtomicComposition _outerAtomicComposition;
private KeyValuePair<object, object>[] _values;
private int _valueCount = 0;
private List<Action> _completeActionList;
private List<Action> _revertActionList;
private bool _isDisposed = false;
private bool _isCompleted = false;
private bool _containsInnerAtomicComposition = false;
public AtomicComposition()
: this(null)
{
}
public AtomicComposition(AtomicComposition outerAtomicComposition)
{
// Lock the inner atomicComposition so that we can assume nothing changes except on
// the innermost scope, and thereby optimize the query path
if (outerAtomicComposition != null)
{
_outerAtomicComposition = outerAtomicComposition;
_outerAtomicComposition.ContainsInnerAtomicComposition = true;
}
}
public void SetValue(object key, object value)
{
ThrowIfDisposed();
ThrowIfCompleted();
ThrowIfContainsInnerAtomicComposition();
Requires.NotNull(key, nameof(key));
SetValueInternal(key, value);
}
public bool TryGetValue<T>(object key, out T value)
{
return TryGetValue(key, false, out value);
}
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters")]
public bool TryGetValue<T>(object key, bool localAtomicCompositionOnly, out T value)
{
ThrowIfDisposed();
ThrowIfCompleted();
Requires.NotNull(key, nameof(key));
return TryGetValueInternal(key, localAtomicCompositionOnly, out value);
}
public void AddCompleteAction(Action completeAction)
{
ThrowIfDisposed();
ThrowIfCompleted();
ThrowIfContainsInnerAtomicComposition();
Requires.NotNull(completeAction, nameof(completeAction));
if (_completeActionList == null)
{
_completeActionList = new List<Action>();
}
_completeActionList.Add(completeAction);
}
public void AddRevertAction(Action revertAction)
{
ThrowIfDisposed();
ThrowIfCompleted();
ThrowIfContainsInnerAtomicComposition();
Requires.NotNull(revertAction, nameof(revertAction));
if (_revertActionList == null)
{
_revertActionList = new List<Action>();
}
_revertActionList.Add(revertAction);
}
public void Complete()
{
ThrowIfDisposed();
ThrowIfCompleted();
if (_outerAtomicComposition == null)
{ // Execute all the complete actions
FinalComplete();
}
else
{ // Copy the actions and state to the outer atomicComposition
CopyComplete();
}
_isCompleted = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
ThrowIfDisposed();
_isDisposed = true;
if (_outerAtomicComposition != null)
{
_outerAtomicComposition.ContainsInnerAtomicComposition = false;
}
// Revert is always immediate and involves forgetting information and
// exceuting any appropriate revert actions
if (!_isCompleted)
{
if (_revertActionList != null)
{
List<Exception> exceptions = null;
// Execute the revert actions in reverse order to ensure
// everything incrementally rollsback its state.
for (int i = _revertActionList.Count - 1; i >= 0; i--)
{
Action action = _revertActionList[i];
try
{
action();
}
catch(CompositionException)
{
// This can only happen after preview is completed, so ... abandon remainder of events is correct
throw;
}
catch(Exception e)
{
if (exceptions == null)
{
//If any exceptions leak through the actions we will swallow them for now
// complete processing the list
// and we will throw InvalidOperationException with an AggregateException as it's innerException
exceptions = new List<Exception>();
}
exceptions.Add(e);
}
}
_revertActionList = null;
if(exceptions != null)
{
throw new InvalidOperationException(SR.InvalidOperation_RevertAndCompleteActionsMustNotThrow, new AggregateException(exceptions));
}
}
}
}
private void FinalComplete()
{
// Completeting the outer most scope is easy, just execute all the actions
if (_completeActionList != null)
{
List<Exception> exceptions = null;
foreach (Action action in _completeActionList)
{
try
{
action();
}
catch(CompositionException)
{
// This can only happen after preview is completed, so ... abandon remainder of events is correct
throw;
}
catch(Exception e)
{
if (exceptions == null)
{
//If any exceptions leak through the actions we will swallow them for now complete processing the list
// and we will throw InvalidOperationException with an AggregateException as it's innerException
exceptions = new List<Exception>();
}
exceptions.Add(e);
}
}
_completeActionList = null;
if(exceptions != null)
{
throw new InvalidOperationException(SR.InvalidOperation_RevertAndCompleteActionsMustNotThrow, new AggregateException(exceptions));
}
}
}
private void CopyComplete()
{
Assumes.NotNull(_outerAtomicComposition);
_outerAtomicComposition.ContainsInnerAtomicComposition = false;
// Inner scopes are much odder, because completeting them means coalescing them into the
// outer scope - the complete or revert actions are deferred until the outermost scope completes
// or any intermediate rolls back
if (_completeActionList != null)
{
foreach (Action action in _completeActionList)
{
_outerAtomicComposition.AddCompleteAction(action);
}
}
if (_revertActionList != null)
{
foreach (Action action in _revertActionList)
{
_outerAtomicComposition.AddRevertAction(action);
}
}
// We can copy over existing atomicComposition entries because they're either already chained or
// overwrite by design and can now be completed or rolled back together
for (var index = 0; index < _valueCount; index++)
{
_outerAtomicComposition.SetValueInternal(
_values[index].Key, _values[index].Value);
}
}
private bool ContainsInnerAtomicComposition
{
set
{
if (value == true && _containsInnerAtomicComposition == true)
{
throw new InvalidOperationException(SR.AtomicComposition_AlreadyNested);
}
_containsInnerAtomicComposition = value;
}
}
private bool TryGetValueInternal<T>(object key, bool localAtomicCompositionOnly, out T value)
{
for (var index = 0; index < _valueCount; index++)
{
if (_values[index].Key == key)
{
value = (T)_values[index].Value;
return true;
}
}
// If there's no atomicComposition available then recurse until we hit the outermost
// scope, where upon we go ahead and return null
if (!localAtomicCompositionOnly && _outerAtomicComposition != null)
{
return _outerAtomicComposition.TryGetValueInternal<T>(key, localAtomicCompositionOnly, out value);
}
value = default(T);
return false;
}
private void SetValueInternal(object key, object value)
{
// Handle overwrites quickly
for (var index = 0; index < _valueCount; index++)
{
if (_values[index].Key == key)
{
_values[index] = new KeyValuePair<object,object>(key, value);
return;
}
}
// Expand storage when needed
if (_values == null || _valueCount == _values.Length)
{
var newQueries = new KeyValuePair<object, object>[_valueCount == 0 ? 5 : _valueCount * 2];
if (_values != null)
{
Array.Copy(_values, newQueries, _valueCount);
}
_values = newQueries;
}
// Store a new entry
_values[_valueCount] = new KeyValuePair<object, object>(key, value);
_valueCount++;
return;
}
[DebuggerStepThrough]
private void ThrowIfContainsInnerAtomicComposition()
{
if (_containsInnerAtomicComposition)
{
throw new InvalidOperationException(SR.AtomicComposition_PartOfAnotherAtomicComposition);
}
}
[DebuggerStepThrough]
private void ThrowIfCompleted()
{
if (_isCompleted)
{
throw new InvalidOperationException(SR.AtomicComposition_AlreadyCompleted);
}
}
[DebuggerStepThrough]
private void ThrowIfDisposed()
{
if (_isDisposed)
{
throw ExceptionBuilder.CreateObjectDisposed(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.Collections.Generic;
using System.Data.Common;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Concurrent;
namespace System.Data.ProviderBase
{
sealed internal class DbConnectionPool
{
private enum State
{
Initializing,
Running,
ShuttingDown,
}
private sealed class PendingGetConnection
{
public PendingGetConnection(long dueTime, DbConnection owner, TaskCompletionSource<DbConnectionInternal> completion, DbConnectionOptions userOptions)
{
DueTime = dueTime;
Owner = owner;
Completion = completion;
}
public long DueTime { get; private set; }
public DbConnection Owner { get; private set; }
public TaskCompletionSource<DbConnectionInternal> Completion { get; private set; }
public DbConnectionOptions UserOptions { get; private set; }
}
private sealed class PoolWaitHandles
{
private readonly Semaphore _poolSemaphore;
private readonly ManualResetEvent _errorEvent;
// Using a Mutex requires ThreadAffinity because SQL CLR can swap
// the underlying Win32 thread associated with a managed thread in preemptive mode.
// Using an AutoResetEvent does not have that complication.
private readonly Semaphore _creationSemaphore;
private readonly WaitHandle[] _handlesWithCreate;
private readonly WaitHandle[] _handlesWithoutCreate;
internal PoolWaitHandles()
{
_poolSemaphore = new Semaphore(0, MAX_Q_SIZE);
_errorEvent = new ManualResetEvent(false);
_creationSemaphore = new Semaphore(1, 1);
_handlesWithCreate = new WaitHandle[] { _poolSemaphore, _errorEvent, _creationSemaphore };
_handlesWithoutCreate = new WaitHandle[] { _poolSemaphore, _errorEvent };
}
internal Semaphore CreationSemaphore
{
get { return _creationSemaphore; }
}
internal ManualResetEvent ErrorEvent
{
get { return _errorEvent; }
}
internal Semaphore PoolSemaphore
{
get { return _poolSemaphore; }
}
internal WaitHandle[] GetHandles(bool withCreate)
{
return withCreate ? _handlesWithCreate : _handlesWithoutCreate;
}
}
private const int MAX_Q_SIZE = (int)0x00100000;
// The order of these is important; we want the WaitAny call to be signaled
// for a free object before a creation signal. Only the index first signaled
// object is returned from the WaitAny call.
private const int SEMAPHORE_HANDLE = (int)0x0;
private const int ERROR_HANDLE = (int)0x1;
private const int CREATION_HANDLE = (int)0x2;
private const int BOGUS_HANDLE = (int)0x3;
private const int ERROR_WAIT_DEFAULT = 5 * 1000; // 5 seconds
// we do want a testable, repeatable set of generated random numbers
private static readonly Random s_random = new Random(5101977); // Value obtained from Dave Driver
private readonly int _cleanupWait;
private readonly DbConnectionPoolIdentity _identity;
private readonly DbConnectionFactory _connectionFactory;
private readonly DbConnectionPoolGroup _connectionPoolGroup;
private readonly DbConnectionPoolGroupOptions _connectionPoolGroupOptions;
private DbConnectionPoolProviderInfo _connectionPoolProviderInfo;
private State _state;
private readonly ConcurrentStack<DbConnectionInternal> _stackOld = new ConcurrentStack<DbConnectionInternal>();
private readonly ConcurrentStack<DbConnectionInternal> _stackNew = new ConcurrentStack<DbConnectionInternal>();
private readonly ConcurrentQueue<PendingGetConnection> _pendingOpens = new ConcurrentQueue<PendingGetConnection>();
private int _pendingOpensWaiting = 0;
private readonly WaitCallback _poolCreateRequest;
private int _waitCount;
private readonly PoolWaitHandles _waitHandles;
private Exception _resError;
private volatile bool _errorOccurred;
private int _errorWait;
private Timer _errorTimer;
private Timer _cleanupTimer;
private readonly List<DbConnectionInternal> _objectList;
private int _totalObjects;
// only created by DbConnectionPoolGroup.GetConnectionPool
internal DbConnectionPool(
DbConnectionFactory connectionFactory,
DbConnectionPoolGroup connectionPoolGroup,
DbConnectionPoolIdentity identity,
DbConnectionPoolProviderInfo connectionPoolProviderInfo)
{
Debug.Assert(null != connectionPoolGroup, "null connectionPoolGroup");
if ((null != identity) && identity.IsRestricted)
{
throw ADP.InternalError(ADP.InternalErrorCode.AttemptingToPoolOnRestrictedToken);
}
_state = State.Initializing;
lock (s_random)
{ // Random.Next is not thread-safe
_cleanupWait = s_random.Next(12, 24) * 10 * 1000; // 2-4 minutes in 10 sec intervals
}
_connectionFactory = connectionFactory;
_connectionPoolGroup = connectionPoolGroup;
_connectionPoolGroupOptions = connectionPoolGroup.PoolGroupOptions;
_connectionPoolProviderInfo = connectionPoolProviderInfo;
_identity = identity;
_waitHandles = new PoolWaitHandles();
_errorWait = ERROR_WAIT_DEFAULT;
_errorTimer = null; // No error yet.
_objectList = new List<DbConnectionInternal>(MaxPoolSize);
_poolCreateRequest = new WaitCallback(PoolCreateRequest); // used by CleanupCallback
_state = State.Running;
//_cleanupTimer & QueuePoolCreateRequest is delayed until DbConnectionPoolGroup calls
// StartBackgroundCallbacks after pool is actually in the collection
}
private int CreationTimeout
{
get { return PoolGroupOptions.CreationTimeout; }
}
internal int Count
{
get { return _totalObjects; }
}
internal DbConnectionFactory ConnectionFactory
{
get { return _connectionFactory; }
}
internal bool ErrorOccurred
{
get { return _errorOccurred; }
}
internal TimeSpan LoadBalanceTimeout
{
get { return PoolGroupOptions.LoadBalanceTimeout; }
}
private bool NeedToReplenish
{
get
{
if (State.Running != _state) // Don't allow connection create when not running.
return false;
int totalObjects = Count;
if (totalObjects >= MaxPoolSize)
return false;
if (totalObjects < MinPoolSize)
return true;
int freeObjects = (_stackNew.Count + _stackOld.Count);
int waitingRequests = _waitCount;
bool needToReplenish = (freeObjects < waitingRequests) || ((freeObjects == waitingRequests) && (totalObjects > 1));
return needToReplenish;
}
}
internal DbConnectionPoolIdentity Identity
{
get { return _identity; }
}
internal bool IsRunning
{
get { return State.Running == _state; }
}
private int MaxPoolSize
{
get { return PoolGroupOptions.MaxPoolSize; }
}
private int MinPoolSize
{
get { return PoolGroupOptions.MinPoolSize; }
}
internal DbConnectionPoolGroup PoolGroup
{
get { return _connectionPoolGroup; }
}
internal DbConnectionPoolGroupOptions PoolGroupOptions
{
get { return _connectionPoolGroupOptions; }
}
internal DbConnectionPoolProviderInfo ProviderInfo
{
get { return _connectionPoolProviderInfo; }
}
internal bool UseLoadBalancing
{
get { return PoolGroupOptions.UseLoadBalancing; }
}
private bool UsingIntegrateSecurity
{
get { return (null != _identity && DbConnectionPoolIdentity.NoIdentity != _identity); }
}
private void CleanupCallback(Object state)
{
// Called when the cleanup-timer ticks over.
// This is the automatic prunning method. Every period, we will
// perform a two-step process:
//
// First, for each free object above MinPoolSize, we will obtain a
// semaphore representing one object and destroy one from old stack.
// We will continue this until we either reach MinPoolSize, we are
// unable to obtain a free object, or we have exhausted all the
// objects on the old stack.
//
// Second we move all free objects on the new stack to the old stack.
// So, every period the objects on the old stack are destroyed and
// the objects on the new stack are pushed to the old stack. All
// objects that are currently out and in use are not on either stack.
//
// With this logic, objects are pruned from the pool if unused for
// at least one period but not more than two periods.
// Destroy free objects that put us above MinPoolSize from old stack.
while (Count > MinPoolSize)
{ // While above MinPoolSize...
if (_waitHandles.PoolSemaphore.WaitOne(0))
{
// We obtained a objects from the semaphore.
DbConnectionInternal obj;
if (_stackOld.TryPop(out obj))
{
Debug.Assert(obj != null, "null connection is not expected");
// If we obtained one from the old stack, destroy it.
DestroyObject(obj);
}
else
{
// Else we exhausted the old stack (the object the
// semaphore represents is on the new stack), so break.
_waitHandles.PoolSemaphore.Release(1);
break;
}
}
else
{
break;
}
}
// Push to the old-stack. For each free object, move object from
// new stack to old stack.
if (_waitHandles.PoolSemaphore.WaitOne(0))
{
for (; ;)
{
DbConnectionInternal obj;
if (!_stackNew.TryPop(out obj))
break;
Debug.Assert(obj != null, "null connection is not expected");
Debug.Assert(!obj.IsEmancipated, "pooled object not in pool");
Debug.Assert(obj.CanBePooled, "pooled object is not poolable");
_stackOld.Push(obj);
}
_waitHandles.PoolSemaphore.Release(1);
}
// Queue up a request to bring us up to MinPoolSize
QueuePoolCreateRequest();
}
internal void Clear()
{
DbConnectionInternal obj;
// First, quickly doom everything.
lock (_objectList)
{
int count = _objectList.Count;
for (int i = 0; i < count; ++i)
{
obj = _objectList[i];
if (null != obj)
{
obj.DoNotPoolThisConnection();
}
}
}
// Second, dispose of all the free connections.
while (_stackNew.TryPop(out obj))
{
Debug.Assert(obj != null, "null connection is not expected");
DestroyObject(obj);
}
while (_stackOld.TryPop(out obj))
{
Debug.Assert(obj != null, "null connection is not expected");
DestroyObject(obj);
}
// Finally, reclaim everything that's emancipated (which, because
// it's been doomed, will cause it to be disposed of as well)
ReclaimEmancipatedObjects();
}
private Timer CreateCleanupTimer()
{
return (new Timer(new TimerCallback(this.CleanupCallback), null, _cleanupWait, _cleanupWait));
}
private DbConnectionInternal CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
{
DbConnectionInternal newObj = null;
try
{
newObj = _connectionFactory.CreatePooledConnection(this, owningObject, _connectionPoolGroup.ConnectionOptions, _connectionPoolGroup.PoolKey, userOptions);
if (null == newObj)
{
throw ADP.InternalError(ADP.InternalErrorCode.CreateObjectReturnedNull); // CreateObject succeeded, but null object
}
if (!newObj.CanBePooled)
{
throw ADP.InternalError(ADP.InternalErrorCode.NewObjectCannotBePooled); // CreateObject succeeded, but non-poolable object
}
newObj.PrePush(null);
lock (_objectList)
{
if ((oldConnection != null) && (oldConnection.Pool == this))
{
_objectList.Remove(oldConnection);
}
_objectList.Add(newObj);
_totalObjects = _objectList.Count;
}
// If the old connection belonged to another pool, we need to remove it from that
if (oldConnection != null)
{
var oldConnectionPool = oldConnection.Pool;
if (oldConnectionPool != null && oldConnectionPool != this)
{
Debug.Assert(oldConnectionPool._state == State.ShuttingDown, "Old connections pool should be shutting down");
lock (oldConnectionPool._objectList)
{
oldConnectionPool._objectList.Remove(oldConnection);
oldConnectionPool._totalObjects = oldConnectionPool._objectList.Count;
}
}
}
// Reset the error wait:
_errorWait = ERROR_WAIT_DEFAULT;
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
newObj = null; // set to null, so we do not return bad new object
// Failed to create instance
_resError = e;
// Make sure the timer starts even if ThreadAbort occurs after setting the ErrorEvent.
// timer allocation has to be done out of CER block
Timer t = new Timer(new TimerCallback(this.ErrorCallback), null, Timeout.Infinite, Timeout.Infinite);
bool timerIsNotDisposed;
try { }
finally
{
_waitHandles.ErrorEvent.Set();
_errorOccurred = true;
// Enable the timer.
// Note that the timer is created to allow periodic invocation. If ThreadAbort occurs in the middle of ErrorCallback,
// the timer will restart. Otherwise, the timer callback (ErrorCallback) destroys the timer after resetting the error to avoid second callback.
_errorTimer = t;
timerIsNotDisposed = t.Change(_errorWait, _errorWait);
}
Debug.Assert(timerIsNotDisposed, "ErrorCallback timer has been disposed");
if (30000 < _errorWait)
{
_errorWait = 60000;
}
else
{
_errorWait *= 2;
}
throw;
}
return newObj;
}
private void DeactivateObject(DbConnectionInternal obj)
{
obj.DeactivateConnection();
bool returnToGeneralPool = false;
bool destroyObject = false;
if (obj.IsConnectionDoomed)
{
// the object is not fit for reuse -- just dispose of it.
destroyObject = true;
}
else
{
// NOTE: constructor should ensure that current state cannot be State.Initializing, so it can only
// be State.Running or State.ShuttingDown
Debug.Assert(_state == State.Running || _state == State.ShuttingDown);
lock (obj)
{
// A connection with a delegated transaction cannot currently
// be returned to a different customer until the transaction
// actually completes, so we send it into Stasis -- the SysTx
// transaction object will ensure that it is owned (not lost),
// and it will be certain to put it back into the pool.
if (_state == State.ShuttingDown)
{
// connection is being closed and the pool has been marked as shutting
// down, so destroy this object.
destroyObject = true;
}
else
{
if (obj.CanBePooled)
{
// We must put this connection into the transacted pool
// while inside a lock to prevent a race condition with
// the transaction asyncronously completing on a second
// thread.
// return to general pool
returnToGeneralPool = true;
}
else
{
// object is not fit for reuse -- just dispose of it
destroyObject = true;
}
}
}
}
if (returnToGeneralPool)
{
// Only push the connection into the general pool if we didn't
// already push it onto the transacted pool, put it into stasis,
// or want to destroy it.
Debug.Assert(destroyObject == false);
PutNewObject(obj);
}
else if (destroyObject)
{
DestroyObject(obj);
QueuePoolCreateRequest();
}
//-------------------------------------------------------------------------------------
// postcondition
// ensure that the connection was processed
Debug.Assert(
returnToGeneralPool == true || destroyObject == true);
}
internal void DestroyObject(DbConnectionInternal obj)
{
// A connection with a delegated transaction cannot be disposed of
// until the delegated transaction has actually completed. Instead,
// we simply leave it alone; when the transaction completes, it will
// come back through PutObjectFromTransactedPool, which will call us
// again.
bool removed = false;
lock (_objectList)
{
removed = _objectList.Remove(obj);
Debug.Assert(removed, "attempt to DestroyObject not in list");
_totalObjects = _objectList.Count;
}
if (removed)
{
}
obj.Dispose();
}
private void ErrorCallback(Object state)
{
_errorOccurred = false;
_waitHandles.ErrorEvent.Reset();
// the error state is cleaned, destroy the timer to avoid periodic invocation
Timer t = _errorTimer;
_errorTimer = null;
if (t != null)
{
t.Dispose(); // Cancel timer request.
}
}
private Exception TryCloneCachedException()
// Cached exception can be of any type, so is not always cloneable.
// This functions clones SqlException
// OleDb and Odbc connections are not passing throw this code
{
if (_resError == null)
return null;
var sqlError = _resError as SqlClient.SqlException;
if (sqlError != null)
return sqlError.InternalClone();
return _resError;
}
private void WaitForPendingOpen()
{
PendingGetConnection next;
do
{
bool started = false;
try
{
try { }
finally
{
started = Interlocked.CompareExchange(ref _pendingOpensWaiting, 1, 0) == 0;
}
if (!started)
{
return;
}
while (_pendingOpens.TryDequeue(out next))
{
if (next.Completion.Task.IsCompleted)
{
continue;
}
uint delay;
if (next.DueTime == Timeout.Infinite)
{
delay = unchecked((uint)Timeout.Infinite);
}
else
{
delay = (uint)Math.Max(ADP.TimerRemainingMilliseconds(next.DueTime), 0);
}
DbConnectionInternal connection = null;
bool timeout = false;
Exception caughtException = null;
try
{
bool allowCreate = true;
bool onlyOneCheckConnection = false;
timeout = !TryGetConnection(next.Owner, delay, allowCreate, onlyOneCheckConnection, next.UserOptions, out connection);
}
catch (Exception e)
{
caughtException = e;
}
if (caughtException != null)
{
next.Completion.TrySetException(caughtException);
}
else if (timeout)
{
next.Completion.TrySetException(ADP.ExceptionWithStackTrace(ADP.PooledOpenTimeout()));
}
else
{
Debug.Assert(connection != null, "connection should never be null in success case");
if (!next.Completion.TrySetResult(connection))
{
// if the completion was cancelled, lets try and get this connection back for the next try
PutObject(connection, next.Owner);
}
}
}
}
finally
{
if (started)
{
Interlocked.Exchange(ref _pendingOpensWaiting, 0);
}
}
} while (_pendingOpens.TryPeek(out next));
}
internal bool TryGetConnection(DbConnection owningObject, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions, out DbConnectionInternal connection)
{
uint waitForMultipleObjectsTimeout = 0;
bool allowCreate = false;
if (retry == null)
{
waitForMultipleObjectsTimeout = (uint)CreationTimeout;
// Set the wait timeout to INFINITE (-1) if the SQL connection timeout is 0 (== infinite)
if (waitForMultipleObjectsTimeout == 0)
waitForMultipleObjectsTimeout = unchecked((uint)Timeout.Infinite);
allowCreate = true;
}
if (_state != State.Running)
{
connection = null;
return true;
}
bool onlyOneCheckConnection = true;
if (TryGetConnection(owningObject, waitForMultipleObjectsTimeout, allowCreate, onlyOneCheckConnection, userOptions, out connection))
{
return true;
}
else if (retry == null)
{
// timed out on a sync call
return true;
}
var pendingGetConnection =
new PendingGetConnection(
CreationTimeout == 0 ? Timeout.Infinite : ADP.TimerCurrent() + ADP.TimerFromSeconds(CreationTimeout / 1000),
owningObject,
retry,
userOptions);
_pendingOpens.Enqueue(pendingGetConnection);
// it is better to StartNew too many times than not enough
if (_pendingOpensWaiting == 0)
{
Thread waitOpenThread = new Thread(WaitForPendingOpen);
waitOpenThread.IsBackground = true;
waitOpenThread.Start();
}
connection = null;
return false;
}
private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObjectsTimeout, bool allowCreate, bool onlyOneCheckConnection, DbConnectionOptions userOptions, out DbConnectionInternal connection)
{
DbConnectionInternal obj = null;
if (null == obj)
{
Interlocked.Increment(ref _waitCount);
do
{
int waitResult = BOGUS_HANDLE;
try
{
try
{
}
finally
{
waitResult = WaitHandle.WaitAny(_waitHandles.GetHandles(allowCreate), unchecked((int)waitForMultipleObjectsTimeout));
}
// From the WaitAny docs: "If more than one object became signaled during
// the call, this is the array index of the signaled object with the
// smallest index value of all the signaled objects." This is important
// so that the free object signal will be returned before a creation
// signal.
switch (waitResult)
{
case WaitHandle.WaitTimeout:
Interlocked.Decrement(ref _waitCount);
connection = null;
return false;
case ERROR_HANDLE:
// Throw the error that PoolCreateRequest stashed.
Interlocked.Decrement(ref _waitCount);
throw TryCloneCachedException();
case CREATION_HANDLE:
try
{
obj = UserCreateRequest(owningObject, userOptions);
}
catch
{
if (null == obj)
{
Interlocked.Decrement(ref _waitCount);
}
throw;
}
finally
{
// Ensure that we release this waiter, regardless
// of any exceptions that may be thrown.
if (null != obj)
{
Interlocked.Decrement(ref _waitCount);
}
}
if (null == obj)
{
// If we were not able to create an object, check to see if
// we reached MaxPoolSize. If so, we will no longer wait on
// the CreationHandle, but instead wait for a free object or
// the timeout.
if (Count >= MaxPoolSize && 0 != MaxPoolSize)
{
if (!ReclaimEmancipatedObjects())
{
// modify handle array not to wait on creation mutex anymore
Debug.Assert(2 == CREATION_HANDLE, "creation handle changed value");
allowCreate = false;
}
}
}
break;
case SEMAPHORE_HANDLE:
//
// guaranteed available inventory
//
Interlocked.Decrement(ref _waitCount);
obj = GetFromGeneralPool();
if ((obj != null) && (!obj.IsConnectionAlive()))
{
DestroyObject(obj);
obj = null; // Setting to null in case creating a new object fails
if (onlyOneCheckConnection)
{
if (_waitHandles.CreationSemaphore.WaitOne(unchecked((int)waitForMultipleObjectsTimeout)))
{
try
{
obj = UserCreateRequest(owningObject, userOptions);
}
finally
{
_waitHandles.CreationSemaphore.Release(1);
}
}
else
{
// Timeout waiting for creation semaphore - return null
connection = null;
return false;
}
}
}
break;
default:
Interlocked.Decrement(ref _waitCount);
throw ADP.InternalError(ADP.InternalErrorCode.UnexpectedWaitAnyResult);
}
}
finally
{
if (CREATION_HANDLE == waitResult)
{
_waitHandles.CreationSemaphore.Release(1);
}
}
} while (null == obj);
}
if (null != obj)
{
PrepareConnection(owningObject, obj);
}
connection = obj;
return true;
}
private void PrepareConnection(DbConnection owningObject, DbConnectionInternal obj)
{
lock (obj)
{ // Protect against Clear and ReclaimEmancipatedObjects, which call IsEmancipated, which is affected by PrePush and PostPop
obj.PostPop(owningObject);
}
try
{
obj.ActivateConnection();
}
catch
{
// if Activate throws an exception
// put it back in the pool or have it properly disposed of
this.PutObject(obj, owningObject);
throw;
}
}
/// <summary>
/// Creates a new connection to replace an existing connection
/// </summary>
/// <param name="owningObject">Outer connection that currently owns <paramref name="oldConnection"/></param>
/// <param name="userOptions">Options used to create the new connection</param>
/// <param name="oldConnection">Inner connection that will be replaced</param>
/// <returns>A new inner connection that is attached to the <paramref name="owningObject"/></returns>
internal DbConnectionInternal ReplaceConnection(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
{
DbConnectionInternal newConnection = UserCreateRequest(owningObject, userOptions, oldConnection);
if (newConnection != null)
{
PrepareConnection(owningObject, newConnection);
oldConnection.PrepareForReplaceConnection();
oldConnection.DeactivateConnection();
oldConnection.Dispose();
}
return newConnection;
}
private DbConnectionInternal GetFromGeneralPool()
{
DbConnectionInternal obj = null;
if (!_stackNew.TryPop(out obj))
{
if (!_stackOld.TryPop(out obj))
{
obj = null;
}
else
{
Debug.Assert(obj != null, "null connection is not expected");
}
}
else
{
Debug.Assert(obj != null, "null connection is not expected");
}
// When another thread is clearing this pool,
// it will remove all connections in this pool which causes the
// following assert to fire, which really mucks up stress against
// checked bits.
if (null != obj)
{
}
return (obj);
}
private void PoolCreateRequest(object state)
{
// called by pooler to ensure pool requests are currently being satisfied -
// creation mutex has not been obtained
if (State.Running == _state)
{
// in case WaitForPendingOpen ever failed with no subsequent OpenAsync calls,
// start it back up again
if (!_pendingOpens.IsEmpty && _pendingOpensWaiting == 0)
{
Thread waitOpenThread = new Thread(WaitForPendingOpen);
waitOpenThread.IsBackground = true;
waitOpenThread.Start();
}
// Before creating any new objects, reclaim any released objects that were
// not closed.
ReclaimEmancipatedObjects();
if (!ErrorOccurred)
{
if (NeedToReplenish)
{
// Check to see if pool was created using integrated security and if so, make
// sure the identity of current user matches that of user that created pool.
// If it doesn't match, do not create any objects on the ThreadPool thread,
// since either Open will fail or we will open a object for this pool that does
// not belong in this pool. The side effect of this is that if using integrated
// security min pool size cannot be guaranteed.
if (UsingIntegrateSecurity && !_identity.Equals(DbConnectionPoolIdentity.GetCurrent()))
{
return;
}
int waitResult = BOGUS_HANDLE;
try
{
try { }
finally
{
waitResult = WaitHandle.WaitAny(_waitHandles.GetHandles(withCreate: true), CreationTimeout);
}
if (CREATION_HANDLE == waitResult)
{
DbConnectionInternal newObj;
// Check ErrorOccurred again after obtaining mutex
if (!ErrorOccurred)
{
while (NeedToReplenish)
{
// Don't specify any user options because there is no outer connection associated with the new connection
newObj = CreateObject(owningObject: null, userOptions: null, oldConnection: null);
// We do not need to check error flag here, since we know if
// CreateObject returned null, we are in error case.
if (null != newObj)
{
PutNewObject(newObj);
}
else
{
break;
}
}
}
}
else if (WaitHandle.WaitTimeout == waitResult)
{
// do not wait forever and potential block this worker thread
// instead wait for a period of time and just requeue to try again
QueuePoolCreateRequest();
}
}
finally
{
if (CREATION_HANDLE == waitResult)
{
// reuse waitResult and ignore its value
_waitHandles.CreationSemaphore.Release(1);
}
}
}
}
}
}
internal void PutNewObject(DbConnectionInternal obj)
{
Debug.Assert(null != obj, "why are we adding a null object to the pool?");
// Debug.Assert(obj.CanBePooled, "non-poolable object in pool");
_stackNew.Push(obj);
_waitHandles.PoolSemaphore.Release(1);
}
internal void PutObject(DbConnectionInternal obj, object owningObject)
{
Debug.Assert(null != obj, "null obj?");
// Once a connection is closing (which is the state that we're in at
// this point in time) you cannot delegate a transaction to or enlist
// a transaction in it, so we can correctly presume that if there was
// not a delegated or enlisted transaction to start with, that there
// will not be a delegated or enlisted transaction once we leave the
// lock.
lock (obj)
{
// Calling PrePush prevents the object from being reclaimed
// once we leave the lock, because it sets _pooledCount such
// that it won't appear to be out of the pool. What that
// means, is that we're now responsible for this connection:
// it won't get reclaimed if we drop the ball somewhere.
obj.PrePush(owningObject);
}
DeactivateObject(obj);
}
private void QueuePoolCreateRequest()
{
if (State.Running == _state)
{
// Make sure we're at quota by posting a callback to the threadpool.
ThreadPool.QueueUserWorkItem(_poolCreateRequest);
}
}
private bool ReclaimEmancipatedObjects()
{
bool emancipatedObjectFound = false;
List<DbConnectionInternal> reclaimedObjects = new List<DbConnectionInternal>();
int count;
lock (_objectList)
{
count = _objectList.Count;
for (int i = 0; i < count; ++i)
{
DbConnectionInternal obj = _objectList[i];
if (null != obj)
{
bool locked = false;
try
{
Monitor.TryEnter(obj, ref locked);
if (locked)
{ // avoid race condition with PrePush/PostPop and IsEmancipated
if (obj.IsEmancipated)
{
// Inside the lock, we want to do as little
// as possible, so we simply mark the object
// as being in the pool, but hand it off to
// an out of pool list to be deactivated,
// etc.
obj.PrePush(null);
reclaimedObjects.Add(obj);
}
}
}
finally
{
if (locked)
Monitor.Exit(obj);
}
}
}
}
// NOTE: we don't want to call DeactivateObject while we're locked,
// because it can make roundtrips to the server and this will block
// object creation in the pooler. Instead, we queue things we need
// to do up, and process them outside the lock.
count = reclaimedObjects.Count;
for (int i = 0; i < count; ++i)
{
DbConnectionInternal obj = reclaimedObjects[i];
emancipatedObjectFound = true;
DeactivateObject(obj);
}
return emancipatedObjectFound;
}
internal void Startup()
{
_cleanupTimer = CreateCleanupTimer();
if (NeedToReplenish)
{
QueuePoolCreateRequest();
}
}
internal void Shutdown()
{
_state = State.ShuttingDown;
// deactivate timer callbacks
Timer t = _cleanupTimer;
_cleanupTimer = null;
if (null != t)
{
t.Dispose();
}
}
private DbConnectionInternal UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection = null)
{
// called by user when they were not able to obtain a free object but
// instead obtained creation mutex
DbConnectionInternal obj = null;
if (ErrorOccurred)
{
throw TryCloneCachedException();
}
else
{
if ((oldConnection != null) || (Count < MaxPoolSize) || (0 == MaxPoolSize))
{
// If we have an odd number of total objects, reclaim any dead objects.
// If we did not find any objects to reclaim, create a new one.
if ((oldConnection != null) || (Count & 0x1) == 0x1 || !ReclaimEmancipatedObjects())
obj = CreateObject(owningObject, userOptions, oldConnection);
}
return obj;
}
}
}
}
| |
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.Reflection;
using System.IO;
namespace PhotoManage.MethodTwo
{
/// <summary>
/// EXIFextractor Class
///
/// </summary>
public class EXIFextractor : IEnumerable
{
/// <summary>
/// Get the individual property value by supplying property name
/// These are the valid property names :
///
/// "Exif IFD"
/// "Gps IFD"
/// "New Subfile Type"
/// "Subfile Type"
/// "Image Width"
/// "Image Height"
/// "Bits Per Sample"
/// "Compression"
/// "Photometric Interp"
/// "Thresh Holding"
/// "Cell Width"
/// "Cell Height"
/// "Fill Order"
/// "Document Name"
/// "Image Description"
/// "Equip Make"
/// "Equip Model"
/// "Strip Offsets"
/// "Orientation"
/// "Samples PerPixel"
/// "Rows Per Strip"
/// "Strip Bytes Count"
/// "Min Sample Value"
/// "Max Sample Value"
/// "X Resolution"
/// "Y Resolution"
/// "Planar Config"
/// "Page Name"
/// "X Position"
/// "Y Position"
/// "Free Offset"
/// "Free Byte Counts"
/// "Gray Response Unit"
/// "Gray Response Curve"
/// "T4 Option"
/// "T6 Option"
/// "Resolution Unit"
/// "Page Number"
/// "Transfer Funcition"
/// "Software Used"
/// "Date Time"
/// "Artist"
/// "Host Computer"
/// "Predictor"
/// "White Point"
/// "Primary Chromaticities"
/// "ColorMap"
/// "Halftone Hints"
/// "Tile Width"
/// "Tile Length"
/// "Tile Offset"
/// "Tile ByteCounts"
/// "InkSet"
/// "Ink Names"
/// "Number Of Inks"
/// "Dot Range"
/// "Target Printer"
/// "Extra Samples"
/// "Sample Format"
/// "S Min Sample Value"
/// "S Max Sample Value"
/// "Transfer Range"
/// "JPEG Proc"
/// "JPEG InterFormat"
/// "JPEG InterLength"
/// "JPEG RestartInterval"
/// "JPEG LosslessPredictors"
/// "JPEG PointTransforms"
/// "JPEG QTables"
/// "JPEG DCTables"
/// "JPEG ACTables"
/// "YCbCr Coefficients"
/// "YCbCr Subsampling"
/// "YCbCr Positioning"
/// "REF Black White"
/// "ICC Profile"
/// "Gamma"
/// "ICC Profile Descriptor"
/// "SRGB RenderingIntent"
/// "Image Title"
/// "Copyright"
/// "Resolution X Unit"
/// "Resolution Y Unit"
/// "Resolution X LengthUnit"
/// "Resolution Y LengthUnit"
/// "Print Flags"
/// "Print Flags Version"
/// "Print Flags Crop"
/// "Print Flags Bleed Width"
/// "Print Flags Bleed Width Scale"
/// "Halftone LPI"
/// "Halftone LPIUnit"
/// "Halftone Degree"
/// "Halftone Shape"
/// "Halftone Misc"
/// "Halftone Screen"
/// "JPEG Quality"
/// "Grid Size"
/// "Thumbnail Format"
/// "Thumbnail Width"
/// "Thumbnail Height"
/// "Thumbnail ColorDepth"
/// "Thumbnail Planes"
/// "Thumbnail RawBytes"
/// "Thumbnail Size"
/// "Thumbnail CompressedSize"
/// "Color Transfer Function"
/// "Thumbnail Data"
/// "Thumbnail ImageWidth"
/// "Thumbnail ImageHeight"
/// "Thumbnail BitsPerSample"
/// "Thumbnail Compression"
/// "Thumbnail PhotometricInterp"
/// "Thumbnail ImageDescription"
/// "Thumbnail EquipMake"
/// "Thumbnail EquipModel"
/// "Thumbnail StripOffsets"
/// "Thumbnail Orientation"
/// "Thumbnail SamplesPerPixel"
/// "Thumbnail RowsPerStrip"
/// "Thumbnail StripBytesCount"
/// "Thumbnail ResolutionX"
/// "Thumbnail ResolutionY"
/// "Thumbnail PlanarConfig"
/// "Thumbnail ResolutionUnit"
/// "Thumbnail TransferFunction"
/// "Thumbnail SoftwareUsed"
/// "Thumbnail DateTime"
/// "Thumbnail Artist"
/// "Thumbnail WhitePoint"
/// "Thumbnail PrimaryChromaticities"
/// "Thumbnail YCbCrCoefficients"
/// "Thumbnail YCbCrSubsampling"
/// "Thumbnail YCbCrPositioning"
/// "Thumbnail RefBlackWhite"
/// "Thumbnail CopyRight"
/// "Luminance Table"
/// "Chrominance Table"
/// "Frame Delay"
/// "Loop Count"
/// "Pixel Unit"
/// "Pixel PerUnit X"
/// "Pixel PerUnit Y"
/// "Palette Histogram"
/// "Exposure Time"
/// "F-Number"
/// "Exposure Prog"
/// "Spectral Sense"
/// "ISO Speed"
/// "OECF"
/// "Ver"
/// "DTOrig"
/// "DTDigitized"
/// "CompConfig"
/// "CompBPP"
/// "Shutter Speed"
/// "Aperture"
/// "Brightness"
/// "Exposure Bias"
/// "MaxAperture"
/// "SubjectDist"
/// "Metering Mode"
/// "LightSource"
/// "Flash"
/// "FocalLength"
/// "Maker Note"
/// "User Comment"
/// "DTSubsec"
/// "DTOrigSS"
/// "DTDigSS"
/// "FPXVer"
/// "ColorSpace"
/// "PixXDim"
/// "PixYDim"
/// "RelatedWav"
/// "Interop"
/// "FlashEnergy"
/// "SpatialFR"
/// "FocalXRes"
/// "FocalYRes"
/// "FocalResUnit"
/// "Subject Loc"
/// "Exposure Index"
/// "Sensing Method"
/// "FileSource"
/// "SceneType"
/// "CfaPattern"
/// "Gps Ver"
/// "Gps LatitudeRef"
/// "Gps Latitude"
/// "Gps LongitudeRef"
/// "Gps Longitude"
/// "Gps AltitudeRef"
/// "Gps Altitude"
/// "Gps GpsTime"
/// "Gps GpsSatellites"
/// "Gps GpsStatus"
/// "Gps GpsMeasureMode"
/// "Gps GpsDop"
/// "Gps SpeedRef"
/// "Gps Speed"
/// "Gps TrackRef"
/// "Gps Track"
/// "Gps ImgDirRef"
/// "Gps ImgDir"
/// "Gps MapDatum"
/// "Gps DestLatRef"
/// "Gps DestLat"
/// "Gps DestLongRef"
/// "Gps DestLong"
/// "Gps DestBearRef"
/// "Gps DestBear"
/// "Gps DestDistRef"
/// "Gps DestDist"
/// </summary>
public object this[string index]
{
get
{
return properties[index];
}
}
//
//private System.Drawing.Bitmap bmp;
//
private string data;
//
private translation myHash;
//
private Hashtable properties;
//
internal int Count
{
get
{
return this.properties.Count;
}
}
//
string sp;
/// <summary>
///
/// </summary>
/// <param name="id"></param>
/// <param name="len"></param>
/// <param name="type"></param>
/// <param name="data"></param>
//public void setTag(int id, string data)
//{
// Encoding ascii = Encoding.ASCII;
// this.setTag(id, data.Length, 0x2, ascii.GetBytes(data));
//}
/// <summary>
///
/// </summary>
/// <param name="id"></param>
/// <param name="len"></param>
/// <param name="type"></param>
/// <param name="data"></param>
//public void setTag(int id, int len, short type, byte[] data)
//{
// PropertyItem p = CreatePropertyItem(type, id, len, data);
// this.bmp.SetPropertyItem(p);
// buildDB(this.bmp.PropertyItems);
//}
/// <summary>
///
/// </summary>
/// <param name="type"></param>
/// <param name="tag"></param>
/// <param name="len"></param>
/// <param name="value"></param>
/// <returns></returns>
//private static PropertyItem CreatePropertyItem(short type, int tag, int len, byte[] value)
//{
// PropertyItem item;
// Loads a PropertyItem from a Jpeg image stored in the assembly as a resource.
// Assembly assembly = Assembly.GetExecutingAssembly();
// Stream emptyBitmapStream = assembly.GetManifestResourceStream("EXIFextractor.decoy.jpg");
// System.Drawing.Image empty = System.Drawing.Image.FromStream(emptyBitmapStream);
// item = empty.PropertyItems[0];
// Copies the data to the property item.
// item.Type = type;
// item.Len = len;
// item.Id = tag;
// item.Value = new byte[value.Length];
// value.CopyTo(item.Value, 0);
// return item;
//}
/// <summary>
///
/// </summary>
/// <param name="bmp"></param>
/// <param name="sp"></param>
//public EXIFextractor(ref System.Drawing.Bitmap bmp, string sp)
//{
// properties = new Hashtable();
// //
// this.bmp = bmp;
// this.sp = sp;
// //
// myHash = new translation();
// buildDB(this.bmp.PropertyItems);
//}
string msp = "";
//public EXIFextractor(ref System.Drawing.Bitmap bmp, string sp, string msp)
//{
// properties = new Hashtable();
// this.sp = sp;
// this.msp = msp;
// this.bmp = bmp;
// //
// myHash = new translation();
// this.buildDB(bmp.PropertyItems);
//}
public static PropertyItem[] GetExifProperties(string fileName)
{
FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
System.Drawing.Image image = System.Drawing.Image.FromStream(stream,
/* useEmbeddedColorManagement = */ true,
/* validateImageData = */ false);
return image.PropertyItems;
}
public EXIFextractor(string file, string sp, string msp)
{
properties = new Hashtable();
this.sp = sp;
this.msp = msp;
myHash = new translation();
//
this.buildDB(GetExifProperties(file));
}
/// <summary>
///
/// </summary>
private void buildDB(System.Drawing.Imaging.PropertyItem[] parr)
{
properties.Clear();
//
data = "";
//
Encoding ascii = Encoding.ASCII;
//
foreach (System.Drawing.Imaging.PropertyItem p in parr)
{
string v = "";
string name = (string)myHash[p.Id];
// tag not found. skip it
if (name == null) continue;
//
data += name + ": ";
//
//1 = BYTE An 8-bit unsigned integer.,
if (p.Type == 0x1)
{
v = p.Value[0].ToString();
}
//2 = ASCII An 8-bit byte containing one 7-bit ASCII code. The final byte is terminated with NULL.,
else if (p.Type == 0x2)
{
// string
v = ascii.GetString(p.Value);
}
//3 = SHORT A 16-bit (2 -byte) unsigned integer,
else if (p.Type == 0x3)
{
// orientation // lookup table
switch (p.Id)
{
case 0x8827: // ISO
v = "ISO-" + convertToInt16U(p.Value).ToString();
break;
case 0xA217: // sensing method
{
switch (convertToInt16U(p.Value))
{
case 1: v = "Not defined"; break;
case 2: v = "One-chip color area sensor"; break;
case 3: v = "Two-chip color area sensor"; break;
case 4: v = "Three-chip color area sensor"; break;
case 5: v = "Color sequential area sensor"; break;
case 7: v = "Trilinear sensor"; break;
case 8: v = "Color sequential linear sensor"; break;
default: v = " reserved"; break;
}
}
break;
case 0x8822: // aperture
switch (convertToInt16U(p.Value))
{
case 0: v = "Not defined"; break;
case 1: v = "Manual"; break;
case 2: v = "Normal program"; break;
case 3: v = "Aperture priority"; break;
case 4: v = "Shutter priority"; break;
case 5: v = "Creative program (biased toward depth of field)"; break;
case 6: v = "Action program (biased toward fast shutter speed)"; break;
case 7: v = "Portrait mode (for closeup photos with the background out of focus)"; break;
case 8: v = "Landscape mode (for landscape photos with the background in focus)"; break;
default: v = "reserved"; break;
}
break;
case 0x9207: // metering mode
switch (convertToInt16U(p.Value))
{
case 0: v = "unknown"; break;
case 1: v = "Average"; break;
case 2: v = "CenterWeightedAverage"; break;
case 3: v = "Spot"; break;
case 4: v = "MultiSpot"; break;
case 5: v = "Pattern"; break;
case 6: v = "Partial"; break;
case 255: v = "Other"; break;
default: v = "reserved"; break;
}
break;
case 0x9208: // light source
{
switch (convertToInt16U(p.Value))
{
case 0: v = "unknown"; break;
case 1: v = "Daylight"; break;
case 2: v = "Fluorescent"; break;
case 3: v = "Tungsten"; break;
case 17: v = "Standard light A"; break;
case 18: v = "Standard light B"; break;
case 19: v = "Standard light C"; break;
case 20: v = "D55"; break;
case 21: v = "D65"; break;
case 22: v = "D75"; break;
case 255: v = "other"; break;
default: v = "reserved"; break;
}
}
break;
case 0x9209:
{
switch (convertToInt16U(p.Value))
{
case 0: v = "Flash did not fire"; break;
case 1: v = "Flash fired"; break;
case 5: v = "Strobe return light not detected"; break;
case 7: v = "Strobe return light detected"; break;
default: v = "reserved"; break;
}
}
break;
default:
v = convertToInt16U(p.Value).ToString();
break;
}
}
//4 = LONG A 32-bit (4 -byte) unsigned integer,
else if (p.Type == 0x4)
{
// orientation // lookup table
v = convertToInt32U(p.Value).ToString();
}
//5 = RATIONAL Two LONGs. The first LONG is the numerator and the second LONG expresses the//denominator.,
else if (p.Type == 0x5)
{
// rational
byte[] n = new byte[p.Len / 2];
byte[] d = new byte[p.Len / 2];
Array.Copy(p.Value, 0, n, 0, p.Len / 2);
Array.Copy(p.Value, p.Len / 2, d, 0, p.Len / 2);
uint a = convertToInt32U(n);
uint b = convertToInt32U(d);
Rational r = new Rational(a, b);
//
//convert here
//
switch (p.Id)
{
case 0x9202: // aperture
v = "F/" + Math.Round(Math.Pow(Math.Sqrt(2), r.ToDouble()), 2).ToString();
break;
case 0x920A:
v = r.ToDouble().ToString();
break;
case 0x829A:
v = r.ToDouble().ToString();
break;
case 0x829D: // F-number
v = "F/" + r.ToDouble().ToString();
break;
default:
v = r.ToString("/");
break;
}
}
//7 = UNDEFINED An 8-bit byte that can take any value depending on the field definition,
else if (p.Type == 0x7)
{
switch (p.Id)
{
case 0xA300:
{
if (p.Value[0] == 3)
{
v = "DSC";
}
else
{
v = "reserved";
}
break;
}
case 0xA301:
if (p.Value[0] == 1)
v = "A directly photographed image";
else
v = "Not a directly photographed image";
break;
default:
v = "-";
break;
}
}
//9 = SLONG A 32-bit (4 -byte) signed integer (2's complement notation),
else if (p.Type == 0x9)
{
v = convertToInt32(p.Value).ToString();
}
//10 = SRATIONAL Two SLONGs. The first SLONG is the numerator and the second SLONG is the
//denominator.
else if (p.Type == 0xA)
{
// rational
byte[] n = new byte[p.Len / 2];
byte[] d = new byte[p.Len / 2];
Array.Copy(p.Value, 0, n, 0, p.Len / 2);
Array.Copy(p.Value, p.Len / 2, d, 0, p.Len / 2);
int a = convertToInt32(n);
int b = convertToInt32(d);
Rational r = new Rational(a, b);
//
// convert here
//
switch (p.Id)
{
case 0x9201: // shutter speed
v = "1/" + Math.Round(Math.Pow(2, r.ToDouble()), 2).ToString();
break;
case 0x9203:
v = Math.Round(r.ToDouble(), 4).ToString();
break;
default:
v = r.ToString("/");
break;
}
}
// add it to the list
if (properties[name] == null)
properties.Add(name, v);
// cat it too
data += v;
data += this.sp;
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override string ToString()
{
return data;
}
/// <summary>
///
/// </summary>
/// <param name="arr"></param>
/// <returns></returns>
int convertToInt32(byte[] arr)
{
if (arr.Length != 4)
return 0;
else
return arr[3] << 24 | arr[2] << 16 | arr[1] << 8 | arr[0];
}
/// <summary>
///
/// </summary>
/// <param name="arr"></param>
/// <returns></returns>
int convertToInt16(byte[] arr)
{
if (arr.Length != 2)
return 0;
else
return arr[1] << 8 | arr[0];
}
/// <summary>
///
/// </summary>
/// <param name="arr"></param>
/// <returns></returns>
uint convertToInt32U(byte[] arr)
{
if (arr.Length != 4)
return 0;
else
return Convert.ToUInt32(arr[3] << 24 | arr[2] << 16 | arr[1] << 8 | arr[0]);
}
/// <summary>
///
/// </summary>
/// <param name="arr"></param>
/// <returns></returns>
uint convertToInt16U(byte[] arr)
{
if (arr.Length != 2)
return 0;
else
return Convert.ToUInt16(arr[1] << 8 | arr[0]);
}
#region IEnumerable Members
public IEnumerator GetEnumerator()
{
// TODO: Add EXIFextractor.GetEnumerator implementation
return (new EXIFextractorEnumerator(this.properties));
}
#endregion
}
//
// dont touch this class. its for IEnumerator
//
//
class EXIFextractorEnumerator : IEnumerator
{
Hashtable exifTable;
IDictionaryEnumerator index;
internal EXIFextractorEnumerator(Hashtable exif)
{
this.exifTable = exif;
this.Reset();
index = exif.GetEnumerator();
}
#region IEnumerator Members
public void Reset()
{
this.index = null;
}
public object Current
{
get
{
return new KeyValuePair<object, object>(this.index.Key, this.index.Value);
// return (new System.Web.UI.Pair(this.index.Key, this.index.Value));
}
}
public bool MoveNext()
{
if (index != null && index.MoveNext())
return true;
else
return false;
}
#endregion
}
}
| |
/*
* Copyright 2004 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.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Security.Permissions;
using System.Threading;
using System.Windows.Forms;
using NUnit.Framework;
using Solenoid.Expressions.Support.Util;
using Solenoid.Expressions.Tests.Objects;
[assembly: InternalsVisibleTo("ReflectionUtils.IsTypeVisible.AssemblyTestName")]
namespace Solenoid.Expressions.Tests.Util
{
/// <summary>
/// Unit tests for the ReflectionUtils class.
/// </summary>
[TestFixture]
public sealed class ReflectionUtilsTests
{
private interface IMapsInterfaceMethodInterface
{
void SomeMethodA();
void SomeMethodB();
object SomeProperty { get; }
}
public class MapsInterfaceMethodClass : IMapsInterfaceMethodInterface
{
public MethodInfo MethodAInfo;
public MethodInfo MethodBInfo;
public MethodInfo PropGetterInfo;
public MapsInterfaceMethodClass()
{
SomeMethodA();
((IMapsInterfaceMethodInterface) this).SomeMethodB();
var o = ((IMapsInterfaceMethodInterface) this).SomeProperty;
}
public void SomeMethodA()
{
MethodAInfo = (MethodInfo) MethodInfo.GetCurrentMethod();
}
void IMapsInterfaceMethodInterface.SomeMethodB()
{
MethodBInfo = (MethodInfo) MethodInfo.GetCurrentMethod();
}
object IMapsInterfaceMethodInterface.SomeProperty
{
get
{
PropGetterInfo = (MethodInfo) MethodInfo.GetCurrentMethod();
return null;
}
}
}
private class DummyException : ApplicationException
{
public DummyException()
: base("dummy message")
{
}
}
public static void ThrowDummyException()
{
throw new DummyException();
}
public delegate void VoidAction();
[Test]
public void UnwrapsTargetInvocationException()
{
if (SystemUtils.MonoRuntime)
{
#if DEBUG
// TODO (EE): find solution for Mono
return;
#endif
}
var mi = new VoidAction(ThrowDummyException).Method;
try
{
try
{
mi.Invoke(null, null);
Assert.Fail();
}
catch (TargetInvocationException tie)
{
// Console.WriteLine(tie);
throw ReflectionUtils.UnwrapTargetInvocationException(tie);
}
Assert.Fail();
}
catch (DummyException e)
{
// Console.WriteLine(e);
var stackFrames = e.StackTrace.Split('\n');
#if !MONO
// TODO: mono includes the invoke() call in inner stackframe does not include the outer stackframes - either remove or document it
var firstFrameMethodName = mi.DeclaringType.FullName + "." + mi.Name;
AssertStringContains(firstFrameMethodName, stackFrames[0]);
var lastFrameMethodName = MethodBase.GetCurrentMethod().DeclaringType.FullName + "." +
MethodBase.GetCurrentMethod().Name;
AssertStringContains(lastFrameMethodName, stackFrames[stackFrames.Length - 1]);
#endif
}
}
private void AssertStringContains(string toSearch, string source)
{
if (source.IndexOf(toSearch) == -1)
{
Assert.Fail("Expected '{0}' contained in source, but not found. Source was {1}", toSearch, source);
}
}
[Test]
public void MapsInterfaceMethodsToImplementation()
{
var instance = new MapsInterfaceMethodClass();
MethodInfo method = null;
try
{
method = ReflectionUtils.MapInterfaceMethodToImplementationIfNecessary(null, typeof (MapsInterfaceMethodClass));
Assert.Fail();
}
catch (ArgumentNullException ex)
{
Assert.AreEqual("methodInfo", ex.ParamName);
}
try
{
method = ReflectionUtils.MapInterfaceMethodToImplementationIfNecessary((MethodInfo) MethodInfo.GetCurrentMethod(),
null);
Assert.Fail();
}
catch (ArgumentNullException ex)
{
Assert.AreEqual("implementingType", ex.ParamName);
}
try
{
// unrelated types
method = ReflectionUtils.MapInterfaceMethodToImplementationIfNecessary((MethodInfo) MethodInfo.GetCurrentMethod(),
typeof (MapsInterfaceMethodClass));
Assert.Fail();
}
catch (ArgumentException ex)
{
Assert.AreEqual("methodInfo and implementingType are unrelated", ex.Message);
}
method =
ReflectionUtils.MapInterfaceMethodToImplementationIfNecessary(
typeof (MapsInterfaceMethodClass).GetMethod("SomeMethodA"), typeof (MapsInterfaceMethodClass));
Assert.AreSame(instance.MethodAInfo, method);
method =
ReflectionUtils.MapInterfaceMethodToImplementationIfNecessary(
typeof (IMapsInterfaceMethodInterface).GetMethod("SomeMethodA"), typeof (MapsInterfaceMethodClass));
Assert.AreSame(instance.MethodAInfo, method);
method =
ReflectionUtils.MapInterfaceMethodToImplementationIfNecessary(
typeof (IMapsInterfaceMethodInterface).GetMethod("SomeMethodB"), typeof (MapsInterfaceMethodClass));
Assert.AreSame(instance.MethodBInfo, method);
method =
ReflectionUtils.MapInterfaceMethodToImplementationIfNecessary(
typeof (IMapsInterfaceMethodInterface).GetProperty("SomeProperty").GetGetMethod(),
typeof (MapsInterfaceMethodClass));
Assert.AreSame(instance.PropGetterInfo, method);
}
public class Foo
{
public readonly string a = "";
public readonly int b = -1;
public readonly char c = '0';
public Foo(string a, int b, char c)
{
this.a = a;
this.b = b;
this.c = c;
}
public Foo(string a)
{
this.a = a;
}
public Foo()
{
}
public void MethodWithNullableIntegerArg(int? nullableInteger)
{
}
}
[Test(Description = "http://jira.springframework.org/browse/SPRNET-992")]
public void ShouldPickDefaultConstructorWithoutArgs()
{
var args = new object[] {};
var best = ReflectionUtils.GetConstructorByArgumentValues(typeof (Foo).GetConstructors(), null);
var foo = (Foo) best.Invoke(args);
Assert.AreEqual("", foo.a);
Assert.AreEqual(-1, foo.b);
Assert.AreEqual('0', foo.c);
}
[Test(Description = "http://jira.springframework.org/browse/SPRNET-992")]
public void ShouldPickDefaultConstructor()
{
var args = new object[] {};
var best = ReflectionUtils.GetConstructorByArgumentValues(typeof (Foo).GetConstructors(), args);
var foo = (Foo) best.Invoke(args);
Assert.AreEqual("", foo.a);
Assert.AreEqual(-1, foo.b);
Assert.AreEqual('0', foo.c);
}
[Test(Description = "http://jira.springframework.org/browse/SPRNET-992")]
public void ShouldPickSingleArgConstructor()
{
var args = new object[] {"b"};
var best = ReflectionUtils.GetConstructorByArgumentValues(typeof (Foo).GetConstructors(), args);
var foo = (Foo) best.Invoke(args);
Assert.AreEqual("b", foo.a);
Assert.AreEqual(-1, foo.b);
Assert.AreEqual('0', foo.c);
}
[Test]
public void GetParameterTypes()
{
var expectedParameterTypes = new Type[] {typeof (string)};
var method = typeof (ReflectionUtilsObject).GetMethod("BadSpanglish");
var parameterTypes = ReflectionUtils.GetParameterTypes(method);
Assert.IsTrue(ArrayUtils.AreEqual(expectedParameterTypes, parameterTypes));
}
[Test]
[ExpectedException(typeof (ArgumentNullException))]
public void GetParameterTypesWithNullMethodInfo()
{
ReflectionUtils.GetParameterTypes((MethodInfo) null);
}
[Test]
[ExpectedException(typeof (ArgumentNullException))]
public void GetParameterTypesWithNullParametersArgs()
{
ReflectionUtils.GetParameterTypes((ParameterInfo[]) null);
}
[Test]
[ExpectedException(typeof (ArgumentNullException))]
public void GetMatchingMethodsWithNullTypeToFindOn()
{
ReflectionUtils.GetMatchingMethods(null, new MethodInfo[] {}, true);
}
[Test]
[ExpectedException(typeof (ArgumentNullException))]
public void GetMatchingMethodsWithNullMethodsToFind()
{
ReflectionUtils.GetMatchingMethods(GetType(), null, true);
}
[Test]
public void GetMatchingMethodsWithPerfectMatch()
{
var clonesMethods =
typeof (ReflectionUtilsObjectClone).GetMethods(BindingFlags.Public | BindingFlags.DeclaredOnly |
BindingFlags.Instance);
var foundMethods = ReflectionUtils.GetMatchingMethods(typeof (ReflectionUtilsObject), clonesMethods, true);
Assert.AreEqual(clonesMethods.Length, foundMethods.Length);
}
[Test]
[ExpectedException(typeof (Exception))]
public void GetMatchingMethodsWithBadMatchStrict()
{
// lets include a protected method that ain't declared on the ReflectionUtilsObject class...
var clonesMethods =
typeof (ReflectionUtilsObjectClone).GetMethods(BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.DeclaredOnly | BindingFlags.Instance);
ReflectionUtils.GetMatchingMethods(typeof (ReflectionUtilsObject), clonesMethods, true);
}
[Test]
public void GetMatchingMethodsWithBadMatchNotStrict()
{
// lets include a protected method that ain't declared on the ReflectionUtilsObject class...
var clonesMethods =
typeof (ReflectionUtilsObjectClone).GetMethods(BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.DeclaredOnly | BindingFlags.Instance);
var foundMethods = ReflectionUtils.GetMatchingMethods(typeof (ReflectionUtilsObject), clonesMethods, false);
// obviously is not strict, 'cos we got here without throwing an exception...
Assert.AreEqual(clonesMethods.Length, foundMethods.Length);
}
[Test]
[ExpectedException(typeof (Exception))]
public void GetMatchingMethodsWithBadReturnTypeMatchStrict()
{
// lets include a method that return type is different...
var clonesMethods =
typeof (ReflectionUtilsObjectBadClone).GetMethods(BindingFlags.Public | BindingFlags.DeclaredOnly |
BindingFlags.Instance);
ReflectionUtils.GetMatchingMethods(typeof (ReflectionUtilsObject), clonesMethods, true);
}
[Test]
public void GetMatchingMethodsWithBadReturnTypeMatchNotStrict()
{
// lets include a method that return type is different...
var clonesMethods =
typeof (ReflectionUtilsObjectBadClone).GetMethods(BindingFlags.Public | BindingFlags.DeclaredOnly |
BindingFlags.Instance);
var foundMethods = ReflectionUtils.GetMatchingMethods(typeof (ReflectionUtilsObject), clonesMethods, false);
// obviously is not strict, 'cos we got here without throwing an exception...
Assert.AreEqual(clonesMethods.Length, foundMethods.Length);
}
[Test]
public void ParameterTypesMatch()
{
var method = typeof (ReflectionUtilsObject).GetMethod("Spanglish");
var types = new Type[] {typeof (string), typeof (object[])};
Assert.IsTrue(ReflectionUtils.ParameterTypesMatch(method, types));
}
[Test]
public void ParameterTypesDontMatchWithNonMatchingArgs()
{
var types = new Type[] {typeof (string), typeof (object[])};
var method = typeof (ReflectionUtilsObject).GetMethod("BadSpanglish");
Assert.IsFalse(ReflectionUtils.ParameterTypesMatch(method, types));
method = typeof (ReflectionUtilsObject).GetMethod("WickedSpanglish");
Assert.IsFalse(ReflectionUtils.ParameterTypesMatch(method, types));
}
[Test]
public void GetDefaultValue()
{
Assert.IsNull(ReflectionUtils.GetDefaultValue(GetType()));
Assert.AreEqual(Cuts.Superficial, ReflectionUtils.GetDefaultValue(typeof (Cuts)));
Assert.AreEqual(false, ReflectionUtils.GetDefaultValue(typeof (bool)));
Assert.AreEqual(DateTime.MinValue, ReflectionUtils.GetDefaultValue(typeof (DateTime)));
Assert.AreEqual(Char.MinValue, ReflectionUtils.GetDefaultValue(typeof (char)));
Assert.AreEqual(0, ReflectionUtils.GetDefaultValue(typeof (long)));
Assert.AreEqual(0, ReflectionUtils.GetDefaultValue(typeof (int)));
Assert.AreEqual(0, ReflectionUtils.GetDefaultValue(typeof (short)));
}
[Test]
public void PropertyIsIndexer()
{
Assert.IsTrue(ReflectionUtils.PropertyIsIndexer("Item", typeof (TestObject)));
//Assert.IsFalse(ReflectionUtils.PropertyIsIndexer("Item", typeof(SideEffectObject)));
//Assert.IsFalse(ReflectionUtils.PropertyIsIndexer("Count", typeof(SideEffectObject)));
Assert.IsTrue(ReflectionUtils.PropertyIsIndexer("MyItem", typeof (ObjectWithNonDefaultIndexerName)));
}
[Test]
public void MethodIsOnOneOfTheseInterfaces()
{
var method = typeof (ReflectionUtilsObject).GetMethod("Spanglish");
Assert.IsTrue(ReflectionUtils.MethodIsOnOneOfTheseInterfaces(method, new Type[] {typeof (IFoo)}));
}
[Test]
[ExpectedException(typeof (ArgumentException))]
public void MethodIsOnOneOfTheseInterfacesWithNonInterfaceType()
{
var method = typeof (ReflectionUtilsObject).GetMethod("Spanglish");
Assert.IsFalse(ReflectionUtils.MethodIsOnOneOfTheseInterfaces(method, new Type[] {GetType()}));
}
[Test]
[ExpectedException(typeof (ArgumentNullException))]
public void MethodIsOnOneOfTheseInterfacesWithNullMethod()
{
MethodInfo method = null;
Assert.IsFalse(ReflectionUtils.MethodIsOnOneOfTheseInterfaces(method, new Type[] {GetType()}));
}
[Test]
public void MethodIsOnOneOfTheseInterfacesWithNullTypes()
{
var method = typeof (ReflectionUtilsObject).GetMethod("Spanglish");
Assert.IsFalse(ReflectionUtils.MethodIsOnOneOfTheseInterfaces(method, null));
}
//[Test]
//public void MethodIsOnOneOfTheseInterfacesMultiple()
//{
// MethodInfo method = typeof(RequiredTestObject).GetMethod("set_ObjectFactory");
// Assert.IsNotNull(method, "Could not get setter property for ObjectFactory");
// Assert.IsTrue(ReflectionUtils.MethodIsOnOneOfTheseInterfaces(method, new Type[] { typeof(IObjectNameAware), typeof(IObjectFactoryAware) }));
//}
[Test]
[ExpectedException(typeof (ArgumentNullException))]
public void ParameterTypesMatchWithNullArgs()
{
ReflectionUtils.ParameterTypesMatch(null, null);
}
[Test]
public void GetSignature()
{
var method = typeof (ReflectionUtilsObject).GetMethod("Spanglish");
var list = new ArrayList();
foreach (var p in method.GetParameters())
{
list.Add(p.ParameterType);
}
var expected = "Solenoid.Expressions.Tests.Util.ReflectionUtilsObject::Spanglish(System.String,System.Object[])";
var pTypes = (Type[]) list.ToArray(typeof (Type));
var actual = ReflectionUtils.GetSignature(method.DeclaringType, method.Name, pTypes);
Assert.AreEqual(expected, actual);
}
[Test]
public void ToInterfaceArrayFromType()
{
var expected = new Type[] {typeof (IFoo), typeof (IBar)};
var actual = ReflectionUtils.ToInterfaceArray(typeof (IBar));
Assert.AreEqual(expected.Length, actual.Count);
Assert.AreEqual(expected[0], actual[0]);
Assert.AreEqual(expected[1], actual[1]);
}
[Test]
[ExpectedException(typeof (ArgumentException))]
public void ToInterfaceArrayFromTypeWithNonInterface()
{
ReflectionUtils.ToInterfaceArray(typeof (ExplicitFoo));
}
[Test]
public void GetMethod()
{
var actual = ReflectionUtils.GetMethod(
typeof (ReflectionUtilsObject),
"Spanglish",
new Type[] {typeof (string), typeof (object[])});
Assert.IsNotNull(actual);
}
[Test]
public void GetMethodWithExplicitInterfaceMethod()
{
var actual = ReflectionUtils.GetMethod(
typeof (ExplicitFoo),
"Solenoid.Expressions.Tests.Util.IFoo.Spanglish",
new Type[] {typeof (string), typeof (object[])});
Assert.IsNotNull(actual);
}
[Test]
public void GetMethodIsCaseInsensitive()
{
var actual = ReflectionUtils.GetMethod(
typeof (ReflectionUtilsObject),
"spAngLISh",
new Type[] {typeof (string), typeof (object[])});
Assert.IsNotNull(actual, "ReflectionUtils.GetMethod would appear to be case sensitive.");
}
[Test]
[ExpectedException(typeof (ArgumentException),
ExpectedMessage = "[Solenoid.Expressions.Tests.Util.ReflectionUtilsTests] does not derive from the [System.Attribute] class.")]
public void CreateCustomAttributeForNonAttributeType()
{
ReflectionUtils.CreateCustomAttribute(GetType());
}
[Test]
[ExpectedException(typeof (ArgumentNullException))]
public void CreateCustomAttributeWithNullType()
{
ReflectionUtils.CreateCustomAttribute((Type) null);
}
[Test]
public void CreateCustomAttributeSunnyDayScenarios()
{
CustomAttributeBuilder builder = null;
builder = ReflectionUtils.CreateCustomAttribute(typeof (MyCustomAttribute));
Assert.IsNotNull(builder);
builder = ReflectionUtils.CreateCustomAttribute(typeof (MyCustomAttribute), "Rick");
Assert.IsNotNull(builder);
builder = ReflectionUtils.CreateCustomAttribute(typeof (MyCustomAttribute), "Rick");
Assert.IsNotNull(builder);
builder = ReflectionUtils.CreateCustomAttribute(new MyCustomAttribute("Rick"));
Assert.IsNotNull(builder);
builder = ReflectionUtils.CreateCustomAttribute(typeof (MyCustomAttribute), new MyCustomAttribute("Rick"));
Assert.IsNotNull(builder);
builder = ReflectionUtils.CreateCustomAttribute(typeof (MyCustomAttribute), new object[] {"Rick"},
new MyCustomAttribute("Evans"));
Assert.IsNotNull(builder);
// TODO : actually emit the attribute and check it...
}
[Test]
public void CreatCustomAttriubtesFromCustomAttributeData()
{
var control = typeof (Control);
var mi = control.GetMethod("get_Font");
var attributes = CustomAttributeData.GetCustomAttributes(mi.ReturnParameter);
CustomAttributeBuilder builder = null;
foreach (var customAttributeData in attributes)
{
builder = ReflectionUtils.CreateCustomAttribute(customAttributeData);
Assert.IsNotNull(builder);
}
}
[Test]
public void CreatCustomAttriubtesFromCustomAttributeDataWithSingleEnum()
{
var mi = typeof (TestClassHavingAttributeWithEnum).GetMethod("SomeMethod");
var attributes = CustomAttributeData.GetCustomAttributes(mi);
CustomAttributeBuilder builder = null;
foreach (var customAttributeData in attributes)
{
builder = ReflectionUtils.CreateCustomAttribute(customAttributeData);
Assert.IsNotNull(builder);
}
}
[Test]
public void CreatCustomAttriubtesFromCustomAttributeDataWithArrayOfEnumsSetOnProperty()
{
var mi = typeof (TestClassHavingAttributeWithEnumArraySetOnProperty).GetMethod("SomeMethod");
var attributes = CustomAttributeData.GetCustomAttributes(mi);
CustomAttributeBuilder builder = null;
foreach (var customAttributeData in attributes)
{
builder = ReflectionUtils.CreateCustomAttribute(customAttributeData);
Assert.IsNotNull(builder);
}
}
[Test]
public void CreatCustomAttriubtesFromCustomAttributeDataWithArrayOfEnumsSetInConstructor()
{
var mi = typeof (TestClassHavingAttributeWithEnumArraySetInConstructor).GetMethod("SomeMethod");
var attributes = CustomAttributeData.GetCustomAttributes(mi);
CustomAttributeBuilder builder = null;
foreach (var customAttributeData in attributes)
{
builder = ReflectionUtils.CreateCustomAttribute(customAttributeData);
Assert.IsNotNull(builder);
}
}
[Test]
public void CreatCustomAttriubtesFromCustomAttributeDataWithSimpleTypeSetInConstructor()
{
var mi = typeof (TestClassHavingAttributeWithSimpleTypeSetInConstructor).GetMethod("SomeMethod");
var attributes = CustomAttributeData.GetCustomAttributes(mi);
CustomAttributeBuilder builder = null;
foreach (var customAttributeData in attributes)
{
builder = ReflectionUtils.CreateCustomAttribute(customAttributeData);
Assert.IsNotNull(builder);
}
}
[Test]
public void CreatCustomAttriubtesFromCustomAttributeDataWithGenericCollectionTypeSetInConstructor()
{
var mi = typeof (TestClassHavingAttributeWithGenericCollectionTypeSetInConstructor).GetMethod("SomeMethod");
var attributes = CustomAttributeData.GetCustomAttributes(mi);
CustomAttributeBuilder builder = null;
foreach (var customAttributeData in attributes)
{
builder = ReflectionUtils.CreateCustomAttribute(customAttributeData);
Assert.IsNotNull(builder);
}
}
internal interface IHaveSomeMethod
{
void SomeMethod();
}
internal class TestClassHavingAttributeWithEnum : IHaveSomeMethod
{
[AttributeWithEnum(SomeProperty = TheTestEnumThing.One)]
public void SomeMethod()
{
}
}
internal class TestClassHavingAttributeWithEnumArraySetInConstructor : IHaveSomeMethod
{
[AttributeWithEnumArraySetInConstructor(new TheTestEnumThing[] {TheTestEnumThing.One, TheTestEnumThing.Two})]
public void SomeMethod()
{
}
}
internal class TestClassHavingAttributeWithSimpleTypeSetInConstructor : IHaveSomeMethod
{
[AttributeWithType(typeof (int))]
public void SomeMethod()
{
}
}
internal class TestClassHavingAttributeWithGenericCollectionTypeSetInConstructor : IHaveSomeMethod
{
[AttributeWithType(typeof (List<int>))]
public void SomeMethod()
{
}
}
internal class TestClassHavingAttributeWithEnumArraySetOnProperty : IHaveSomeMethod
{
[AttributeWithEnumArray(SomeProperty = new TheTestEnumThing[] {TheTestEnumThing.One, TheTestEnumThing.Three})]
public void SomeMethod()
{
}
}
internal enum TheTestEnumThing
{
One,
Two,
Three
}
internal class AttributeWithTypeAttribute : Attribute
{
public AttributeWithTypeAttribute(Type T)
{
}
}
internal class AttributeWithEnumArrayAttribute : Attribute
{
public TheTestEnumThing[] SomeProperty { get; set; }
}
internal class AttributeWithEnumArraySetInConstructorAttribute : Attribute
{
/// <summary>
/// Initializes a new instance of the AttributeWithEnumArraySetInConstructorAttribute class.
/// </summary>
public AttributeWithEnumArraySetInConstructorAttribute(TheTestEnumThing[] things)
{
}
}
private class AttributeWithEnumAttribute : Attribute
{
public TheTestEnumThing SomeProperty { get; set; }
}
[Test]
public void CreateCustomAttributeUsingDefaultValuesForTheConstructor()
{
CustomAttributeBuilder builder = null;
builder = ReflectionUtils.CreateCustomAttribute(typeof (AnotherCustomAttribute));
Assert.IsNotNull(builder);
var att
= (AnotherCustomAttribute) CheckForPresenceOfCustomAttribute(builder, typeof (AnotherCustomAttribute));
Assert.IsNull(att.Name);
Assert.AreEqual(0, att.Age);
Assert.IsFalse(att.HasSwallowedExplosives);
}
[Test]
public void CreateCustomAttributeFromSourceAttribute()
{
CustomAttributeBuilder builder = null;
var source = new AnotherCustomAttribute("Rick", 30, true);
builder = ReflectionUtils.CreateCustomAttribute(source);
Assert.IsNotNull(builder);
var att
= (AnotherCustomAttribute) CheckForPresenceOfCustomAttribute(builder, typeof (AnotherCustomAttribute));
Assert.AreEqual(source.Name, att.Name);
Assert.AreEqual(source.Age, att.Age);
Assert.AreEqual(source.HasSwallowedExplosives, att.HasSwallowedExplosives);
}
[Test]
public void CreateCustomAttributeUsingExplicitValuesForTheConstructor()
{
CustomAttributeBuilder builder = null;
const string expectedName = "Rick";
const int expectedAge = 30;
builder = ReflectionUtils.CreateCustomAttribute(typeof (AnotherCustomAttribute), new object[]
{
expectedName, expectedAge, true
});
Assert.IsNotNull(builder);
var att
= (AnotherCustomAttribute) CheckForPresenceOfCustomAttribute(builder, typeof (AnotherCustomAttribute));
Assert.AreEqual(expectedName, att.Name);
Assert.AreEqual(expectedAge, att.Age);
Assert.IsTrue(att.HasSwallowedExplosives);
}
[Test]
public void CreateCustomAttributeUsingExplicitValuesForTheConstructorAndASourceAttribute()
{
CustomAttributeBuilder builder = null;
const string expectedName = "Rick";
const int expectedAge = 30;
var source = new AnotherCustomAttribute(expectedName, expectedAge, false);
builder = ReflectionUtils.CreateCustomAttribute(typeof (AnotherCustomAttribute), new object[]
{
"Hoop", 2, true
}, source);
Assert.IsNotNull(builder);
var att
= (AnotherCustomAttribute) CheckForPresenceOfCustomAttribute(builder, typeof (AnotherCustomAttribute));
Assert.AreEqual(expectedName, att.Name);
Assert.AreEqual(expectedAge, att.Age);
Assert.IsFalse(att.HasSwallowedExplosives);
}
[Test]
public void HasAtLeastOneMethodWithName()
{
var testType = typeof (ExtendedReflectionUtilsObject);
// declared method...
Assert.IsTrue(ReflectionUtils.HasAtLeastOneMethodWithName(testType, "Declared"));
// case insensitive method...
Assert.IsTrue(ReflectionUtils.HasAtLeastOneMethodWithName(testType, "deCLAReD"));
// superclass method...
Assert.IsTrue(ReflectionUtils.HasAtLeastOneMethodWithName(testType, "Spanglish"));
// static method...
Assert.IsTrue(ReflectionUtils.HasAtLeastOneMethodWithName(testType, "Static"));
// protected method...
Assert.IsTrue(ReflectionUtils.HasAtLeastOneMethodWithName(testType, "Protected"));
// non existent method...
Assert.IsFalse(ReflectionUtils.HasAtLeastOneMethodWithName(testType, "Sponglish"));
// null type...
Assert.IsFalse(ReflectionUtils.HasAtLeastOneMethodWithName(null, "Spanglish"));
// null method name...
Assert.IsFalse(ReflectionUtils.HasAtLeastOneMethodWithName(testType, null));
// empty method name...
Assert.IsFalse(ReflectionUtils.HasAtLeastOneMethodWithName(testType, ""));
// all nulls...
Assert.IsFalse(ReflectionUtils.HasAtLeastOneMethodWithName(null, null));
}
[Test]
[ExpectedException(typeof (NullReferenceException))]
public void GetTypeOfOrTypeWithNull()
{
ReflectionUtils.TypeOfOrType(null);
}
[Test]
public void GetTypeOfOrType()
{
Assert.AreEqual(typeof (string), ReflectionUtils.TypeOfOrType(typeof (string)));
}
[Test]
public void GetTypeOfOrTypeWithNonNullType()
{
Assert.AreEqual(typeof (string), ReflectionUtils.TypeOfOrType(string.Empty));
}
[Test]
public void GetTypes()
{
var actual = ReflectionUtils.GetTypes(
new object[] {1, "I've never been to Taco Bell (sighs).", new ReflectionUtilsObject()});
var expected = new Type[]
{
typeof (int),
typeof (string),
typeof (ReflectionUtilsObject),
};
Assert.IsTrue(ArrayUtils.AreEqual(expected, actual),
"The ReflectionUtils.GetTypes method did not return a correct Type [] array. Yep, that's as helpful as it gets.");
}
[Test]
public void GetTypesWithEmptyArrayArgument()
{
var actual = ReflectionUtils.GetTypes(new object[] {});
Assert.IsNotNull(actual,
"The ReflectionUtils.GetTypes method returned null when given an empty array. Must return an empty Type [] array.");
Assert.IsTrue(actual.Length == 0,
"The ReflectionUtils.GetTypes method returned a Type [] that had some elements in it when given an empty array. Must return an empty Type [] array.");
}
[Test]
public void GetTypesWithNullArrayArgument()
{
var actual = ReflectionUtils.GetTypes(null);
Assert.IsNotNull(actual,
"The ReflectionUtils.GetTypes method returned null when given null. Must return an empty Type [] array.");
Assert.IsTrue(actual.Length == 0,
"The ReflectionUtils.GetTypes method returned a Type [] that had some elements in it when given null. Must return an empty Type [] array.");
}
[Test]
[ExpectedException(typeof (ArgumentException))]
public void GetDefaultValueWithZeroValueEnumType()
{
ReflectionUtils.GetDefaultValue(typeof (EnumWithNoValues));
}
[Test]
public void GetParameterTypesWithMethodThatHasRefParameters()
{
var method = GetType().GetMethod("Add");
var types = ReflectionUtils.GetParameterTypes(method);
Assert.IsNotNull(types);
Assert.AreEqual(2, types.Length);
// first method parameter is byRef, so type name must end in '&'
Assert.AreEqual("System.Int32&", types[0].FullName);
Assert.AreEqual("System.Int32", types[1].FullName);
}
[Test]
public void GetMethodByArgumentValuesCanResolveWhenAmbiguousMatchIsOnlyDifferentiatedByParams()
{
var typedArg = new GetMethodByArgumentValuesTarget.DummyArgumentType[] {};
var foo = new GetMethodByArgumentValuesTarget(1, typedArg);
var type = typeof (GetMethodByArgumentValuesTarget);
var candidateMethods = new MethodInfo[]
{
type.GetMethod("ParamOverloadedMethod", new Type[] {typeof (string), typeof (string), typeof (string)})
, type.GetMethod("ParamOverloadedMethod", new Type[] {typeof (string), typeof (string), typeof (bool)})
,
type.GetMethod("ParamOverloadedMethod",
new Type[] {typeof (string), typeof (string), typeof (string), typeof (string), typeof (object[])})
};
// ensure noone changed our test class
Assert.IsNotNull(candidateMethods[0]);
Assert.IsNotNull(candidateMethods[1]);
Assert.IsNotNull(candidateMethods[2]);
Assert.AreEqual("ThreeStringsOverload", foo.ParamOverloadedMethod(string.Empty, string.Empty, string.Empty));
Assert.AreEqual("TwoStringsAndABoolOverload", foo.ParamOverloadedMethod(string.Empty, string.Empty, default(bool)));
Assert.AreEqual("FourStringsAndAParamsCollectionOverload",
foo.ParamOverloadedMethod(string.Empty, string.Empty, string.Empty, string.Empty, typedArg));
var resolvedMethod = ReflectionUtils.GetMethodByArgumentValues(candidateMethods,
new object[] {string.Empty, string.Empty, string.Empty, string.Empty, typedArg});
Assert.AreSame(candidateMethods[2], resolvedMethod);
}
[Test]
public void GetMethodByArgumentValuesResolvesToExactMatchIfAvailable()
{
var typedArg = new GetMethodByArgumentValuesTarget.DummyArgumentType[] {};
var foo = new GetMethodByArgumentValuesTarget(1, typedArg);
var type = typeof (GetMethodByArgumentValuesTarget);
var candidateMethods = new MethodInfo[]
{
type.GetMethod("MethodWithSimilarArguments", new Type[] {typeof (int), typeof (ICollection)})
,
type.GetMethod("MethodWithSimilarArguments",
new Type[] {typeof (int), typeof (GetMethodByArgumentValuesTarget.DummyArgumentType[])})
, type.GetMethod("MethodWithSimilarArguments", new Type[] {typeof (int), typeof (object[])})
};
// ensure noone changed our test class
Assert.IsNotNull(candidateMethods[0]);
Assert.IsNotNull(candidateMethods[1]);
Assert.IsNotNull(candidateMethods[2]);
Assert.AreEqual("ParamArrayMatch", foo.MethodWithSimilarArguments(1, new object()));
Assert.AreEqual("ExactMatch",
foo.MethodWithSimilarArguments(1, (GetMethodByArgumentValuesTarget.DummyArgumentType[]) typedArg));
Assert.AreEqual("AssignableMatch", foo.MethodWithSimilarArguments(1, (ICollection) typedArg));
var resolvedMethod = ReflectionUtils.GetMethodByArgumentValues(candidateMethods, new object[] {1, typedArg});
Assert.AreSame(candidateMethods[1], resolvedMethod);
}
[Test]
public void GetMethodByArgumentValuesMatchesNullableArgs()
{
var typedArg = new GetMethodByArgumentValuesTarget.DummyArgumentType[] {};
var foo = new GetMethodByArgumentValuesTarget(1, typedArg);
var type = typeof (GetMethodByArgumentValuesTarget);
var candidateMethods = new MethodInfo[]
{
type.GetMethod("MethodWithSimilarArguments", new Type[] {typeof (int), typeof (ICollection)})
,
type.GetMethod("MethodWithSimilarArguments",
new Type[] {typeof (int), typeof (GetMethodByArgumentValuesTarget.DummyArgumentType[])})
, type.GetMethod("MethodWithSimilarArguments", new Type[] {typeof (int), typeof (object[])})
, type.GetMethod("MethodWithNullableArgument", new Type[] {typeof (int?)})
};
// ensure noone changed our test class
Assert.IsNotNull(candidateMethods[0]);
Assert.IsNotNull(candidateMethods[1]);
Assert.IsNotNull(candidateMethods[2]);
Assert.IsNotNull(candidateMethods[3]);
Assert.AreEqual("ParamArrayMatch", foo.MethodWithSimilarArguments(1, new object()));
Assert.AreEqual("ExactMatch",
foo.MethodWithSimilarArguments(1, (GetMethodByArgumentValuesTarget.DummyArgumentType[]) typedArg));
Assert.AreEqual("AssignableMatch", foo.MethodWithSimilarArguments(1, (ICollection) typedArg));
Assert.AreEqual("NullableArgumentMatch", foo.MethodWithNullableArgument(null));
var resolvedMethod = ReflectionUtils.GetMethodByArgumentValues(candidateMethods, new object[] {null});
Assert.AreSame(candidateMethods[3], resolvedMethod);
}
[Test]
public void GetConstructorByArgumentValuesResolvesToExactMatchIfAvailable()
{
var typedArg = new GetMethodByArgumentValuesTarget.DummyArgumentType[] {};
var type = typeof (GetMethodByArgumentValuesTarget);
var candidateConstructors = new ConstructorInfo[]
{
type.GetConstructor(new Type[] {typeof (int), typeof (ICollection)})
, type.GetConstructor(new Type[] {typeof (int), typeof (GetMethodByArgumentValuesTarget.DummyArgumentType[])})
, type.GetConstructor(new Type[] {typeof (int), typeof (object[])})
};
// ensure noone changed our test class
Assert.IsNotNull(candidateConstructors[0]);
Assert.IsNotNull(candidateConstructors[1]);
Assert.IsNotNull(candidateConstructors[2]);
Assert.AreEqual("ParamArrayMatch", new GetMethodByArgumentValuesTarget(1, new object()).SelectedConstructor);
Assert.AreEqual("ExactMatch",
new GetMethodByArgumentValuesTarget(1, (GetMethodByArgumentValuesTarget.DummyArgumentType[]) typedArg)
.SelectedConstructor);
Assert.AreEqual("AssignableMatch", new GetMethodByArgumentValuesTarget(1, (ICollection) typedArg).SelectedConstructor);
var resolvedConstructor = ReflectionUtils.GetConstructorByArgumentValues(candidateConstructors,
new object[] {1, typedArg});
Assert.AreSame(candidateConstructors[1], resolvedConstructor);
}
[Test]
public void GetInterfaces()
{
Assert.AreEqual(
typeof (TestObject).GetInterfaces().Length,
ReflectionUtils.GetInterfaces(typeof (TestObject)).Length);
Assert.AreEqual(1, ReflectionUtils.GetInterfaces(typeof (IInterface1)).Length);
Assert.AreEqual(4, ReflectionUtils.GetInterfaces(typeof (IInterface2)).Length);
}
public interface IInterface1
{
}
public interface IInterface2 : IInterface3
{
}
public interface IInterface3 : IInterface4, IInterface5
{
}
public interface IInterface4
{
}
public interface IInterface5
{
}
[Test]
public void IsTypeVisibleWithInternalType()
{
var type = typeof (InternalType);
Assert.IsFalse(ReflectionUtils.IsTypeVisible(type));
}
[Test]
public void IsTypeVisibleWithPublicNestedTypeOnInternalType()
{
var type = typeof (InternalType.PublicNestedType);
Assert.IsFalse(ReflectionUtils.IsTypeVisible(type));
}
[Test]
public void IsTypeVisibleWithInternalNestedTypeOnInternalType()
{
var type = typeof (InternalType.InternalNestedType);
Assert.IsFalse(ReflectionUtils.IsTypeVisible(type));
}
[Test]
public void IsTypeVisibleWithProtectedInternalNestedTypeOnInternalType()
{
var type = typeof (InternalType.ProtectedInternalNestedType);
Assert.IsFalse(ReflectionUtils.IsTypeVisible(type));
}
[Test]
public void IsTypeVisibleWithProtectedNestedTypeOnInternalType()
{
var type = typeof (InternalType).GetNestedType("ProtectedNestedType", BindingFlags.NonPublic);
Assert.IsFalse(ReflectionUtils.IsTypeVisible(type));
}
[Test]
public void IsTypeVisibleWithPrivateNestedTypeOnInternalType()
{
var type = typeof (InternalType).GetNestedType("PrivateNestedType", BindingFlags.NonPublic);
Assert.IsFalse(ReflectionUtils.IsTypeVisible(type));
}
[Test]
public void IsTypeVisibleWithPublicType()
{
var type = typeof (PublicType);
Assert.IsTrue(ReflectionUtils.IsTypeVisible(type));
}
[Test]
public void IsTypeVisibleWithPublicNestedTypeOnPublicType()
{
var type = typeof (PublicType.PublicNestedType);
Assert.IsTrue(ReflectionUtils.IsTypeVisible(type));
}
[Test]
public void IsTypeVisibleWithInternalNestedTypeOnPublicType()
{
var type = typeof (PublicType.InternalNestedType);
Assert.IsFalse(ReflectionUtils.IsTypeVisible(type));
}
[Test]
public void IsTypeVisibleWithProtectedInternalNestedTypeOnPublicType()
{
var type = typeof (PublicType.ProtectedInternalNestedType);
Assert.IsFalse(ReflectionUtils.IsTypeVisible(type));
}
[Test]
public void IsTypeVisibleWithProtectedNestedTypeOnPublicType()
{
var type = typeof (PublicType).GetNestedType("ProtectedNestedType", BindingFlags.NonPublic);
Assert.IsFalse(ReflectionUtils.IsTypeVisible(type));
}
[Test]
public void IsTypeVisibleWithPrivateNestedTypeOnPublicType()
{
var type = typeof (PublicType).GetNestedType("PrivateNestedType", BindingFlags.NonPublic);
Assert.IsFalse(ReflectionUtils.IsTypeVisible(type));
}
private static readonly string FRIENDLY_ASSEMBLY_NAME = "ReflectionUtils.IsTypeVisible.AssemblyTestName";
[Test]
public void IsTypeVisibleFromFriendlyAssemblyWithInternalType()
{
var type = typeof (InternalType);
Assert.IsTrue(ReflectionUtils.IsTypeVisible(type, FRIENDLY_ASSEMBLY_NAME));
}
[Test]
public void IsTypeVisibleFromFriendlyAssemblyWithPublicNestedTypeOnInternalType()
{
var type = typeof (InternalType.PublicNestedType);
Assert.IsTrue(ReflectionUtils.IsTypeVisible(type, FRIENDLY_ASSEMBLY_NAME));
}
[Test]
public void IsTypeVisibleFromFriendlyAssemblyWithInternalNestedTypeOnInternalType()
{
var type = typeof (InternalType.InternalNestedType);
Assert.IsTrue(ReflectionUtils.IsTypeVisible(type, FRIENDLY_ASSEMBLY_NAME));
}
[Test]
public void IsTypeVisibleFromFriendlyAssemblyWithProtectedInternalNestedTypeOnInternalType()
{
var type = typeof (InternalType.ProtectedInternalNestedType);
Assert.IsTrue(ReflectionUtils.IsTypeVisible(type, FRIENDLY_ASSEMBLY_NAME));
}
[Test]
public void IsTypeVisibleFromFriendlyAssemblyWithProtectedNestedTypeOnInternalType()
{
var type = typeof (InternalType).GetNestedType("ProtectedNestedType", BindingFlags.NonPublic);
Assert.IsFalse(ReflectionUtils.IsTypeVisible(type, FRIENDLY_ASSEMBLY_NAME));
}
[Test]
public void IsTypeVisibleFromFriendlyAssemblyWithPrivateNestedTypeOnInternalType()
{
var type = typeof (InternalType).GetNestedType("PrivateNestedType", BindingFlags.NonPublic);
Assert.IsFalse(ReflectionUtils.IsTypeVisible(type, FRIENDLY_ASSEMBLY_NAME));
}
[Test]
public void IsTypeVisibleFromFriendlyAssemblyWithPublicType()
{
var type = typeof (PublicType);
Assert.IsTrue(ReflectionUtils.IsTypeVisible(type, FRIENDLY_ASSEMBLY_NAME));
}
[Test]
public void IsTypeVisibleFromFriendlyAssemblyWithPublicNestedTypeOnPublicType()
{
var type = typeof (PublicType.PublicNestedType);
Assert.IsTrue(ReflectionUtils.IsTypeVisible(type, FRIENDLY_ASSEMBLY_NAME));
}
[Test]
public void IsTypeVisibleFromFriendlyAssemblyWithInternalNestedTypeOnPublicType()
{
var type = typeof (PublicType.InternalNestedType);
Assert.IsTrue(ReflectionUtils.IsTypeVisible(type, FRIENDLY_ASSEMBLY_NAME));
}
[Test]
public void IsTypeVisibleFromFriendlyAssemblyWithProtectedInternalNestedTypeOnPublicType()
{
var type = typeof (PublicType.ProtectedInternalNestedType);
Assert.IsTrue(ReflectionUtils.IsTypeVisible(type, FRIENDLY_ASSEMBLY_NAME));
}
[Test]
public void IsTypeVisibleFromFriendlyAssemblyWithProtectedNestedTypeOnPublicType()
{
var type = typeof (PublicType).GetNestedType("ProtectedNestedType", BindingFlags.NonPublic);
Assert.IsFalse(ReflectionUtils.IsTypeVisible(type, FRIENDLY_ASSEMBLY_NAME));
}
[Test]
public void IsTypeVisibleFromFriendlyAssemblyWithPrivateNestedTypeOnPublicType()
{
var type = typeof (PublicType).GetNestedType("PrivateNestedType", BindingFlags.NonPublic);
Assert.IsFalse(ReflectionUtils.IsTypeVisible(type, FRIENDLY_ASSEMBLY_NAME));
}
[Test]
public void IsTypeNullable_WhenTrue()
{
var type = typeof (int?);
Assert.That(ReflectionUtils.IsNullableType(type), Is.True);
}
[Test]
public void IsTypeNullable_WhenFalse()
{
var type = typeof (int);
Assert.That(ReflectionUtils.IsNullableType(type), Is.False);
}
[Test]
public void GetCustomAttributesOnType()
{
var attrs = ReflectionUtils.GetCustomAttributes(typeof (ClassWithAttributes));
// for some reason mono doesnt recognize
// System.Security.Permissions.SecurityPermission
// as a custom attribute
Assert.AreEqual(
SystemUtils.MonoRuntime ? 1 : 2,
attrs.Count);
}
[Test]
public void GetCustomAttributesOnMethod()
{
var attrs = ReflectionUtils.GetCustomAttributes(typeof (ClassWithAttributes).GetMethod("MethodWithAttributes"));
// for some reason mono doesnt recognize
// System.Security.Permissions.SecurityPermission
// as a custom attribute
Assert.AreEqual(
SystemUtils.MonoRuntime ? 1 : 2,
attrs.Count);
}
[Test]
public void GetExplicitBaseExceptionWithNoInnerException()
{
Exception appEx = new ApplicationException();
var ex = ReflectionUtils.GetExplicitBaseException(appEx);
Assert.AreEqual(ex, appEx);
}
[Test]
public void GetExplicitBaseExceptionWithInnerException()
{
Exception dbzEx = new DivideByZeroException();
Exception appEx = new ApplicationException("Test message", dbzEx);
var ex = ReflectionUtils.GetExplicitBaseException(appEx);
Assert.AreEqual(ex, dbzEx);
}
[Test]
public void GetExplicitBaseExceptionWithInnerExceptions()
{
Exception dbzEx = new DivideByZeroException();
Exception sEx = new SystemException("Test message", dbzEx);
Exception appEx = new ApplicationException("Test message", sEx);
var ex = ReflectionUtils.GetExplicitBaseException(appEx);
Assert.AreEqual(ex, dbzEx);
}
[Test]
public void GetExplicitBaseExceptionWithNullReferenceExceptionAsRootException()
{
Exception nrEx = new NullReferenceException();
Exception appEx = new ApplicationException("Test message", nrEx);
var ex = ReflectionUtils.GetExplicitBaseException(appEx);
Assert.AreEqual(ex, appEx);
}
[Test]
public void CanGetFriendlyNamesForGenericTypes()
{
var t = typeof (List<Dictionary<string, int>>);
Assert.AreEqual("System.Collections.Generic.List<System.Collections.Generic.Dictionary<string, int>>",
ReflectionUtils.GetTypeFriendlyName(t));
}
public int Add(ref int one, int two)
{
return one + two;
}
private Attribute CheckForPresenceOfCustomAttribute(
CustomAttributeBuilder attBuilder, Type attType)
{
var atts = ApplyAndGetCustomAttributes(attBuilder);
Assert.IsNotNull(atts);
Assert.IsTrue(atts.Length == 1);
var att = atts[0];
Assert.IsNotNull(att);
Assert.AreEqual(attType, att.GetType(), "Wrong Attribute applied to the class.");
return att;
}
private static Attribute[] ApplyAndGetCustomAttributes(CustomAttributeBuilder attBuilder)
{
var type = BuildTypeWithThisCustomAttribute(attBuilder);
var attributes = type.GetCustomAttributes(true);
return (Attribute[]) ArrayList.Adapter(attributes).ToArray(typeof (Attribute));
}
private static Type BuildTypeWithThisCustomAttribute(CustomAttributeBuilder attBuilder)
{
var assemblyName = new AssemblyName();
assemblyName.Name = "AnAssembly";
var asmBuilder = Thread.GetDomain().DefineDynamicAssembly(
assemblyName, AssemblyBuilderAccess.Run);
var modBuilder = asmBuilder.DefineDynamicModule("AModule");
var classBuilder = modBuilder.DefineType("AClass", TypeAttributes.Public);
classBuilder.SetCustomAttribute(attBuilder);
return classBuilder.CreateType();
}
}
public class PublicType
{
public class PublicNestedType
{
}
internal class InternalNestedType
{
}
protected internal class ProtectedInternalNestedType
{
}
protected class ProtectedNestedType
{
}
private class PrivateNestedType
{
}
}
internal class InternalType
{
public class PublicNestedType
{
}
internal class InternalNestedType
{
}
protected internal class ProtectedInternalNestedType
{
}
protected class ProtectedNestedType
{
}
private class PrivateNestedType
{
}
}
internal enum EnumWithNoValues
{
}
internal enum Cuts
{
Superficial,
Deep,
Severing
}
internal interface IBar : IFoo
{
}
internal interface IFoo
{
bool Spanglish(string foo, object[] args);
}
internal sealed class ExplicitFoo : IFoo
{
bool IFoo.Spanglish(string foo, object[] args)
{
return false;
}
}
internal class ReflectionUtilsObject : IComparable
{
public bool Spanglish(string foo, object[] args)
{
return false;
}
public bool BadSpanglish(string foo)
{
return false;
}
public bool WickedSpanglish(string foo, string bar)
{
return false;
}
/// <summary>
/// Explicit interface implementation for ReflectionUtils.GetMethod tests
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
int IComparable.CompareTo(object obj)
{
return 0;
}
}
internal sealed class ExtendedReflectionUtilsObject : ReflectionUtilsObject
{
public void Declared(string name)
{
}
public void Protected()
{
}
public static void Static()
{
}
}
/// <summary>
/// Exposes methods with the same names as the ReflectionUtilsObject, used in
/// the tests for the GetMatchingMethods method.
/// </summary>
internal class ReflectionUtilsObjectClone
{
public bool Spanglish(string foo, object[] args)
{
return false;
}
public bool BadSpanglish(string foo)
{
return false;
}
public bool WickedSpanglish(string foo, string bar)
{
return false;
}
protected void Bingo()
{
}
}
/// <summary>
/// Exposes methods with the same names as the ReflectionUtilsObject, used in
/// the tests for the GetMatchingMethods method.
/// </summary>
internal class ReflectionUtilsObjectBadClone
{
public bool Spanglish(string foo, object[] args)
{
return false;
}
public string BadSpanglish(string foo)
{
return foo;
}
public bool WickedSpanglish(string foo, string bar)
{
return false;
}
}
internal class GetMethodByArgumentValuesTarget
{
public class DummyArgumentType
{
}
public string SelectedConstructor;
public GetMethodByArgumentValuesTarget(int flag, params object[] values)
{
SelectedConstructor = "ParamArrayMatch";
}
public GetMethodByArgumentValuesTarget(int flag, DummyArgumentType[] bars)
{
SelectedConstructor = "ExactMatch";
}
public GetMethodByArgumentValuesTarget(int flag, ICollection bars)
{
SelectedConstructor = "AssignableMatch";
}
public string MethodWithSimilarArguments(int flags, params object[] args)
{
return "ParamArrayMatch";
}
public string MethodWithSimilarArguments(int flags, DummyArgumentType[] bars)
{
return "ExactMatch";
}
public string MethodWithSimilarArguments(int flags, ICollection bar)
{
return "AssignableMatch";
}
public string MethodWithNullableArgument(int? nullableInteger)
{
return "NullableArgumentMatch";
}
public string ParamOverloadedMethod(string s1, string s2, string s3)
{
return "ThreeStringsOverload";
}
public string ParamOverloadedMethod(string s1, string s2, bool b1)
{
return "TwoStringsAndABoolOverload";
}
public string ParamOverloadedMethod(string s1, string s2, string s3, string s4, params object[] args)
{
return "FourStringsAndAParamsCollectionOverload";
}
}
public sealed class MyCustomAttribute : Attribute
{
public MyCustomAttribute()
{
}
public MyCustomAttribute(string name)
{
_name = name;
}
public string Name
{
get { return _name; }
}
private readonly string _name;
}
/// <summary>
/// Used for testing that default values are supplied for the ctor args.
/// </summary>
public sealed class AnotherCustomAttribute : Attribute
{
public AnotherCustomAttribute(string name, int age, bool hasSwallowedExplosives)
{
Name = name;
Age = age;
HasSwallowedExplosives = hasSwallowedExplosives;
}
public string Name { get; set; }
public int Age { get; set; }
public bool HasSwallowedExplosives { get; set; }
}
public sealed class ObjectWithNonDefaultIndexerName
{
private readonly string[] _favoriteQuotes = new string[10];
[IndexerName("MyItem")]
public string this[int index]
{
get
{
if (index < 0 || index >= _favoriteQuotes.Length)
{
throw new ArgumentException("Index out of range");
}
return _favoriteQuotes[index];
}
set
{
if (index < 0 || index >= _favoriteQuotes.Length)
{
throw new ArgumentException("index is out of range.");
}
_favoriteQuotes[index] = value;
}
}
}
[MyCustom]
[SecurityPermission(SecurityAction.Demand)]
public sealed class ClassWithAttributes
{
[MyCustom]
[SecurityPermission(SecurityAction.Demand)]
public void MethodWithAttributes()
{
}
}
}
| |
/*
* 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.Runtime.Remoting.Lifetime;
using System.Threading;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using OpenSim.Region.ScriptEngine.Interfaces;
using OpenSim.Region.ScriptEngine.Shared.Api.Interfaces;
using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat;
using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger;
using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list;
using LSL_Rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion;
using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
using LSL_Vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3;
namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase
{
public partial class ScriptBaseClass : MarshalByRefObject
{
public ILSL_Api m_LSL_Functions;
public void ApiTypeLSL(IScriptApi api)
{
if (!(api is ILSL_Api))
return;
m_LSL_Functions = (ILSL_Api)api;
}
public void state(string newState)
{
m_LSL_Functions.state(newState);
}
//
// Script functions
//
public LSL_Integer llAbs(int i)
{
return m_LSL_Functions.llAbs(i);
}
public LSL_Float llAcos(double val)
{
return m_LSL_Functions.llAcos(val);
}
public void llAddToLandBanList(string avatar, double hours)
{
m_LSL_Functions.llAddToLandBanList(avatar, hours);
}
public void llAddToLandPassList(string avatar, double hours)
{
m_LSL_Functions.llAddToLandPassList(avatar, hours);
}
public void llAdjustSoundVolume(double volume)
{
m_LSL_Functions.llAdjustSoundVolume(volume);
}
public void llAllowInventoryDrop(int add)
{
m_LSL_Functions.llAllowInventoryDrop(add);
}
public LSL_Float llAngleBetween(LSL_Rotation a, LSL_Rotation b)
{
return m_LSL_Functions.llAngleBetween(a, b);
}
public void llApplyImpulse(LSL_Vector force, int local)
{
m_LSL_Functions.llApplyImpulse(force, local);
}
public void llApplyRotationalImpulse(LSL_Vector force, int local)
{
m_LSL_Functions.llApplyRotationalImpulse(force, local);
}
public LSL_Float llAsin(double val)
{
return m_LSL_Functions.llAsin(val);
}
public LSL_Float llAtan2(double x, double y)
{
return m_LSL_Functions.llAtan2(x, y);
}
public void llAttachToAvatar(int attachment)
{
m_LSL_Functions.llAttachToAvatar(attachment);
}
public LSL_Key llAvatarOnSitTarget()
{
return m_LSL_Functions.llAvatarOnSitTarget();
}
public LSL_Key llAvatarOnLinkSitTarget(int linknum)
{
return m_LSL_Functions.llAvatarOnLinkSitTarget(linknum);
}
public LSL_Rotation llAxes2Rot(LSL_Vector fwd, LSL_Vector left, LSL_Vector up)
{
return m_LSL_Functions.llAxes2Rot(fwd, left, up);
}
public LSL_Rotation llAxisAngle2Rot(LSL_Vector axis, double angle)
{
return m_LSL_Functions.llAxisAngle2Rot(axis, angle);
}
public LSL_Integer llBase64ToInteger(string str)
{
return m_LSL_Functions.llBase64ToInteger(str);
}
public LSL_String llBase64ToString(string str)
{
return m_LSL_Functions.llBase64ToString(str);
}
public void llBreakAllLinks()
{
m_LSL_Functions.llBreakAllLinks();
}
public void llBreakLink(int linknum)
{
m_LSL_Functions.llBreakLink(linknum);
}
public LSL_Integer llCeil(double f)
{
return m_LSL_Functions.llCeil(f);
}
public void llClearCameraParams()
{
m_LSL_Functions.llClearCameraParams();
}
public void llCloseRemoteDataChannel(string channel)
{
m_LSL_Functions.llCloseRemoteDataChannel(channel);
}
public LSL_Float llCloud(LSL_Vector offset)
{
return m_LSL_Functions.llCloud(offset);
}
public void llCollisionFilter(string name, string id, int accept)
{
m_LSL_Functions.llCollisionFilter(name, id, accept);
}
public void llCollisionSound(string impact_sound, double impact_volume)
{
m_LSL_Functions.llCollisionSound(impact_sound, impact_volume);
}
public void llCollisionSprite(string impact_sprite)
{
m_LSL_Functions.llCollisionSprite(impact_sprite);
}
public LSL_Float llCos(double f)
{
return m_LSL_Functions.llCos(f);
}
public void llCreateLink(string target, int parent)
{
m_LSL_Functions.llCreateLink(target, parent);
}
public LSL_List llCSV2List(string src)
{
return m_LSL_Functions.llCSV2List(src);
}
public LSL_List llDeleteSubList(LSL_List src, int start, int end)
{
return m_LSL_Functions.llDeleteSubList(src, start, end);
}
public LSL_String llDeleteSubString(string src, int start, int end)
{
return m_LSL_Functions.llDeleteSubString(src, start, end);
}
public void llDetachFromAvatar()
{
m_LSL_Functions.llDetachFromAvatar();
}
public LSL_Vector llDetectedGrab(int number)
{
return m_LSL_Functions.llDetectedGrab(number);
}
public LSL_Integer llDetectedGroup(int number)
{
return m_LSL_Functions.llDetectedGroup(number);
}
public LSL_Key llDetectedKey(int number)
{
return m_LSL_Functions.llDetectedKey(number);
}
public LSL_Integer llDetectedLinkNumber(int number)
{
return m_LSL_Functions.llDetectedLinkNumber(number);
}
public LSL_String llDetectedName(int number)
{
return m_LSL_Functions.llDetectedName(number);
}
public LSL_Key llDetectedOwner(int number)
{
return m_LSL_Functions.llDetectedOwner(number);
}
public LSL_Vector llDetectedPos(int number)
{
return m_LSL_Functions.llDetectedPos(number);
}
public LSL_Rotation llDetectedRot(int number)
{
return m_LSL_Functions.llDetectedRot(number);
}
public LSL_Integer llDetectedType(int number)
{
return m_LSL_Functions.llDetectedType(number);
}
public LSL_Vector llDetectedTouchBinormal(int index)
{
return m_LSL_Functions.llDetectedTouchBinormal(index);
}
public LSL_Integer llDetectedTouchFace(int index)
{
return m_LSL_Functions.llDetectedTouchFace(index);
}
public LSL_Vector llDetectedTouchNormal(int index)
{
return m_LSL_Functions.llDetectedTouchNormal(index);
}
public LSL_Vector llDetectedTouchPos(int index)
{
return m_LSL_Functions.llDetectedTouchPos(index);
}
public LSL_Vector llDetectedTouchST(int index)
{
return m_LSL_Functions.llDetectedTouchST(index);
}
public LSL_Vector llDetectedTouchUV(int index)
{
return m_LSL_Functions.llDetectedTouchUV(index);
}
public LSL_Vector llDetectedVel(int number)
{
return m_LSL_Functions.llDetectedVel(number);
}
public void llDialog(string avatar, string message, LSL_List buttons, int chat_channel)
{
m_LSL_Functions.llDialog(avatar, message, buttons, chat_channel);
}
public void llDie()
{
m_LSL_Functions.llDie();
}
public LSL_String llDumpList2String(LSL_List src, string seperator)
{
return m_LSL_Functions.llDumpList2String(src, seperator);
}
public LSL_Integer llEdgeOfWorld(LSL_Vector pos, LSL_Vector dir)
{
return m_LSL_Functions.llEdgeOfWorld(pos, dir);
}
public void llEjectFromLand(string pest)
{
m_LSL_Functions.llEjectFromLand(pest);
}
public void llEmail(string address, string subject, string message)
{
m_LSL_Functions.llEmail(address, subject, message);
}
public LSL_String llEscapeURL(string url)
{
return m_LSL_Functions.llEscapeURL(url);
}
public LSL_Rotation llEuler2Rot(LSL_Vector v)
{
return m_LSL_Functions.llEuler2Rot(v);
}
public LSL_Float llFabs(double f)
{
return m_LSL_Functions.llFabs(f);
}
public LSL_Integer llFloor(double f)
{
return m_LSL_Functions.llFloor(f);
}
public void llForceMouselook(int mouselook)
{
m_LSL_Functions.llForceMouselook(mouselook);
}
public LSL_Float llFrand(double mag)
{
return m_LSL_Functions.llFrand(mag);
}
public LSL_Key llGenerateKey()
{
return m_LSL_Functions.llGenerateKey();
}
public LSL_Vector llGetAccel()
{
return m_LSL_Functions.llGetAccel();
}
public LSL_Integer llGetAgentInfo(string id)
{
return m_LSL_Functions.llGetAgentInfo(id);
}
public LSL_String llGetAgentLanguage(string id)
{
return m_LSL_Functions.llGetAgentLanguage(id);
}
public LSL_List llGetAgentList(LSL_Integer scope, LSL_List options)
{
return m_LSL_Functions.llGetAgentList(scope, options);
}
public LSL_Vector llGetAgentSize(string id)
{
return m_LSL_Functions.llGetAgentSize(id);
}
public LSL_Float llGetAlpha(int face)
{
return m_LSL_Functions.llGetAlpha(face);
}
public LSL_Float llGetAndResetTime()
{
return m_LSL_Functions.llGetAndResetTime();
}
public LSL_String llGetAnimation(string id)
{
return m_LSL_Functions.llGetAnimation(id);
}
public LSL_List llGetAnimationList(string id)
{
return m_LSL_Functions.llGetAnimationList(id);
}
public LSL_Integer llGetAttached()
{
return m_LSL_Functions.llGetAttached();
}
public LSL_List llGetBoundingBox(string obj)
{
return m_LSL_Functions.llGetBoundingBox(obj);
}
public LSL_Vector llGetCameraPos()
{
return m_LSL_Functions.llGetCameraPos();
}
public LSL_Rotation llGetCameraRot()
{
return m_LSL_Functions.llGetCameraRot();
}
public LSL_Vector llGetCenterOfMass()
{
return m_LSL_Functions.llGetCenterOfMass();
}
public LSL_Vector llGetColor(int face)
{
return m_LSL_Functions.llGetColor(face);
}
public LSL_String llGetCreator()
{
return m_LSL_Functions.llGetCreator();
}
public LSL_String llGetDate()
{
return m_LSL_Functions.llGetDate();
}
public LSL_Float llGetEnergy()
{
return m_LSL_Functions.llGetEnergy();
}
public LSL_String llGetEnv(LSL_String name)
{
return m_LSL_Functions.llGetEnv(name);
}
public LSL_Vector llGetForce()
{
return m_LSL_Functions.llGetForce();
}
public LSL_Integer llGetFreeMemory()
{
return m_LSL_Functions.llGetFreeMemory();
}
public LSL_Integer llGetFreeURLs()
{
return m_LSL_Functions.llGetFreeURLs();
}
public LSL_Vector llGetGeometricCenter()
{
return m_LSL_Functions.llGetGeometricCenter();
}
public LSL_Float llGetGMTclock()
{
return m_LSL_Functions.llGetGMTclock();
}
public LSL_String llGetHTTPHeader(LSL_Key request_id, string header)
{
return m_LSL_Functions.llGetHTTPHeader(request_id, header);
}
public LSL_Key llGetInventoryCreator(string item)
{
return m_LSL_Functions.llGetInventoryCreator(item);
}
public LSL_Key llGetInventoryKey(string name)
{
return m_LSL_Functions.llGetInventoryKey(name);
}
public LSL_String llGetInventoryName(int type, int number)
{
return m_LSL_Functions.llGetInventoryName(type, number);
}
public LSL_Integer llGetInventoryNumber(int type)
{
return m_LSL_Functions.llGetInventoryNumber(type);
}
public LSL_Integer llGetInventoryPermMask(string item, int mask)
{
return m_LSL_Functions.llGetInventoryPermMask(item, mask);
}
public LSL_Integer llGetInventoryType(string name)
{
return m_LSL_Functions.llGetInventoryType(name);
}
public LSL_Key llGetKey()
{
return m_LSL_Functions.llGetKey();
}
public LSL_Key llGetLandOwnerAt(LSL_Vector pos)
{
return m_LSL_Functions.llGetLandOwnerAt(pos);
}
public LSL_Key llGetLinkKey(int linknum)
{
return m_LSL_Functions.llGetLinkKey(linknum);
}
public LSL_String llGetLinkName(int linknum)
{
return m_LSL_Functions.llGetLinkName(linknum);
}
public LSL_Integer llGetLinkNumber()
{
return m_LSL_Functions.llGetLinkNumber();
}
public LSL_Integer llGetLinkNumberOfSides(int link)
{
return m_LSL_Functions.llGetLinkNumberOfSides(link);
}
public void llSetKeyframedMotion(LSL_List frames, LSL_List options)
{
m_LSL_Functions.llSetKeyframedMotion(frames, options);
}
public LSL_Integer llGetListEntryType(LSL_List src, int index)
{
return m_LSL_Functions.llGetListEntryType(src, index);
}
public LSL_Integer llGetListLength(LSL_List src)
{
return m_LSL_Functions.llGetListLength(src);
}
public LSL_Vector llGetLocalPos()
{
return m_LSL_Functions.llGetLocalPos();
}
public LSL_Rotation llGetLocalRot()
{
return m_LSL_Functions.llGetLocalRot();
}
public LSL_Float llGetMass()
{
return m_LSL_Functions.llGetMass();
}
public LSL_Float llGetMassMKS()
{
return m_LSL_Functions.llGetMassMKS();
}
public LSL_Integer llGetMemoryLimit()
{
return m_LSL_Functions.llGetMemoryLimit();
}
public void llGetNextEmail(string address, string subject)
{
m_LSL_Functions.llGetNextEmail(address, subject);
}
public LSL_String llGetNotecardLine(string name, int line)
{
return m_LSL_Functions.llGetNotecardLine(name, line);
}
public LSL_Key llGetNumberOfNotecardLines(string name)
{
return m_LSL_Functions.llGetNumberOfNotecardLines(name);
}
public LSL_Integer llGetNumberOfPrims()
{
return m_LSL_Functions.llGetNumberOfPrims();
}
public LSL_Integer llGetNumberOfSides()
{
return m_LSL_Functions.llGetNumberOfSides();
}
public LSL_String llGetObjectDesc()
{
return m_LSL_Functions.llGetObjectDesc();
}
public LSL_List llGetObjectDetails(string id, LSL_List args)
{
return m_LSL_Functions.llGetObjectDetails(id, args);
}
public LSL_Float llGetObjectMass(string id)
{
return m_LSL_Functions.llGetObjectMass(id);
}
public LSL_String llGetObjectName()
{
return m_LSL_Functions.llGetObjectName();
}
public LSL_Integer llGetObjectPermMask(int mask)
{
return m_LSL_Functions.llGetObjectPermMask(mask);
}
public LSL_Integer llGetObjectPrimCount(string object_id)
{
return m_LSL_Functions.llGetObjectPrimCount(object_id);
}
public LSL_Vector llGetOmega()
{
return m_LSL_Functions.llGetOmega();
}
public LSL_Key llGetOwner()
{
return m_LSL_Functions.llGetOwner();
}
public LSL_Key llGetOwnerKey(string id)
{
return m_LSL_Functions.llGetOwnerKey(id);
}
public LSL_List llGetParcelDetails(LSL_Vector pos, LSL_List param)
{
return m_LSL_Functions.llGetParcelDetails(pos, param);
}
public LSL_Integer llGetParcelFlags(LSL_Vector pos)
{
return m_LSL_Functions.llGetParcelFlags(pos);
}
public LSL_Integer llGetParcelMaxPrims(LSL_Vector pos, int sim_wide)
{
return m_LSL_Functions.llGetParcelMaxPrims(pos, sim_wide);
}
public LSL_String llGetParcelMusicURL()
{
return m_LSL_Functions.llGetParcelMusicURL();
}
public LSL_Integer llGetParcelPrimCount(LSL_Vector pos, int category, int sim_wide)
{
return m_LSL_Functions.llGetParcelPrimCount(pos, category, sim_wide);
}
public LSL_List llGetParcelPrimOwners(LSL_Vector pos)
{
return m_LSL_Functions.llGetParcelPrimOwners(pos);
}
public LSL_Integer llGetPermissions()
{
return m_LSL_Functions.llGetPermissions();
}
public LSL_Key llGetPermissionsKey()
{
return m_LSL_Functions.llGetPermissionsKey();
}
public LSL_Vector llGetPos()
{
return m_LSL_Functions.llGetPos();
}
public LSL_List llGetPrimitiveParams(LSL_List rules)
{
return m_LSL_Functions.llGetPrimitiveParams(rules);
}
public LSL_List llGetLinkPrimitiveParams(int linknum, LSL_List rules)
{
return m_LSL_Functions.llGetLinkPrimitiveParams(linknum, rules);
}
public LSL_Integer llGetRegionAgentCount()
{
return m_LSL_Functions.llGetRegionAgentCount();
}
public LSL_Vector llGetRegionCorner()
{
return m_LSL_Functions.llGetRegionCorner();
}
public LSL_Integer llGetRegionFlags()
{
return m_LSL_Functions.llGetRegionFlags();
}
public LSL_Float llGetRegionFPS()
{
return m_LSL_Functions.llGetRegionFPS();
}
public LSL_String llGetRegionName()
{
return m_LSL_Functions.llGetRegionName();
}
public LSL_Float llGetRegionTimeDilation()
{
return m_LSL_Functions.llGetRegionTimeDilation();
}
public LSL_Vector llGetRootPosition()
{
return m_LSL_Functions.llGetRootPosition();
}
public LSL_Rotation llGetRootRotation()
{
return m_LSL_Functions.llGetRootRotation();
}
public LSL_Rotation llGetRot()
{
return m_LSL_Functions.llGetRot();
}
public LSL_Vector llGetScale()
{
return m_LSL_Functions.llGetScale();
}
public LSL_String llGetScriptName()
{
return m_LSL_Functions.llGetScriptName();
}
public LSL_Integer llGetScriptState(string name)
{
return m_LSL_Functions.llGetScriptState(name);
}
public LSL_String llGetSimulatorHostname()
{
return m_LSL_Functions.llGetSimulatorHostname();
}
public LSL_Integer llGetSPMaxMemory()
{
return m_LSL_Functions.llGetSPMaxMemory();
}
public LSL_Integer llGetStartParameter()
{
return m_LSL_Functions.llGetStartParameter();
}
public LSL_Integer llGetStatus(int status)
{
return m_LSL_Functions.llGetStatus(status);
}
public LSL_String llGetSubString(string src, int start, int end)
{
return m_LSL_Functions.llGetSubString(src, start, end);
}
public LSL_Vector llGetSunDirection()
{
return m_LSL_Functions.llGetSunDirection();
}
public LSL_String llGetTexture(int face)
{
return m_LSL_Functions.llGetTexture(face);
}
public LSL_Vector llGetTextureOffset(int face)
{
return m_LSL_Functions.llGetTextureOffset(face);
}
public LSL_Float llGetTextureRot(int side)
{
return m_LSL_Functions.llGetTextureRot(side);
}
public LSL_Vector llGetTextureScale(int side)
{
return m_LSL_Functions.llGetTextureScale(side);
}
public LSL_Float llGetTime()
{
return m_LSL_Functions.llGetTime();
}
public LSL_Float llGetTimeOfDay()
{
return m_LSL_Functions.llGetTimeOfDay();
}
public LSL_String llGetTimestamp()
{
return m_LSL_Functions.llGetTimestamp();
}
public LSL_Vector llGetTorque()
{
return m_LSL_Functions.llGetTorque();
}
public LSL_Integer llGetUnixTime()
{
return m_LSL_Functions.llGetUnixTime();
}
public LSL_Integer llGetUsedMemory()
{
return m_LSL_Functions.llGetUsedMemory();
}
public LSL_Vector llGetVel()
{
return m_LSL_Functions.llGetVel();
}
public LSL_Float llGetWallclock()
{
return m_LSL_Functions.llGetWallclock();
}
public void llGiveInventory(string destination, string inventory)
{
m_LSL_Functions.llGiveInventory(destination, inventory);
}
public void llGiveInventoryList(string destination, string category, LSL_List inventory)
{
m_LSL_Functions.llGiveInventoryList(destination, category, inventory);
}
public void llGiveMoney(string destination, int amount)
{
m_LSL_Functions.llGiveMoney(destination, amount);
}
public LSL_String llTransferLindenDollars(string destination, int amount)
{
return m_LSL_Functions.llTransferLindenDollars(destination, amount);
}
public void llGodLikeRezObject(string inventory, LSL_Vector pos)
{
m_LSL_Functions.llGodLikeRezObject(inventory, pos);
}
public LSL_Float llGround(LSL_Vector offset)
{
return m_LSL_Functions.llGround(offset);
}
public LSL_Vector llGroundContour(LSL_Vector offset)
{
return m_LSL_Functions.llGroundContour(offset);
}
public LSL_Vector llGroundNormal(LSL_Vector offset)
{
return m_LSL_Functions.llGroundNormal(offset);
}
public void llGroundRepel(double height, int water, double tau)
{
m_LSL_Functions.llGroundRepel(height, water, tau);
}
public LSL_Vector llGroundSlope(LSL_Vector offset)
{
return m_LSL_Functions.llGroundSlope(offset);
}
public LSL_String llHTTPRequest(string url, LSL_List parameters, string body)
{
return m_LSL_Functions.llHTTPRequest(url, parameters, body);
}
public void llHTTPResponse(LSL_Key id, int status, string body)
{
m_LSL_Functions.llHTTPResponse(id, status, body);
}
public LSL_String llInsertString(string dst, int position, string src)
{
return m_LSL_Functions.llInsertString(dst, position, src);
}
public void llInstantMessage(string user, string message)
{
m_LSL_Functions.llInstantMessage(user, message);
}
public LSL_String llIntegerToBase64(int number)
{
return m_LSL_Functions.llIntegerToBase64(number);
}
public LSL_String llKey2Name(string id)
{
return m_LSL_Functions.llKey2Name(id);
}
public LSL_String llGetUsername(string id)
{
return m_LSL_Functions.llGetUsername(id);
}
public LSL_String llRequestUsername(string id)
{
return m_LSL_Functions.llRequestUsername(id);
}
public LSL_String llGetDisplayName(string id)
{
return m_LSL_Functions.llGetDisplayName(id);
}
public LSL_String llRequestDisplayName(string id)
{
return m_LSL_Functions.llRequestDisplayName(id);
}
public LSL_List llCastRay(LSL_Vector start, LSL_Vector end, LSL_List options)
{
return m_LSL_Functions.llCastRay(start, end, options);
}
public void llLinkParticleSystem(int linknum, LSL_List rules)
{
m_LSL_Functions.llLinkParticleSystem(linknum, rules);
}
public LSL_String llList2CSV(LSL_List src)
{
return m_LSL_Functions.llList2CSV(src);
}
public LSL_Float llList2Float(LSL_List src, int index)
{
return m_LSL_Functions.llList2Float(src, index);
}
public LSL_Integer llList2Integer(LSL_List src, int index)
{
return m_LSL_Functions.llList2Integer(src, index);
}
public LSL_Key llList2Key(LSL_List src, int index)
{
return m_LSL_Functions.llList2Key(src, index);
}
public LSL_List llList2List(LSL_List src, int start, int end)
{
return m_LSL_Functions.llList2List(src, start, end);
}
public LSL_List llList2ListStrided(LSL_List src, int start, int end, int stride)
{
return m_LSL_Functions.llList2ListStrided(src, start, end, stride);
}
public LSL_Rotation llList2Rot(LSL_List src, int index)
{
return m_LSL_Functions.llList2Rot(src, index);
}
public LSL_String llList2String(LSL_List src, int index)
{
return m_LSL_Functions.llList2String(src, index);
}
public LSL_Vector llList2Vector(LSL_List src, int index)
{
return m_LSL_Functions.llList2Vector(src, index);
}
public LSL_Integer llListen(int channelID, string name, string ID, string msg)
{
return m_LSL_Functions.llListen(channelID, name, ID, msg);
}
public void llListenControl(int number, int active)
{
m_LSL_Functions.llListenControl(number, active);
}
public void llListenRemove(int number)
{
m_LSL_Functions.llListenRemove(number);
}
public LSL_Integer llListFindList(LSL_List src, LSL_List test)
{
return m_LSL_Functions.llListFindList(src, test);
}
public LSL_List llListInsertList(LSL_List dest, LSL_List src, int start)
{
return m_LSL_Functions.llListInsertList(dest, src, start);
}
public LSL_List llListRandomize(LSL_List src, int stride)
{
return m_LSL_Functions.llListRandomize(src, stride);
}
public LSL_List llListReplaceList(LSL_List dest, LSL_List src, int start, int end)
{
return m_LSL_Functions.llListReplaceList(dest, src, start, end);
}
public LSL_List llListSort(LSL_List src, int stride, int ascending)
{
return m_LSL_Functions.llListSort(src, stride, ascending);
}
public LSL_Float llListStatistics(int operation, LSL_List src)
{
return m_LSL_Functions.llListStatistics(operation, src);
}
public void llLoadURL(string avatar_id, string message, string url)
{
m_LSL_Functions.llLoadURL(avatar_id, message, url);
}
public LSL_Float llLog(double val)
{
return m_LSL_Functions.llLog(val);
}
public LSL_Float llLog10(double val)
{
return m_LSL_Functions.llLog10(val);
}
public void llLookAt(LSL_Vector target, double strength, double damping)
{
m_LSL_Functions.llLookAt(target, strength, damping);
}
public void llLoopSound(string sound, double volume)
{
m_LSL_Functions.llLoopSound(sound, volume);
}
public void llLoopSoundMaster(string sound, double volume)
{
m_LSL_Functions.llLoopSoundMaster(sound, volume);
}
public void llLoopSoundSlave(string sound, double volume)
{
m_LSL_Functions.llLoopSoundSlave(sound, volume);
}
public LSL_Integer llManageEstateAccess(int action, string avatar)
{
return m_LSL_Functions.llManageEstateAccess(action, avatar);
}
public void llMakeExplosion(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset)
{
m_LSL_Functions.llMakeExplosion(particles, scale, vel, lifetime, arc, texture, offset);
}
public void llMakeFire(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset)
{
m_LSL_Functions.llMakeFire(particles, scale, vel, lifetime, arc, texture, offset);
}
public void llMakeFountain(int particles, double scale, double vel, double lifetime, double arc, int bounce, string texture, LSL_Vector offset, double bounce_offset)
{
m_LSL_Functions.llMakeFountain(particles, scale, vel, lifetime, arc, bounce, texture, offset, bounce_offset);
}
public void llMakeSmoke(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset)
{
m_LSL_Functions.llMakeSmoke(particles, scale, vel, lifetime, arc, texture, offset);
}
public void llMapDestination(string simname, LSL_Vector pos, LSL_Vector look_at)
{
m_LSL_Functions.llMapDestination(simname, pos, look_at);
}
public LSL_String llMD5String(string src, int nonce)
{
return m_LSL_Functions.llMD5String(src, nonce);
}
public LSL_String llSHA1String(string src)
{
return m_LSL_Functions.llSHA1String(src);
}
public void llMessageLinked(int linknum, int num, string str, string id)
{
m_LSL_Functions.llMessageLinked(linknum, num, str, id);
}
public void llMinEventDelay(double delay)
{
m_LSL_Functions.llMinEventDelay(delay);
}
public void llModifyLand(int action, int brush)
{
m_LSL_Functions.llModifyLand(action, brush);
}
public LSL_Integer llModPow(int a, int b, int c)
{
return m_LSL_Functions.llModPow(a, b, c);
}
public void llMoveToTarget(LSL_Vector target, double tau)
{
m_LSL_Functions.llMoveToTarget(target, tau);
}
public void llOffsetTexture(double u, double v, int face)
{
m_LSL_Functions.llOffsetTexture(u, v, face);
}
public void llOpenRemoteDataChannel()
{
m_LSL_Functions.llOpenRemoteDataChannel();
}
public LSL_Integer llOverMyLand(string id)
{
return m_LSL_Functions.llOverMyLand(id);
}
public void llOwnerSay(string msg)
{
m_LSL_Functions.llOwnerSay(msg);
}
public void llParcelMediaCommandList(LSL_List commandList)
{
m_LSL_Functions.llParcelMediaCommandList(commandList);
}
public LSL_List llParcelMediaQuery(LSL_List aList)
{
return m_LSL_Functions.llParcelMediaQuery(aList);
}
public LSL_List llParseString2List(string str, LSL_List separators, LSL_List spacers)
{
return m_LSL_Functions.llParseString2List(str, separators, spacers);
}
public LSL_List llParseStringKeepNulls(string src, LSL_List seperators, LSL_List spacers)
{
return m_LSL_Functions.llParseStringKeepNulls(src, seperators, spacers);
}
public void llParticleSystem(LSL_List rules)
{
m_LSL_Functions.llParticleSystem(rules);
}
public void llPassCollisions(int pass)
{
m_LSL_Functions.llPassCollisions(pass);
}
public void llPassTouches(int pass)
{
m_LSL_Functions.llPassTouches(pass);
}
public void llPlaySound(string sound, double volume)
{
m_LSL_Functions.llPlaySound(sound, volume);
}
public void llPlaySoundSlave(string sound, double volume)
{
m_LSL_Functions.llPlaySoundSlave(sound, volume);
}
public void llPointAt(LSL_Vector pos)
{
m_LSL_Functions.llPointAt(pos);
}
public LSL_Float llPow(double fbase, double fexponent)
{
return m_LSL_Functions.llPow(fbase, fexponent);
}
public void llPreloadSound(string sound)
{
m_LSL_Functions.llPreloadSound(sound);
}
public void llPushObject(string target, LSL_Vector impulse, LSL_Vector ang_impulse, int local)
{
m_LSL_Functions.llPushObject(target, impulse, ang_impulse, local);
}
public void llRefreshPrimURL()
{
m_LSL_Functions.llRefreshPrimURL();
}
public void llRegionSay(int channelID, string text)
{
m_LSL_Functions.llRegionSay(channelID, text);
}
public void llRegionSayTo(string key, int channelID, string text)
{
m_LSL_Functions.llRegionSayTo(key, channelID, text);
}
public void llReleaseCamera(string avatar)
{
m_LSL_Functions.llReleaseCamera(avatar);
}
public void llReleaseURL(string url)
{
m_LSL_Functions.llReleaseURL(url);
}
public void llReleaseControls()
{
m_LSL_Functions.llReleaseControls();
}
public void llRemoteDataReply(string channel, string message_id, string sdata, int idata)
{
m_LSL_Functions.llRemoteDataReply(channel, message_id, sdata, idata);
}
public void llRemoteDataSetRegion()
{
m_LSL_Functions.llRemoteDataSetRegion();
}
public void llRemoteLoadScript(string target, string name, int running, int start_param)
{
m_LSL_Functions.llRemoteLoadScript(target, name, running, start_param);
}
public void llRemoteLoadScriptPin(string target, string name, int pin, int running, int start_param)
{
m_LSL_Functions.llRemoteLoadScriptPin(target, name, pin, running, start_param);
}
public void llRemoveFromLandBanList(string avatar)
{
m_LSL_Functions.llRemoveFromLandBanList(avatar);
}
public void llRemoveFromLandPassList(string avatar)
{
m_LSL_Functions.llRemoveFromLandPassList(avatar);
}
public void llRemoveInventory(string item)
{
m_LSL_Functions.llRemoveInventory(item);
}
public void llRemoveVehicleFlags(int flags)
{
m_LSL_Functions.llRemoveVehicleFlags(flags);
}
public LSL_Key llRequestAgentData(string id, int data)
{
return m_LSL_Functions.llRequestAgentData(id, data);
}
public LSL_Key llRequestInventoryData(string name)
{
return m_LSL_Functions.llRequestInventoryData(name);
}
public void llRequestPermissions(string agent, int perm)
{
m_LSL_Functions.llRequestPermissions(agent, perm);
}
public LSL_String llRequestSecureURL()
{
return m_LSL_Functions.llRequestSecureURL();
}
public LSL_Key llRequestSimulatorData(string simulator, int data)
{
return m_LSL_Functions.llRequestSimulatorData(simulator, data);
}
public LSL_Key llRequestURL()
{
return m_LSL_Functions.llRequestURL();
}
public void llResetLandBanList()
{
m_LSL_Functions.llResetLandBanList();
}
public void llResetLandPassList()
{
m_LSL_Functions.llResetLandPassList();
}
public void llResetOtherScript(string name)
{
m_LSL_Functions.llResetOtherScript(name);
}
public void llResetScript()
{
m_LSL_Functions.llResetScript();
}
public void llResetTime()
{
m_LSL_Functions.llResetTime();
}
public void llRezAtRoot(string inventory, LSL_Vector position, LSL_Vector velocity, LSL_Rotation rot, int param)
{
m_LSL_Functions.llRezAtRoot(inventory, position, velocity, rot, param);
}
public void llRezObject(string inventory, LSL_Vector pos, LSL_Vector vel, LSL_Rotation rot, int param)
{
m_LSL_Functions.llRezObject(inventory, pos, vel, rot, param);
}
public LSL_Float llRot2Angle(LSL_Rotation rot)
{
return m_LSL_Functions.llRot2Angle(rot);
}
public LSL_Vector llRot2Axis(LSL_Rotation rot)
{
return m_LSL_Functions.llRot2Axis(rot);
}
public LSL_Vector llRot2Euler(LSL_Rotation r)
{
return m_LSL_Functions.llRot2Euler(r);
}
public LSL_Vector llRot2Fwd(LSL_Rotation r)
{
return m_LSL_Functions.llRot2Fwd(r);
}
public LSL_Vector llRot2Left(LSL_Rotation r)
{
return m_LSL_Functions.llRot2Left(r);
}
public LSL_Vector llRot2Up(LSL_Rotation r)
{
return m_LSL_Functions.llRot2Up(r);
}
public void llRotateTexture(double rotation, int face)
{
m_LSL_Functions.llRotateTexture(rotation, face);
}
public LSL_Rotation llRotBetween(LSL_Vector start, LSL_Vector end)
{
return m_LSL_Functions.llRotBetween(start, end);
}
public void llRotLookAt(LSL_Rotation target, double strength, double damping)
{
m_LSL_Functions.llRotLookAt(target, strength, damping);
}
public LSL_Integer llRotTarget(LSL_Rotation rot, double error)
{
return m_LSL_Functions.llRotTarget(rot, error);
}
public void llRotTargetRemove(int number)
{
m_LSL_Functions.llRotTargetRemove(number);
}
public LSL_Integer llRound(double f)
{
return m_LSL_Functions.llRound(f);
}
public LSL_Integer llSameGroup(string agent)
{
return m_LSL_Functions.llSameGroup(agent);
}
public void llSay(int channelID, string text)
{
m_LSL_Functions.llSay(channelID, text);
}
public void llScaleTexture(double u, double v, int face)
{
m_LSL_Functions.llScaleTexture(u, v, face);
}
public LSL_Integer llScriptDanger(LSL_Vector pos)
{
return m_LSL_Functions.llScriptDanger(pos);
}
public void llScriptProfiler(LSL_Integer flags)
{
m_LSL_Functions.llScriptProfiler(flags);
}
public LSL_Key llSendRemoteData(string channel, string dest, int idata, string sdata)
{
return m_LSL_Functions.llSendRemoteData(channel, dest, idata, sdata);
}
public void llSensor(string name, string id, int type, double range, double arc)
{
m_LSL_Functions.llSensor(name, id, type, range, arc);
}
public void llSensorRemove()
{
m_LSL_Functions.llSensorRemove();
}
public void llSensorRepeat(string name, string id, int type, double range, double arc, double rate)
{
m_LSL_Functions.llSensorRepeat(name, id, type, range, arc, rate);
}
public void llSetAlpha(double alpha, int face)
{
m_LSL_Functions.llSetAlpha(alpha, face);
}
public void llSetBuoyancy(double buoyancy)
{
m_LSL_Functions.llSetBuoyancy(buoyancy);
}
public void llSetCameraAtOffset(LSL_Vector offset)
{
m_LSL_Functions.llSetCameraAtOffset(offset);
}
public void llSetCameraEyeOffset(LSL_Vector offset)
{
m_LSL_Functions.llSetCameraEyeOffset(offset);
}
public void llSetLinkCamera(LSL_Integer link, LSL_Vector eye, LSL_Vector at)
{
m_LSL_Functions.llSetLinkCamera(link, eye, at);
}
public void llSetCameraParams(LSL_List rules)
{
m_LSL_Functions.llSetCameraParams(rules);
}
public void llSetClickAction(int action)
{
m_LSL_Functions.llSetClickAction(action);
}
public void llSetColor(LSL_Vector color, int face)
{
m_LSL_Functions.llSetColor(color, face);
}
public void llSetContentType(LSL_Key id, LSL_Integer type)
{
m_LSL_Functions.llSetContentType(id, type);
}
public void llSetDamage(double damage)
{
m_LSL_Functions.llSetDamage(damage);
}
public void llSetForce(LSL_Vector force, int local)
{
m_LSL_Functions.llSetForce(force, local);
}
public void llSetForceAndTorque(LSL_Vector force, LSL_Vector torque, int local)
{
m_LSL_Functions.llSetForceAndTorque(force, torque, local);
}
public void llSetVelocity(LSL_Vector force, int local)
{
m_LSL_Functions.llSetVelocity(force, local);
}
public void llSetAngularVelocity(LSL_Vector force, int local)
{
m_LSL_Functions.llSetAngularVelocity(force, local);
}
public void llSetHoverHeight(double height, int water, double tau)
{
m_LSL_Functions.llSetHoverHeight(height, water, tau);
}
public void llSetInventoryPermMask(string item, int mask, int value)
{
m_LSL_Functions.llSetInventoryPermMask(item, mask, value);
}
public void llSetLinkAlpha(int linknumber, double alpha, int face)
{
m_LSL_Functions.llSetLinkAlpha(linknumber, alpha, face);
}
public void llSetLinkColor(int linknumber, LSL_Vector color, int face)
{
m_LSL_Functions.llSetLinkColor(linknumber, color, face);
}
public void llSetLinkPrimitiveParams(int linknumber, LSL_List rules)
{
m_LSL_Functions.llSetLinkPrimitiveParams(linknumber, rules);
}
public void llSetLinkTexture(int linknumber, string texture, int face)
{
m_LSL_Functions.llSetLinkTexture(linknumber, texture, face);
}
public void llSetLinkTextureAnim(int linknum, int mode, int face, int sizex, int sizey, double start, double length, double rate)
{
m_LSL_Functions.llSetLinkTextureAnim(linknum, mode, face, sizex, sizey, start, length, rate);
}
public void llSetLocalRot(LSL_Rotation rot)
{
m_LSL_Functions.llSetLocalRot(rot);
}
public LSL_Integer llSetMemoryLimit(LSL_Integer limit)
{
return m_LSL_Functions.llSetMemoryLimit(limit);
}
public void llSetObjectDesc(string desc)
{
m_LSL_Functions.llSetObjectDesc(desc);
}
public void llSetObjectName(string name)
{
m_LSL_Functions.llSetObjectName(name);
}
public void llSetObjectPermMask(int mask, int value)
{
m_LSL_Functions.llSetObjectPermMask(mask, value);
}
public void llSetParcelMusicURL(string url)
{
m_LSL_Functions.llSetParcelMusicURL(url);
}
public void llSetPayPrice(int price, LSL_List quick_pay_buttons)
{
m_LSL_Functions.llSetPayPrice(price, quick_pay_buttons);
}
public void llSetPos(LSL_Vector pos)
{
m_LSL_Functions.llSetPos(pos);
}
public void llSetPrimitiveParams(LSL_List rules)
{
m_LSL_Functions.llSetPrimitiveParams(rules);
}
public void llSetLinkPrimitiveParamsFast(int linknum, LSL_List rules)
{
m_LSL_Functions.llSetLinkPrimitiveParamsFast(linknum, rules);
}
public void llSetPrimURL(string url)
{
m_LSL_Functions.llSetPrimURL(url);
}
public LSL_Integer llSetRegionPos(LSL_Vector pos)
{
return m_LSL_Functions.llSetRegionPos(pos);
}
public void llSetRemoteScriptAccessPin(int pin)
{
m_LSL_Functions.llSetRemoteScriptAccessPin(pin);
}
public void llSetRot(LSL_Rotation rot)
{
m_LSL_Functions.llSetRot(rot);
}
public void llSetScale(LSL_Vector scale)
{
m_LSL_Functions.llSetScale(scale);
}
public void llSetScriptState(string name, int run)
{
m_LSL_Functions.llSetScriptState(name, run);
}
public void llSetSitText(string text)
{
m_LSL_Functions.llSetSitText(text);
}
public void llSetSoundQueueing(int queue)
{
m_LSL_Functions.llSetSoundQueueing(queue);
}
public void llSetSoundRadius(double radius)
{
m_LSL_Functions.llSetSoundRadius(radius);
}
public void llSetStatus(int status, int value)
{
m_LSL_Functions.llSetStatus(status, value);
}
public void llSetText(string text, LSL_Vector color, double alpha)
{
m_LSL_Functions.llSetText(text, color, alpha);
}
public void llSetTexture(string texture, int face)
{
m_LSL_Functions.llSetTexture(texture, face);
}
public void llSetTextureAnim(int mode, int face, int sizex, int sizey, double start, double length, double rate)
{
m_LSL_Functions.llSetTextureAnim(mode, face, sizex, sizey, start, length, rate);
}
public void llSetTimerEvent(double sec)
{
m_LSL_Functions.llSetTimerEvent(sec);
}
public void llSetTorque(LSL_Vector torque, int local)
{
m_LSL_Functions.llSetTorque(torque, local);
}
public void llSetTouchText(string text)
{
m_LSL_Functions.llSetTouchText(text);
}
public void llSetVehicleFlags(int flags)
{
m_LSL_Functions.llSetVehicleFlags(flags);
}
public void llSetVehicleFloatParam(int param, LSL_Float value)
{
m_LSL_Functions.llSetVehicleFloatParam(param, value);
}
public void llSetVehicleRotationParam(int param, LSL_Rotation rot)
{
m_LSL_Functions.llSetVehicleRotationParam(param, rot);
}
public void llSetVehicleType(int type)
{
m_LSL_Functions.llSetVehicleType(type);
}
public void llSetVehicleVectorParam(int param, LSL_Vector vec)
{
m_LSL_Functions.llSetVehicleVectorParam(param, vec);
}
public void llShout(int channelID, string text)
{
m_LSL_Functions.llShout(channelID, text);
}
public LSL_Float llSin(double f)
{
return m_LSL_Functions.llSin(f);
}
public void llSitTarget(LSL_Vector offset, LSL_Rotation rot)
{
m_LSL_Functions.llSitTarget(offset, rot);
}
public void llLinkSitTarget(LSL_Integer link, LSL_Vector offset, LSL_Rotation rot)
{
m_LSL_Functions.llLinkSitTarget(link, offset, rot);
}
public void llSleep(double sec)
{
m_LSL_Functions.llSleep(sec);
}
public void llSound(string sound, double volume, int queue, int loop)
{
m_LSL_Functions.llSound(sound, volume, queue, loop);
}
public void llSoundPreload(string sound)
{
m_LSL_Functions.llSoundPreload(sound);
}
public LSL_Float llSqrt(double f)
{
return m_LSL_Functions.llSqrt(f);
}
public void llStartAnimation(string anim)
{
m_LSL_Functions.llStartAnimation(anim);
}
public void llStopAnimation(string anim)
{
m_LSL_Functions.llStopAnimation(anim);
}
public void llStopHover()
{
m_LSL_Functions.llStopHover();
}
public void llStopLookAt()
{
m_LSL_Functions.llStopLookAt();
}
public void llStopMoveToTarget()
{
m_LSL_Functions.llStopMoveToTarget();
}
public void llStopPointAt()
{
m_LSL_Functions.llStopPointAt();
}
public void llStopSound()
{
m_LSL_Functions.llStopSound();
}
public LSL_Integer llStringLength(string str)
{
return m_LSL_Functions.llStringLength(str);
}
public LSL_String llStringToBase64(string str)
{
return m_LSL_Functions.llStringToBase64(str);
}
public LSL_String llStringTrim(string src, int type)
{
return m_LSL_Functions.llStringTrim(src, type);
}
public LSL_Integer llSubStringIndex(string source, string pattern)
{
return m_LSL_Functions.llSubStringIndex(source, pattern);
}
public void llTakeCamera(string avatar)
{
m_LSL_Functions.llTakeCamera(avatar);
}
public void llTakeControls(int controls, int accept, int pass_on)
{
m_LSL_Functions.llTakeControls(controls, accept, pass_on);
}
public LSL_Float llTan(double f)
{
return m_LSL_Functions.llTan(f);
}
public LSL_Integer llTarget(LSL_Vector position, double range)
{
return m_LSL_Functions.llTarget(position, range);
}
public void llTargetOmega(LSL_Vector axis, double spinrate, double gain)
{
m_LSL_Functions.llTargetOmega(axis, spinrate, gain);
}
public void llTargetRemove(int number)
{
m_LSL_Functions.llTargetRemove(number);
}
public void llTeleportAgent(string agent, string simname, LSL_Vector pos, LSL_Vector lookAt)
{
m_LSL_Functions.llTeleportAgent(agent, simname, pos, lookAt);
}
public void llTeleportAgentGlobalCoords(string agent, LSL_Vector global, LSL_Vector pos, LSL_Vector lookAt)
{
m_LSL_Functions.llTeleportAgentGlobalCoords(agent, global, pos, lookAt);
}
public void llTeleportAgentHome(string agent)
{
m_LSL_Functions.llTeleportAgentHome(agent);
}
public void llTextBox(string avatar, string message, int chat_channel)
{
m_LSL_Functions.llTextBox(avatar, message, chat_channel);
}
public LSL_String llToLower(string source)
{
return m_LSL_Functions.llToLower(source);
}
public LSL_String llToUpper(string source)
{
return m_LSL_Functions.llToUpper(source);
}
public void llTriggerSound(string sound, double volume)
{
m_LSL_Functions.llTriggerSound(sound, volume);
}
public void llTriggerSoundLimited(string sound, double volume, LSL_Vector top_north_east, LSL_Vector bottom_south_west)
{
m_LSL_Functions.llTriggerSoundLimited(sound, volume, top_north_east, bottom_south_west);
}
public LSL_String llUnescapeURL(string url)
{
return m_LSL_Functions.llUnescapeURL(url);
}
public void llUnSit(string id)
{
m_LSL_Functions.llUnSit(id);
}
public LSL_Float llVecDist(LSL_Vector a, LSL_Vector b)
{
return m_LSL_Functions.llVecDist(a, b);
}
public LSL_Float llVecMag(LSL_Vector v)
{
return m_LSL_Functions.llVecMag(v);
}
public LSL_Vector llVecNorm(LSL_Vector v)
{
return m_LSL_Functions.llVecNorm(v);
}
public void llVolumeDetect(int detect)
{
m_LSL_Functions.llVolumeDetect(detect);
}
public LSL_Float llWater(LSL_Vector offset)
{
return m_LSL_Functions.llWater(offset);
}
public void llWhisper(int channelID, string text)
{
m_LSL_Functions.llWhisper(channelID, text);
}
public LSL_Vector llWind(LSL_Vector offset)
{
return m_LSL_Functions.llWind(offset);
}
public LSL_String llXorBase64Strings(string str1, string str2)
{
return m_LSL_Functions.llXorBase64Strings(str1, str2);
}
public LSL_String llXorBase64StringsCorrect(string str1, string str2)
{
return m_LSL_Functions.llXorBase64StringsCorrect(str1, str2);
}
public LSL_List llGetPrimMediaParams(int face, LSL_List rules)
{
return m_LSL_Functions.llGetPrimMediaParams(face, rules);
}
public LSL_List llGetLinkMedia(LSL_Integer link, LSL_Integer face, LSL_List rules)
{
return m_LSL_Functions.llGetLinkMedia(link, face, rules);
}
public LSL_Integer llSetPrimMediaParams(int face, LSL_List rules)
{
return m_LSL_Functions.llSetPrimMediaParams(face, rules);
}
public LSL_Integer llSetLinkMedia(LSL_Integer link, LSL_Integer face, LSL_List rules)
{
return m_LSL_Functions.llSetLinkMedia(link, face, rules);
}
public LSL_Integer llClearPrimMedia(LSL_Integer face)
{
return m_LSL_Functions.llClearPrimMedia(face);
}
public LSL_Integer llClearLinkMedia(LSL_Integer link, LSL_Integer face)
{
return m_LSL_Functions.llClearLinkMedia(link, face);
}
public void print(string str)
{
m_LSL_Functions.print(str);
}
}
}
| |
//#define DEBUG
//#define DEBUG2
//#define THROTTLE_ALL
//#define ADJUST_RATE_FEEDBACK
using System;
using System.Collections.Generic;
namespace ICSimulator
{
public class HotNetsThrottlePool : IPrioPktPool
{
Queue<Flit>[] queues;
int nqueues;
int next_queue;
int last_peek_queue;
int node_id=-1;
int flitCount = 0;
public static IPrioPktPool construct()
{
return new HotNetsThrottlePool();
}
private HotNetsThrottlePool()
{
nqueues = Packet.numQueues;
queues = new Queue<Flit>[nqueues];
for (int i = 0; i < nqueues; i++)
queues[i] = new Queue<Flit>();
next_queue = nqueues - 1;
last_peek_queue = 0;
}
public bool FlitInterface { get { return true; } }
public void addPacket(Packet pkt)
{
flitCount += pkt.nrOfFlits;
Queue<Flit> q = queues[pkt.getQueue()];
foreach (Flit f in pkt.flits)
q.Enqueue(f);
}
int chooseQueue()
{
if (!Simulator.controller.tryInject(node_id))
return 1;
else if (queues[next_queue].Count > 0 && queues[next_queue].Peek().flitNr != 0)
return next_queue;
else
{
int tries = nqueues;
while (tries-- > 0)
{
next_queue = (next_queue + 1) % nqueues;
if (queues[next_queue].Count > 0) return next_queue;
}
return next_queue;
}
}
public Flit peekFlit()
{
last_peek_queue = chooseQueue();
if (queues[last_peek_queue].Count == 0) return null;
else return queues[last_peek_queue].Peek();
}
public void takeFlit()
{
if (queues[last_peek_queue].Count == 0) throw new Exception("don't take unless you peek!");
queues[last_peek_queue].Dequeue();
}
public Packet next() { return null; }
public void setNodeId(int id)
{
node_id=id;
}
public int Count { get { return flitCount; } }
public int FlitCount { get { return flitCount; } }
public int ReqCount { get { return queues[0].Count; } }
}
public class Controller_HotNets : Controller_ClassicBLESS
{
HotNetsThrottlePool[] m_injPools = new HotNetsThrottlePool[Config.N];
AveragingWindow avg_netutil, avg_ipc;
AveragingWindow[] avg_qlen;
double m_target;
double m_rate;
bool[] m_throttled = new bool[Config.N];
ulong[] last_ins = new ulong[Config.N];
ulong[] last_inj = new ulong[Config.N];
double[] m_ipf = new double[Config.N];
double m_avg_ipf = 0.0;
bool m_starved = false;
public Controller_HotNets()
{
avg_netutil = new AveragingWindow(Config.selftuned_netutil_window);
avg_ipc = new AveragingWindow(Config.selftuned_ipc_window);
avg_qlen = new AveragingWindow[Config.N];
for (int i = 0; i < Config.N; i++)
avg_qlen[i] = new AveragingWindow(Config.hotnets_qlen_window);
m_target = Config.selftuned_init_netutil_target;
m_rate = 0.0;
}
public override IPrioPktPool newPrioPktPool(int node)
{
return HotNetsThrottlePool.construct();
}
public override void setInjPool(int node, IPrioPktPool pool)
{
m_injPools[node] = pool as HotNetsThrottlePool;
pool.setNodeId(node);
}
public override bool ThrottleAtRouter
{ get { return false; } }
// true to allow injection, false to block (throttle)
public override bool tryInject(int node)
{
if (!m_throttled[node])
return true;
if (Config.hotnets_closedloop_rate)
{
if (m_rate > 0.0)
return Simulator.rand.NextDouble() > m_rate;
else
return true;
}
else
{
double rate = Math.Min(Config.hotnets_max_throttle, Config.hotnets_min_throttle + Config.hotnets_scale / avg_qlen[node].average());
#if DEBUG2
Console.WriteLine("node {0} qlen {1} rate {2}", node, avg_qlen[node].average(), rate);
#endif
if (rate > 0)
return Simulator.rand.NextDouble() > rate;
else
return true;
}
}
public override void doStep()
{
avg_netutil.accumulate(Simulator.network._cycle_netutil);
avg_ipc.accumulate((double)Simulator.network._cycle_insns / Config.N);
for (int i = 0; i < Config.N; i++)
avg_qlen[i].accumulate(m_injPools[i].ReqCount);
if (Simulator.CurrentRound % (ulong)Config.hotnets_ipc_quantum == 0)
doUpdateIPF();
if (Simulator.CurrentRound % (ulong)Config.selftuned_quantum == 0)
doUpdate();
stepStarve();
}
int m_starve_idx = 0;
bool[,] m_starve_window = new bool[Config.N, Config.hotnets_starve_window];
int[] m_starve_total = new int[Config.N];
void stepStarve()
{
m_starve_idx = (m_starve_idx + 1) % Config.hotnets_starve_window;
for (int node = 0; node < Config.N; node++)
{
if (m_starve_window[node, m_starve_idx]) m_starve_total[node]--;
m_starve_window[node, m_starve_idx] = false;
}
}
public override void reportStarve(int node)
{
m_starve_window[node, m_starve_idx] = true;
m_starve_total[node]++;
}
void doUpdateIPF()
{
m_avg_ipf = 0.0;
m_starved = false;
for (int i = 0; i < Config.N; i++)
{
ulong ins = Simulator.network.nodes[i].cpu.ICount - last_ins[i];
ulong inj = Simulator.network.routers[i].Inject - last_inj[i];
last_ins[i] = Simulator.network.nodes[i].cpu.ICount;
last_inj[i] = Simulator.network.routers[i].Inject;
m_ipf[i] = (inj > 0) ? (double)ins / (double)inj : 0.0;
m_avg_ipf += m_ipf[i];
}
m_avg_ipf /= (double)Config.N;
}
void doUpdate()
{
double netu = avg_netutil.average();
m_starved = false;
double avg_Q = 0;
for (int i = 0; i < Config.N; i++)
{
double qlen = avg_qlen[i].average();
avg_Q += qlen;
double srate = (double)m_starve_total[i] / Config.hotnets_starve_window;
double starve_thresh = Math.Min(Config.hotnets_starve_max,
Config.hotnets_starve_min + Config.hotnets_starve_scale / m_ipf[i]);
#if DEBUG2
Console.WriteLine("router {0} starve_thresh {1} starvation rate {2} starved {3}",
i, starve_thresh, srate, srate > starve_thresh);
#endif
if (srate > starve_thresh)
m_starved = true;
}
avg_Q /= Config.N;
for (int i = 0; i < Config.N; i++)
{
if (Simulator.CurrentRound > 0)
//m_throttled[i] = m_starved && (m_ipf[i] < m_avg_ipf);
m_throttled[i] = m_starved && (avg_qlen[i].average() > avg_Q);
else
m_throttled[i] = false;
#if DEBUG
//Console.WriteLine("cycle {0} node {1} ipf {2} (avg {3}) throttle {4}",
// Simulator.CurrentRound, i, m_ipf[i], avg_ipf, m_throttled[i]);
#endif
}
if (netu > m_target + Config.selftuned_netutil_tolerance)
if (m_rate < 1.00) m_rate += Config.selftuned_rate_delta;
if (netu < m_target - Config.selftuned_netutil_tolerance)
if (m_rate > 0.00) m_rate -= Config.selftuned_rate_delta;
#if DEBUG
Console.WriteLine("cycle {0}: netu {1}, target {2}, rate {3}",
Simulator.CurrentRound, netu, m_target, m_rate);
#endif
}
}
}
| |
using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using OTFontFile;
using NS_ValCommon;
using OTFontFileVal;
namespace FontValidator
{
public class CmdLineInterface : Driver.DriverCallbacks
{
string [] m_sFiles;
ReportFileDestination m_ReportFileDestination;
bool m_bOpenReportFiles;
string m_sReportFixedDir;
ValidatorParameters m_vp;
OTFileVal m_curOTFileVal;
List<string> m_reportFiles = new List<string>();
List<string> m_captions = new List<string>();
static void ErrOut( string s )
{
Console.WriteLine( s );
}
static void StdOut( string s ) {
Console.WriteLine( s );
}
static public void CopyXslFile(string sReportFile)
{
// Note that this will not work in development because it depends
// upon the xsl file existing in the same location as the
// executing assembly, which is only true of the deployment package.
//
// During development, though, the file FontVal/fval.xsl can be
// copied as needed to
// FontVal/bin/Debug or
// FontVal/bin/Release
// and then the source file is found.
// build the src filename
string sAssemblyLocation =
System.Reflection.Assembly.GetExecutingAssembly().Location;
FileInfo fi = new FileInfo(sAssemblyLocation);
string sSrcDir = fi.DirectoryName;
string sSrcFile = sSrcDir + Path.DirectorySeparatorChar + "fval.xsl";
// build the dest filename
fi = new FileInfo(sReportFile);
string sDestDir = fi.DirectoryName;
string sDestFile = sDestDir + Path.DirectorySeparatorChar + "fval.xsl";
// copy the file
try
{
File.Copy(sSrcFile, sDestFile, true);
fi = new FileInfo(sDestFile);
fi.Attributes = fi.Attributes & ~FileAttributes.ReadOnly;
}
catch (Exception)
{
}
}
// ================================================================
// Callbacks for Driver.DriverCallbacks interface
// ================================================================
public void OnException( Exception e )
{
ErrOut( "Error: " + e.Message );
DeleteTempFiles();
}
public void OnReportsReady()
{
StdOut( "Reports are ready!" );
}
public void OnBeginRasterTest( string label )
{
StdOut( "Begin Raster Test: " + label );
}
public void OnBeginTableTest( DirectoryEntry de )
{
StdOut( "Table Test: " + ( string )de.tag );
}
public void OnTestProgress( object oParam )
{
string s = ( string )oParam;
if (s == null) {
s = "";
}
StdOut( "Progress: " + s );
}
public void OnCloseReportFile( string sReportFile )
{
StdOut( "Complete: " + sReportFile );
// copy the xsl file to the same directory as the report
//
// This has to be done for each file because the if we are
// putting the report on the font's directory, there may
// be a different directory for each font.
CopyXslFile( sReportFile );
}
public void OnOpenReportFile( string sReportFile, string fpath )
{
m_captions.Add( fpath );
m_reportFiles.Add( sReportFile );
}
public void OnCancel()
{
DeleteTempFiles();
}
public void OnOTFileValChange( OTFileVal fontFile )
{
m_curOTFileVal = fontFile;
}
public string GetReportFileName( string sFontFile )
{
string sReportFile = null;
switch ( m_ReportFileDestination )
{
case ReportFileDestination.TempFiles:
string sTemp = Path.GetTempFileName();
sReportFile = sTemp + ".report.xml";
File.Move(sTemp, sReportFile);
break;
case ReportFileDestination.FixedDir:
sReportFile = m_sReportFixedDir + Path.DirectorySeparatorChar +
Path.GetFileName(sFontFile) + ".report.xml";
break;
case ReportFileDestination.SameDirAsFont:
sReportFile = sFontFile + ".report.xml";
break;
}
return sReportFile;
}
public void OnBeginFontTest( string fname, int nth, int nFonts )
{
string label = fname + " (file " + (nth+1) + " of " + nFonts + ")";
StdOut( label );
}
public void DeleteTempFiles()
{
if ( m_ReportFileDestination == ReportFileDestination.TempFiles )
{
for ( int i = 0; i < m_reportFiles.Count; i++ ) {
File.Delete( m_reportFiles[i] );
}
}
}
public int DoIt( )
{
Validator v = new Validator();
m_vp.SetupValidator( v );
OTFontFileVal.Driver driver = new OTFontFileVal.Driver( this );
return driver.RunValidation( v, m_sFiles );
}
public CmdLineInterface( ValidatorParameters vp,
string [] sFilenames,
ReportFileDestination rfd,
bool bOpenReportFiles,
string sReportFixedDir )
{
m_vp = vp;
m_sFiles = sFilenames;
m_ReportFileDestination = rfd;
m_bOpenReportFiles = bOpenReportFiles;
m_sReportFixedDir = sReportFixedDir;
}
static void Usage()
{
Console.WriteLine( "Usage: FontValidator [options]" );
Console.WriteLine( "" );
Console.WriteLine( "Options:" );
Console.WriteLine( "-file <fontfile> (multiple allowed)" );
Console.WriteLine( "+table <table-include> (multible allowed)" );
Console.WriteLine( "-table <table-skip> (multiple allowed)" );
Console.WriteLine( "-all-tables" );
Console.WriteLine( "-only-tables" );
Console.WriteLine( "-report-dir <reportDir>" );
Console.WriteLine( "-report-in-font-dir" );
Console.WriteLine( "" );
Console.WriteLine( "Valid table names (note the space after \"CFF \" and \"cvt \"):" );
string [] allTables = TableManager.GetKnownOTTableTypes();
Console.Write(allTables[0]);
for ( int k = 1; k < allTables.Length; k++ )
Console.Write(",{0}", allTables[k]);
Console.WriteLine( "" );
Console.WriteLine( "" );
Console.WriteLine( "Example:" );
Console.WriteLine( " FontValidator -file arial.ttf -file times.ttf -table 'OS/2' -table DSIG -report-dir /tmp");
}
static int Main( string[] args )
{
bool err = false;
string reportDir = null;
ReportFileDestination rfd = ReportFileDestination.TempFiles;
List<string> sFileList = new List<string>();
ValidatorParameters vp = new ValidatorParameters();
if (args.Length == 0) {
Usage();
return 0;
}
for ( int i = 0; i < args.Length; i++ ) {
if ( "-file" == args[i] ) {
i++;
if ( i < args.Length ) {
sFileList.Add( args[i] );
} else {
ErrOut( "Argument required for \"" + args[i-1] + "\"" );
err = true;
}
}
else if ( "+table" == args[i] ) {
if ( i < args.Length ) {
vp.AddTable( args[i] );
} else {
ErrOut( "Argument required for \"" + args[i-1] + "\"" );
err = true;
}
}
else if ( "-table" == args[i] ) {
i++;
if ( i < args.Length ) {
int n = vp.RemoveTableFromList( args[i] );
if ( 0 == n ) {
ErrOut( "Table \"" + args[i] + "\" not found" );
err = true;
}
} else {
ErrOut( "Argument required for \"" + args[i-1] + "\"" );
err = true;
}
}
else if ( "-all-tables" == args[i] ) {
vp.SetAllTables();
}
else if ( "-only-tables" == args[i] ) {
vp.ClearTables();
}
else if ( "-report-dir" == args[i] ) {
i++;
if ( i < args.Length ) {
reportDir = args[i];
rfd = ReportFileDestination.FixedDir;
} else {
ErrOut( "Argument required for \"" + args[i-1] + "\"" );
err = true;
}
}
else if ( "-report-in-font-dir" == args[i] ) {
rfd = ReportFileDestination.SameDirAsFont;
}
else {
ErrOut( "Unknown argument: \"" + args[i] + "\"" );
err = true;
}
}
if ( err ) {
Usage();
return 1;
}
CmdLineInterface cmd = new
CmdLineInterface( vp, sFileList.ToArray(), rfd, false,
reportDir );
return cmd.DoIt();
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: A1024Response.txt
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.ProtocolBuffers;
using pbc = global::Google.ProtocolBuffers.Collections;
using pbd = global::Google.ProtocolBuffers.Descriptors;
using scg = global::System.Collections.Generic;
namespace DolphinServer.ProtoEntity {
namespace Proto {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class A1024Response {
#region Extension registration
public static void RegisterAllExtensions(pb::ExtensionRegistry registry) {
}
#endregion
#region Static variables
internal static pbd::MessageDescriptor internal__static_A1024Response__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::DolphinServer.ProtoEntity.A1024Response, global::DolphinServer.ProtoEntity.A1024Response.Builder> internal__static_A1024Response__FieldAccessorTable;
#endregion
#region Descriptor
public static pbd::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbd::FileDescriptor descriptor;
static A1024Response() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"ChFBMTAyNFJlc3BvbnNlLnR4dCJQCg1BMTAyNFJlc3BvbnNlEhEKCUVycm9y",
"SW5mbxgBIAEoCRIRCglFcnJvckNvZGUYAiABKAUSDAoEQ2FyZBgDIAEoBRIL",
"CgNVaWQYBCABKAlCHKoCGURvbHBoaW5TZXJ2ZXIuUHJvdG9FbnRpdHk="));
pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) {
descriptor = root;
internal__static_A1024Response__Descriptor = Descriptor.MessageTypes[0];
internal__static_A1024Response__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::DolphinServer.ProtoEntity.A1024Response, global::DolphinServer.ProtoEntity.A1024Response.Builder>(internal__static_A1024Response__Descriptor,
new string[] { "ErrorInfo", "ErrorCode", "Card", "Uid", });
pb::ExtensionRegistry registry = pb::ExtensionRegistry.CreateInstance();
RegisterAllExtensions(registry);
return registry;
};
pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbd::FileDescriptor[] {
}, assigner);
}
#endregion
}
}
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class A1024Response : pb::GeneratedMessage<A1024Response, A1024Response.Builder> {
private A1024Response() { }
private static readonly A1024Response defaultInstance = new A1024Response().MakeReadOnly();
private static readonly string[] _a1024ResponseFieldNames = new string[] { "Card", "ErrorCode", "ErrorInfo", "Uid" };
private static readonly uint[] _a1024ResponseFieldTags = new uint[] { 24, 16, 10, 34 };
public static A1024Response DefaultInstance {
get { return defaultInstance; }
}
public override A1024Response DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override A1024Response ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::DolphinServer.ProtoEntity.Proto.A1024Response.internal__static_A1024Response__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<A1024Response, A1024Response.Builder> InternalFieldAccessors {
get { return global::DolphinServer.ProtoEntity.Proto.A1024Response.internal__static_A1024Response__FieldAccessorTable; }
}
public const int ErrorInfoFieldNumber = 1;
private bool hasErrorInfo;
private string errorInfo_ = "";
public bool HasErrorInfo {
get { return hasErrorInfo; }
}
public string ErrorInfo {
get { return errorInfo_; }
}
public const int ErrorCodeFieldNumber = 2;
private bool hasErrorCode;
private int errorCode_;
public bool HasErrorCode {
get { return hasErrorCode; }
}
public int ErrorCode {
get { return errorCode_; }
}
public const int CardFieldNumber = 3;
private bool hasCard;
private int card_;
public bool HasCard {
get { return hasCard; }
}
public int Card {
get { return card_; }
}
public const int UidFieldNumber = 4;
private bool hasUid;
private string uid_ = "";
public bool HasUid {
get { return hasUid; }
}
public string Uid {
get { return uid_; }
}
public override bool IsInitialized {
get {
return true;
}
}
public override void WriteTo(pb::ICodedOutputStream output) {
CalcSerializedSize();
string[] field_names = _a1024ResponseFieldNames;
if (hasErrorInfo) {
output.WriteString(1, field_names[2], ErrorInfo);
}
if (hasErrorCode) {
output.WriteInt32(2, field_names[1], ErrorCode);
}
if (hasCard) {
output.WriteInt32(3, field_names[0], Card);
}
if (hasUid) {
output.WriteString(4, field_names[3], Uid);
}
UnknownFields.WriteTo(output);
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
int size = memoizedSerializedSize;
if (size != -1) return size;
return CalcSerializedSize();
}
}
private int CalcSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (hasErrorInfo) {
size += pb::CodedOutputStream.ComputeStringSize(1, ErrorInfo);
}
if (hasErrorCode) {
size += pb::CodedOutputStream.ComputeInt32Size(2, ErrorCode);
}
if (hasCard) {
size += pb::CodedOutputStream.ComputeInt32Size(3, Card);
}
if (hasUid) {
size += pb::CodedOutputStream.ComputeStringSize(4, Uid);
}
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
public static A1024Response ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static A1024Response ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static A1024Response ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static A1024Response ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static A1024Response ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static A1024Response ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static A1024Response ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static A1024Response ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static A1024Response ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static A1024Response ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private A1024Response MakeReadOnly() {
return this;
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(A1024Response prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::GeneratedBuilder<A1024Response, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(A1024Response cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private A1024Response result;
private A1024Response PrepareBuilder() {
if (resultIsReadOnly) {
A1024Response original = result;
result = new A1024Response();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override A1024Response MessageBeingBuilt {
get { return PrepareBuilder(); }
}
public override Builder Clear() {
result = DefaultInstance;
resultIsReadOnly = true;
return this;
}
public override Builder Clone() {
if (resultIsReadOnly) {
return new Builder(result);
} else {
return new Builder().MergeFrom(result);
}
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::DolphinServer.ProtoEntity.A1024Response.Descriptor; }
}
public override A1024Response DefaultInstanceForType {
get { return global::DolphinServer.ProtoEntity.A1024Response.DefaultInstance; }
}
public override A1024Response BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is A1024Response) {
return MergeFrom((A1024Response) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(A1024Response other) {
if (other == global::DolphinServer.ProtoEntity.A1024Response.DefaultInstance) return this;
PrepareBuilder();
if (other.HasErrorInfo) {
ErrorInfo = other.ErrorInfo;
}
if (other.HasErrorCode) {
ErrorCode = other.ErrorCode;
}
if (other.HasCard) {
Card = other.Card;
}
if (other.HasUid) {
Uid = other.Uid;
}
this.MergeUnknownFields(other.UnknownFields);
return this;
}
public override Builder MergeFrom(pb::ICodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
PrepareBuilder();
pb::UnknownFieldSet.Builder unknownFields = null;
uint tag;
string field_name;
while (input.ReadTag(out tag, out field_name)) {
if(tag == 0 && field_name != null) {
int field_ordinal = global::System.Array.BinarySearch(_a1024ResponseFieldNames, field_name, global::System.StringComparer.Ordinal);
if(field_ordinal >= 0)
tag = _a1024ResponseFieldTags[field_ordinal];
else {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
continue;
}
}
switch (tag) {
case 0: {
throw pb::InvalidProtocolBufferException.InvalidTag();
}
default: {
if (pb::WireFormat.IsEndGroupTag(tag)) {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
break;
}
case 10: {
result.hasErrorInfo = input.ReadString(ref result.errorInfo_);
break;
}
case 16: {
result.hasErrorCode = input.ReadInt32(ref result.errorCode_);
break;
}
case 24: {
result.hasCard = input.ReadInt32(ref result.card_);
break;
}
case 34: {
result.hasUid = input.ReadString(ref result.uid_);
break;
}
}
}
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
public bool HasErrorInfo {
get { return result.hasErrorInfo; }
}
public string ErrorInfo {
get { return result.ErrorInfo; }
set { SetErrorInfo(value); }
}
public Builder SetErrorInfo(string value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.hasErrorInfo = true;
result.errorInfo_ = value;
return this;
}
public Builder ClearErrorInfo() {
PrepareBuilder();
result.hasErrorInfo = false;
result.errorInfo_ = "";
return this;
}
public bool HasErrorCode {
get { return result.hasErrorCode; }
}
public int ErrorCode {
get { return result.ErrorCode; }
set { SetErrorCode(value); }
}
public Builder SetErrorCode(int value) {
PrepareBuilder();
result.hasErrorCode = true;
result.errorCode_ = value;
return this;
}
public Builder ClearErrorCode() {
PrepareBuilder();
result.hasErrorCode = false;
result.errorCode_ = 0;
return this;
}
public bool HasCard {
get { return result.hasCard; }
}
public int Card {
get { return result.Card; }
set { SetCard(value); }
}
public Builder SetCard(int value) {
PrepareBuilder();
result.hasCard = true;
result.card_ = value;
return this;
}
public Builder ClearCard() {
PrepareBuilder();
result.hasCard = false;
result.card_ = 0;
return this;
}
public bool HasUid {
get { return result.hasUid; }
}
public string Uid {
get { return result.Uid; }
set { SetUid(value); }
}
public Builder SetUid(string value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.hasUid = true;
result.uid_ = value;
return this;
}
public Builder ClearUid() {
PrepareBuilder();
result.hasUid = false;
result.uid_ = "";
return this;
}
}
static A1024Response() {
object.ReferenceEquals(global::DolphinServer.ProtoEntity.Proto.A1024Response.Descriptor, null);
}
}
#endregion
}
#endregion Designer generated code
| |
using System;
using ModestTree;
#if !ZEN_NOT_UNITY3D
using UnityEngine;
#endif
namespace Zenject
{
public abstract class TypeBinder : BinderBase
{
readonly SingletonProviderMap _singletonMap;
public TypeBinder(
DiContainer container,
Type contractType,
string bindIdentifier,
SingletonProviderMap singletonMap)
: base(container, contractType, bindIdentifier)
{
_singletonMap = singletonMap;
}
public BindingConditionSetter ToTransient()
{
#if !ZEN_NOT_UNITY3D
if (ContractType.DerivesFrom(typeof(Component)))
{
throw new ZenjectBindException(
"Should not use ToTransient for Monobehaviours (when binding type '{0}'), you probably want either ToLookup or ToTransientFromPrefab"
.Fmt(ContractType.Name()));
}
#endif
return ToProvider(new TransientProvider(Container, ContractType));
}
public BindingConditionSetter ToTransient(Type concreteType)
{
#if !ZEN_NOT_UNITY3D
if (concreteType.DerivesFrom(typeof(Component)))
{
throw new ZenjectBindException(
"Should not use ToTransient for Monobehaviours (when binding type '{0}'), you probably want either ToLookup or ToTransientFromPrefab"
.Fmt(concreteType.Name()));
}
#endif
return ToProvider(new TransientProvider(Container, concreteType));
}
public BindingConditionSetter ToSingle()
{
return ToSingle((string)null);
}
public BindingConditionSetter ToSingle(string concreteIdentifier)
{
#if !ZEN_NOT_UNITY3D
if (ContractType.DerivesFrom(typeof(Component)))
{
throw new ZenjectBindException(
"Should not use ToSingle for Monobehaviours (when binding type '{0}'), you probably want either ToLookup or ToSinglePrefab or ToSingleGameObject"
.Fmt(ContractType.Name()));
}
#endif
return ToProvider(_singletonMap.CreateProviderFromType(concreteIdentifier, ContractType));
}
public BindingConditionSetter ToSingle(Type concreteType)
{
return ToSingle(null, concreteType);
}
public BindingConditionSetter ToSingle(string concreteIdentifier, Type concreteType)
{
if (!concreteType.DerivesFromOrEqual(ContractType))
{
throw new ZenjectBindException(
"Invalid type given during bind command. Expected type '{0}' to derive from type '{1}'".Fmt(concreteType.Name(), ContractType.Name()));
}
return ToProvider(_singletonMap.CreateProviderFromType(concreteIdentifier, concreteType));
}
public BindingConditionSetter ToSingle(Type concreteType, string concreteIdentifier)
{
if (!concreteType.DerivesFromOrEqual(ContractType))
{
throw new ZenjectBindException(
"Invalid type given during bind command. Expected type '{0}' to derive from type '{1}'".Fmt(concreteType.Name(), ContractType.Name()));
}
#if !ZEN_NOT_UNITY3D
if (concreteType.DerivesFrom(typeof(Component)))
{
throw new ZenjectBindException(
"Should not use ToSingle for Monobehaviours (when binding type '{0}' to '{1}'), you probably want either ToLookup or ToSinglePrefab or ToSinglePrefabResource or ToSingleGameObject"
.Fmt(ContractType.Name(), concreteType.Name()));
}
#endif
return ToProvider(_singletonMap.CreateProviderFromType(concreteIdentifier, concreteType));
}
#if !ZEN_NOT_UNITY3D
// Note that concreteType here could be an interface as well
public BindingConditionSetter ToSinglePrefab(
Type concreteType, string concreteIdentifier, GameObject prefab)
{
if (!concreteType.DerivesFromOrEqual(ContractType))
{
throw new ZenjectBindException(
"Invalid type given during bind command. Expected type '{0}' to derive from type '{1}'".Fmt(concreteType.Name(), ContractType.Name()));
}
if (ZenUtil.IsNull(prefab))
{
throw new ZenjectBindException(
"Received null prefab while binding type '{0}'".Fmt(concreteType.Name()));
}
var prefabSingletonMap = Container.Resolve<PrefabSingletonProviderMap>();
return ToProvider(
prefabSingletonMap.CreateProvider(concreteIdentifier, concreteType, prefab, null));
}
public BindingConditionSetter ToTransientPrefab(Type concreteType, GameObject prefab)
{
if (!concreteType.DerivesFromOrEqual(ContractType))
{
throw new ZenjectBindException(
"Invalid type given during bind command. Expected type '{0}' to derive from type '{1}'".Fmt(concreteType.Name(), ContractType.Name()));
}
// We have to cast to object otherwise we get SecurityExceptions when this function is run outside of unity
if (ZenUtil.IsNull(prefab))
{
throw new ZenjectBindException("Received null prefab while binding type '{0}'".Fmt(concreteType.Name()));
}
return ToProvider(new GameObjectTransientProviderFromPrefab(concreteType, Container, prefab));
}
public BindingConditionSetter ToSingleGameObject()
{
return ToSingleGameObject(ContractType.Name());
}
// Creates a new game object and adds the given type as a new component on it
// NOTE! The string given here is just a name and not a singleton identifier
public BindingConditionSetter ToSingleGameObject(string name)
{
if (!ContractType.IsSubclassOf(typeof(Component)))
{
throw new ZenjectBindException("Expected UnityEngine.Component derived type when binding type '{0}'".Fmt(ContractType.Name()));
}
return ToProvider(new GameObjectSingletonProvider(ContractType, Container, name));
}
// Creates a new game object and adds the given type as a new component on it
// NOTE! The string given here is just a name and not a singleton identifier
public BindingConditionSetter ToSingleGameObject(Type concreteType, string name)
{
if (!concreteType.DerivesFromOrEqual(ContractType))
{
throw new ZenjectBindException(
"Invalid type given during bind command. Expected type '{0}' to derive from type '{1}'".Fmt(concreteType.Name(), ContractType.Name()));
}
return ToProvider(new GameObjectSingletonProvider(concreteType, Container, name));
}
public BindingConditionSetter ToTransientPrefabResource(string resourcePath)
{
return ToTransientPrefabResource(ContractType, resourcePath);
}
public BindingConditionSetter ToTransientPrefabResource(Type concreteType, string resourcePath)
{
Assert.IsNotNull(resourcePath);
return ToProvider(new GameObjectTransientProviderFromPrefabResource(concreteType, Container, resourcePath));
}
public BindingConditionSetter ToSinglePrefabResource(Type concreteType, string concreteIdentifier, string resourcePath)
{
Assert.That(concreteType.DerivesFromOrEqual(ContractType));
Assert.IsNotNull(resourcePath);
var prefabSingletonMap = Container.Resolve<PrefabSingletonProviderMap>();
return ToProvider(
prefabSingletonMap.CreateProvider(concreteIdentifier, concreteType, null, resourcePath));
}
public BindingConditionSetter ToSinglePrefabResource(string resourcePath)
{
return ToSinglePrefabResource(null, resourcePath);
}
public BindingConditionSetter ToSinglePrefabResource(string identifier, string resourcePath)
{
return ToSinglePrefabResource(ContractType, identifier, resourcePath);
}
public BindingConditionSetter ToTransientPrefab(GameObject prefab)
{
return ToTransientPrefab(ContractType, prefab);
}
public BindingConditionSetter ToSinglePrefab(GameObject prefab)
{
return ToSinglePrefab(null, prefab);
}
public BindingConditionSetter ToSinglePrefab(string identifier, GameObject prefab)
{
return ToSinglePrefab(ContractType, identifier, prefab);
}
#endif
protected BindingConditionSetter ToSingleMethodBase<TConcrete>(string concreteIdentifier, Func<InjectContext, TConcrete> method)
{
return ToProvider(_singletonMap.CreateProviderFromMethod(concreteIdentifier, method));
}
protected BindingConditionSetter ToSingleFactoryBase<TConcrete, TFactory>(string concreteIdentifier)
where TFactory : IFactory<TConcrete>
{
return ToProvider(_singletonMap.CreateProviderFromFactory<TConcrete, TFactory>(concreteIdentifier));
}
protected BindingConditionSetter ToMethodBase<T>(Func<InjectContext, T> method)
{
if (!typeof(T).DerivesFromOrEqual(ContractType))
{
throw new ZenjectBindException(
"Invalid type given during bind command. Expected type '{0}' to derive from type '{1}'".Fmt(typeof(T), ContractType.Name()));
}
return ToProvider(new MethodProvider<T>(method));
}
protected BindingConditionSetter ToLookupBase<TConcrete>(string identifier)
{
return ToMethodBase<TConcrete>((ctx) => ctx.Container.Resolve<TConcrete>(
new InjectContext(
ctx.Container, typeof(TConcrete), identifier,
false, ctx.ObjectType, ctx.ObjectInstance, ctx.MemberName, ctx, null, ctx.FallBackValue, ctx.LocalOnly)));
}
protected BindingConditionSetter ToGetterBase<TObj, TResult>(string identifier, Func<TObj, TResult> method)
{
return ToMethodBase((ctx) => method(ctx.Container.Resolve<TObj>(
new InjectContext(
ctx.Container, typeof(TObj), identifier,
false, ctx.ObjectType, ctx.ObjectInstance, ctx.MemberName, ctx, null, ctx.FallBackValue, ctx.LocalOnly))));
}
public BindingConditionSetter ToInstance(Type concreteType, object instance)
{
if (ZenUtil.IsNull(instance) && !Container.IsValidating)
{
string message;
if (ContractType == concreteType)
{
message = "Received null instance during Bind command with type '{0}'".Fmt(ContractType.Name());
}
else
{
message =
"Received null instance during Bind command when binding type '{0}' to '{1}'".Fmt(ContractType.Name(), concreteType.Name());
}
throw new ZenjectBindException(message);
}
if (!ZenUtil.IsNull(instance) && !instance.GetType().DerivesFromOrEqual(ContractType))
{
throw new ZenjectBindException(
"Invalid type given during bind command. Expected type '{0}' to derive from type '{1}'".Fmt(concreteType.Name(), ContractType.Name()));
}
return ToProvider(new InstanceProvider(concreteType, instance));
}
protected BindingConditionSetter ToSingleInstance(Type concreteType, string concreteIdentifier, object instance)
{
if (!concreteType.DerivesFromOrEqual(ContractType))
{
throw new ZenjectBindException(
"Invalid type given during bind command. Expected type '{0}' to derive from type '{1}'".Fmt(concreteType.Name(), ContractType.Name()));
}
if (ZenUtil.IsNull(instance) && !Container.IsValidating)
{
string message;
if (ContractType == concreteType)
{
message = "Received null singleton instance during Bind command with type '{0}'".Fmt(ContractType.Name());
}
else
{
message =
"Received null singleton instance during Bind command when binding type '{0}' to '{1}'".Fmt(ContractType.Name(), concreteType.Name());
}
throw new ZenjectBindException(message);
}
return ToProvider(_singletonMap.CreateProviderFromInstance(concreteIdentifier, concreteType, instance));
}
#if !ZEN_NOT_UNITY3D
protected BindingConditionSetter ToSingleMonoBehaviourBase<TConcrete>(GameObject gameObject)
{
return ToProvider(new MonoBehaviourSingletonProvider(typeof(TConcrete), Container, gameObject));
}
public BindingConditionSetter ToResource(string resourcePath)
{
return ToResource(ContractType, resourcePath);
}
public BindingConditionSetter ToResource(Type concreteType, string resourcePath)
{
if (!concreteType.DerivesFromOrEqual(ContractType))
{
throw new ZenjectBindException(
"Invalid type given during bind command. Expected type '{0}' to derive from type '{1}'".Fmt(concreteType.Name(), ContractType.Name()));
}
return ToProvider(new ResourceProvider(concreteType, resourcePath));
}
#endif
}
}
| |
// 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.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace Microsoft.Win32.SafeHandles
{
public sealed partial class SafeX509ChainHandle : Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid
{
internal SafeX509ChainHandle() : base(default(bool)) { }
public override bool IsInvalid { get { throw null; } }
protected override void Dispose(bool disposing) { }
protected override bool ReleaseHandle() { throw null; }
}
}
namespace System.Security.Cryptography.X509Certificates
{
public sealed partial class CertificateRequest
{
public CertificateRequest(System.Security.Cryptography.X509Certificates.X500DistinguishedName subjectName, System.Security.Cryptography.ECDsa key, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { }
public CertificateRequest(System.Security.Cryptography.X509Certificates.X500DistinguishedName subjectName, System.Security.Cryptography.RSA key, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { }
public CertificateRequest(System.Security.Cryptography.X509Certificates.X500DistinguishedName subjectName, System.Security.Cryptography.X509Certificates.PublicKey publicKey, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { }
public CertificateRequest(string subjectName, System.Security.Cryptography.ECDsa key, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { }
public CertificateRequest(string subjectName, System.Security.Cryptography.RSA key, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { }
public System.Collections.ObjectModel.Collection<System.Security.Cryptography.X509Certificates.X509Extension> CertificateExtensions { get { throw null; } }
public System.Security.Cryptography.HashAlgorithmName HashAlgorithm { get { throw null; } }
public System.Security.Cryptography.X509Certificates.PublicKey PublicKey { get { throw null; } }
public System.Security.Cryptography.X509Certificates.X500DistinguishedName SubjectName { get { throw null; } }
public System.Security.Cryptography.X509Certificates.X509Certificate2 Create(System.Security.Cryptography.X509Certificates.X500DistinguishedName issuerName, System.Security.Cryptography.X509Certificates.X509SignatureGenerator generator, System.DateTimeOffset notBefore, System.DateTimeOffset notAfter, byte[] serialNumber) { throw null; }
public System.Security.Cryptography.X509Certificates.X509Certificate2 Create(System.Security.Cryptography.X509Certificates.X509Certificate2 issuerCertificate, System.DateTimeOffset notBefore, System.DateTimeOffset notAfter, byte[] serialNumber) { throw null; }
public System.Security.Cryptography.X509Certificates.X509Certificate2 CreateSelfSigned(System.DateTimeOffset notBefore, System.DateTimeOffset notAfter) { throw null; }
public byte[] CreateSigningRequest() { throw null; }
public byte[] CreateSigningRequest(System.Security.Cryptography.X509Certificates.X509SignatureGenerator signatureGenerator) { throw null; }
}
public static partial class DSACertificateExtensions
{
public static System.Security.Cryptography.X509Certificates.X509Certificate2 CopyWithPrivateKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate, System.Security.Cryptography.DSA privateKey) { throw null; }
public static System.Security.Cryptography.DSA GetDSAPrivateKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; }
public static System.Security.Cryptography.DSA GetDSAPublicKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; }
}
public static partial class ECDsaCertificateExtensions
{
public static System.Security.Cryptography.X509Certificates.X509Certificate2 CopyWithPrivateKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate, System.Security.Cryptography.ECDsa privateKey) { throw null; }
public static System.Security.Cryptography.ECDsa GetECDsaPrivateKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; }
public static System.Security.Cryptography.ECDsa GetECDsaPublicKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; }
}
[System.FlagsAttribute]
public enum OpenFlags
{
IncludeArchived = 8,
MaxAllowed = 2,
OpenExistingOnly = 4,
ReadOnly = 0,
ReadWrite = 1,
}
public sealed partial class PublicKey
{
public PublicKey(System.Security.Cryptography.Oid oid, System.Security.Cryptography.AsnEncodedData parameters, System.Security.Cryptography.AsnEncodedData keyValue) { }
public System.Security.Cryptography.AsnEncodedData EncodedKeyValue { get { throw null; } }
public System.Security.Cryptography.AsnEncodedData EncodedParameters { get { throw null; } }
public System.Security.Cryptography.AsymmetricAlgorithm Key { get { throw null; } }
public System.Security.Cryptography.Oid Oid { get { throw null; } }
}
public static partial class RSACertificateExtensions
{
public static System.Security.Cryptography.X509Certificates.X509Certificate2 CopyWithPrivateKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate, System.Security.Cryptography.RSA privateKey) { throw null; }
public static System.Security.Cryptography.RSA GetRSAPrivateKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; }
public static System.Security.Cryptography.RSA GetRSAPublicKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; }
}
public enum StoreLocation
{
CurrentUser = 1,
LocalMachine = 2,
}
public enum StoreName
{
AddressBook = 1,
AuthRoot = 2,
CertificateAuthority = 3,
Disallowed = 4,
My = 5,
Root = 6,
TrustedPeople = 7,
TrustedPublisher = 8,
}
public sealed partial class SubjectAlternativeNameBuilder
{
public SubjectAlternativeNameBuilder() { }
public void AddDnsName(string dnsName) { }
public void AddEmailAddress(string emailAddress) { }
public void AddIpAddress(System.Net.IPAddress ipAddress) { }
public void AddUri(System.Uri uri) { }
public void AddUserPrincipalName(string upn) { }
public System.Security.Cryptography.X509Certificates.X509Extension Build(bool critical=false) { throw null; }
}
public sealed partial class X500DistinguishedName : System.Security.Cryptography.AsnEncodedData
{
public X500DistinguishedName(byte[] encodedDistinguishedName) { }
public X500DistinguishedName(System.Security.Cryptography.AsnEncodedData encodedDistinguishedName) { }
public X500DistinguishedName(System.Security.Cryptography.X509Certificates.X500DistinguishedName distinguishedName) { }
public X500DistinguishedName(string distinguishedName) { }
public X500DistinguishedName(string distinguishedName, System.Security.Cryptography.X509Certificates.X500DistinguishedNameFlags flag) { }
public string Name { get { throw null; } }
public string Decode(System.Security.Cryptography.X509Certificates.X500DistinguishedNameFlags flag) { throw null; }
public override string Format(bool multiLine) { throw null; }
}
[System.FlagsAttribute]
public enum X500DistinguishedNameFlags
{
DoNotUsePlusSign = 32,
DoNotUseQuotes = 64,
ForceUTF8Encoding = 16384,
None = 0,
Reversed = 1,
UseCommas = 128,
UseNewLines = 256,
UseSemicolons = 16,
UseT61Encoding = 8192,
UseUTF8Encoding = 4096,
}
public sealed partial class X509BasicConstraintsExtension : System.Security.Cryptography.X509Certificates.X509Extension
{
public X509BasicConstraintsExtension() { }
public X509BasicConstraintsExtension(bool certificateAuthority, bool hasPathLengthConstraint, int pathLengthConstraint, bool critical) { }
public X509BasicConstraintsExtension(System.Security.Cryptography.AsnEncodedData encodedBasicConstraints, bool critical) { }
public bool CertificateAuthority { get { throw null; } }
public bool HasPathLengthConstraint { get { throw null; } }
public int PathLengthConstraint { get { throw null; } }
public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { }
}
public partial class X509Certificate : System.IDisposable, System.Runtime.Serialization.ISerializable, System.Runtime.Serialization.IDeserializationCallback
{
public X509Certificate() { }
public X509Certificate(byte[] data) { }
[System.CLSCompliantAttribute(false)]
public X509Certificate(byte[] rawData, System.Security.SecureString password) { }
[System.CLSCompliantAttribute(false)]
public X509Certificate(byte[] rawData, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { }
public X509Certificate(byte[] rawData, string password) { }
public X509Certificate(byte[] rawData, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { }
public X509Certificate(System.IntPtr handle) { }
public X509Certificate(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public X509Certificate(System.Security.Cryptography.X509Certificates.X509Certificate cert) { }
public X509Certificate(string fileName) { }
[System.CLSCompliantAttribute(false)]
public X509Certificate(string fileName, System.Security.SecureString password) { }
[System.CLSCompliantAttribute(false)]
public X509Certificate(string fileName, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { }
public X509Certificate(string fileName, string password) { }
public X509Certificate(string fileName, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { }
public System.IntPtr Handle { get { throw null; } }
public string Issuer { get { throw null; } }
public string Subject { get { throw null; } }
public static System.Security.Cryptography.X509Certificates.X509Certificate CreateFromCertFile(string filename) { throw null; }
public static System.Security.Cryptography.X509Certificates.X509Certificate CreateFromSignedFile(string filename) { throw null; }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public override bool Equals(object obj) { throw null; }
public virtual bool Equals(System.Security.Cryptography.X509Certificates.X509Certificate other) { throw null; }
public virtual byte[] Export(System.Security.Cryptography.X509Certificates.X509ContentType contentType) { throw null; }
[System.CLSCompliantAttribute(false)]
public virtual byte[] Export(System.Security.Cryptography.X509Certificates.X509ContentType contentType, System.Security.SecureString password) { throw null; }
public virtual byte[] Export(System.Security.Cryptography.X509Certificates.X509ContentType contentType, string password) { throw null; }
protected static string FormatDate(System.DateTime date) { throw null; }
public virtual byte[] GetCertHash() { throw null; }
public virtual string GetCertHashString() { throw null; }
public virtual string GetEffectiveDateString() { throw null; }
public virtual string GetExpirationDateString() { throw null; }
public virtual string GetFormat() { throw null; }
public override int GetHashCode() { throw null; }
[System.ObsoleteAttribute("This method has been deprecated. Please use the Issuer property instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public virtual string GetIssuerName() { throw null; }
public virtual string GetKeyAlgorithm() { throw null; }
public virtual byte[] GetKeyAlgorithmParameters() { throw null; }
public virtual string GetKeyAlgorithmParametersString() { throw null; }
[System.ObsoleteAttribute("This method has been deprecated. Please use the Subject property instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public virtual string GetName() { throw null; }
public virtual byte[] GetPublicKey() { throw null; }
public virtual string GetPublicKeyString() { throw null; }
public virtual byte[] GetRawCertData() { throw null; }
public virtual string GetRawCertDataString() { throw null; }
public virtual byte[] GetSerialNumber() { throw null; }
public virtual string GetSerialNumberString() { throw null; }
public virtual void Import(byte[] rawData) { }
[System.CLSCompliantAttribute(false)]
public virtual void Import(byte[] rawData, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { }
public virtual void Import(byte[] rawData, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { }
public virtual void Import(string fileName) { }
[System.CLSCompliantAttribute(false)]
public virtual void Import(string fileName, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { }
public virtual void Import(string fileName, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { }
public virtual void Reset() { }
void System.Runtime.Serialization.IDeserializationCallback.OnDeserialization(object sender) { }
void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public override string ToString() { throw null; }
public virtual string ToString(bool fVerbose) { throw null; }
}
public partial class X509Certificate2 : System.Security.Cryptography.X509Certificates.X509Certificate
{
public X509Certificate2() { }
public X509Certificate2(byte[] rawData) { }
[System.CLSCompliantAttribute(false)]
public X509Certificate2(byte[] rawData, System.Security.SecureString password) { }
[System.CLSCompliantAttribute(false)]
public X509Certificate2(byte[] rawData, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { }
public X509Certificate2(byte[] rawData, string password) { }
public X509Certificate2(byte[] rawData, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { }
public X509Certificate2(System.IntPtr handle) { }
protected X509Certificate2(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public X509Certificate2(System.Security.Cryptography.X509Certificates.X509Certificate certificate) { }
public X509Certificate2(string fileName) { }
[System.CLSCompliantAttribute(false)]
public X509Certificate2(string fileName, System.Security.SecureString password) { }
[System.CLSCompliantAttribute(false)]
public X509Certificate2(string fileName, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { }
public X509Certificate2(string fileName, string password) { }
public X509Certificate2(string fileName, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { }
public bool Archived { get { throw null; } set { } }
public System.Security.Cryptography.X509Certificates.X509ExtensionCollection Extensions { get { throw null; } }
public string FriendlyName { get { throw null; } set { } }
public bool HasPrivateKey { get { throw null; } }
public System.Security.Cryptography.X509Certificates.X500DistinguishedName IssuerName { get { throw null; } }
public System.DateTime NotAfter { get { throw null; } }
public System.DateTime NotBefore { get { throw null; } }
public System.Security.Cryptography.AsymmetricAlgorithm PrivateKey { get { throw null; } set { } }
public System.Security.Cryptography.X509Certificates.PublicKey PublicKey { get { throw null; } }
public byte[] RawData { get { throw null; } }
public string SerialNumber { get { throw null; } }
public System.Security.Cryptography.Oid SignatureAlgorithm { get { throw null; } }
public System.Security.Cryptography.X509Certificates.X500DistinguishedName SubjectName { get { throw null; } }
public string Thumbprint { get { throw null; } }
public int Version { get { throw null; } }
public static System.Security.Cryptography.X509Certificates.X509ContentType GetCertContentType(byte[] rawData) { throw null; }
public static System.Security.Cryptography.X509Certificates.X509ContentType GetCertContentType(string fileName) { throw null; }
public string GetNameInfo(System.Security.Cryptography.X509Certificates.X509NameType nameType, bool forIssuer) { throw null; }
public override void Import(byte[] rawData) { }
[System.CLSCompliantAttribute(false)]
public override void Import(byte[] rawData, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { }
public override void Import(byte[] rawData, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { }
public override void Import(string fileName) { }
[System.CLSCompliantAttribute(false)]
public override void Import(string fileName, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { }
public override void Import(string fileName, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { }
public override void Reset() { }
public override string ToString() { throw null; }
public override string ToString(bool verbose) { throw null; }
public bool Verify() { throw null; }
}
public partial class X509Certificate2Collection : System.Security.Cryptography.X509Certificates.X509CertificateCollection
{
public X509Certificate2Collection() { }
public X509Certificate2Collection(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { }
public X509Certificate2Collection(System.Security.Cryptography.X509Certificates.X509Certificate2[] certificates) { }
public X509Certificate2Collection(System.Security.Cryptography.X509Certificates.X509Certificate2Collection certificates) { }
public new System.Security.Cryptography.X509Certificates.X509Certificate2 this[int index] { get { throw null; } set { } }
public int Add(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; }
public void AddRange(System.Security.Cryptography.X509Certificates.X509Certificate2[] certificates) { }
public void AddRange(System.Security.Cryptography.X509Certificates.X509Certificate2Collection certificates) { }
public bool Contains(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; }
public byte[] Export(System.Security.Cryptography.X509Certificates.X509ContentType contentType) { throw null; }
public byte[] Export(System.Security.Cryptography.X509Certificates.X509ContentType contentType, string password) { throw null; }
public System.Security.Cryptography.X509Certificates.X509Certificate2Collection Find(System.Security.Cryptography.X509Certificates.X509FindType findType, object findValue, bool validOnly) { throw null; }
public new System.Security.Cryptography.X509Certificates.X509Certificate2Enumerator GetEnumerator() { throw null; }
public void Import(byte[] rawData) { }
public void Import(byte[] rawData, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { }
public void Import(string fileName) { }
public void Import(string fileName, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { }
public void Insert(int index, System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { }
public void Remove(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { }
public void RemoveRange(System.Security.Cryptography.X509Certificates.X509Certificate2[] certificates) { }
public void RemoveRange(System.Security.Cryptography.X509Certificates.X509Certificate2Collection certificates) { }
}
public sealed partial class X509Certificate2Enumerator : System.Collections.IEnumerator
{
internal X509Certificate2Enumerator() { }
public System.Security.Cryptography.X509Certificates.X509Certificate2 Current { get { throw null; } }
object System.Collections.IEnumerator.Current { get { throw null; } }
public bool MoveNext() { throw null; }
public void Reset() { }
bool System.Collections.IEnumerator.MoveNext() { throw null; }
void System.Collections.IEnumerator.Reset() { }
}
public partial class X509CertificateCollection : System.Collections.CollectionBase
{
public X509CertificateCollection() { }
public X509CertificateCollection(System.Security.Cryptography.X509Certificates.X509Certificate[] value) { }
public X509CertificateCollection(System.Security.Cryptography.X509Certificates.X509CertificateCollection value) { }
public System.Security.Cryptography.X509Certificates.X509Certificate this[int index] { get { throw null; } set { } }
public int Add(System.Security.Cryptography.X509Certificates.X509Certificate value) { throw null; }
public void AddRange(System.Security.Cryptography.X509Certificates.X509Certificate[] value) { }
public void AddRange(System.Security.Cryptography.X509Certificates.X509CertificateCollection value) { }
public bool Contains(System.Security.Cryptography.X509Certificates.X509Certificate value) { throw null; }
public void CopyTo(System.Security.Cryptography.X509Certificates.X509Certificate[] array, int index) { }
public new System.Security.Cryptography.X509Certificates.X509CertificateCollection.X509CertificateEnumerator GetEnumerator() { throw null; }
public override int GetHashCode() { throw null; }
public int IndexOf(System.Security.Cryptography.X509Certificates.X509Certificate value) { throw null; }
public void Insert(int index, System.Security.Cryptography.X509Certificates.X509Certificate value) { }
public void Remove(System.Security.Cryptography.X509Certificates.X509Certificate value) { }
public partial class X509CertificateEnumerator : System.Collections.IEnumerator
{
public X509CertificateEnumerator(System.Security.Cryptography.X509Certificates.X509CertificateCollection mappings) { }
public System.Security.Cryptography.X509Certificates.X509Certificate Current { get { throw null; } }
object System.Collections.IEnumerator.Current { get { throw null; } }
public bool MoveNext() { throw null; }
public void Reset() { }
bool System.Collections.IEnumerator.MoveNext() { throw null; }
void System.Collections.IEnumerator.Reset() { }
}
}
public partial class X509Chain : System.IDisposable
{
public X509Chain() { }
public X509Chain(bool useMachineContext) { }
public X509Chain(System.IntPtr chainContext) { }
public static X509Chain Create() { throw null; }
public System.IntPtr ChainContext { get { throw null; } }
public System.Security.Cryptography.X509Certificates.X509ChainElementCollection ChainElements { get { throw null; } }
public System.Security.Cryptography.X509Certificates.X509ChainPolicy ChainPolicy { get { throw null; } set { } }
public System.Security.Cryptography.X509Certificates.X509ChainStatus[] ChainStatus { get { throw null; } }
public Microsoft.Win32.SafeHandles.SafeX509ChainHandle SafeHandle { get { throw null; } }
public bool Build(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public void Reset() { }
}
public partial class X509ChainElement
{
internal X509ChainElement() { }
public System.Security.Cryptography.X509Certificates.X509Certificate2 Certificate { get { throw null; } }
public System.Security.Cryptography.X509Certificates.X509ChainStatus[] ChainElementStatus { get { throw null; } }
public string Information { get { throw null; } }
}
public sealed partial class X509ChainElementCollection : System.Collections.ICollection, System.Collections.IEnumerable
{
internal X509ChainElementCollection() { }
public int Count { get { throw null; } }
public bool IsSynchronized { get { throw null; } }
public System.Security.Cryptography.X509Certificates.X509ChainElement this[int index] { get { throw null; } }
public object SyncRoot { get { throw null; } }
public void CopyTo(System.Security.Cryptography.X509Certificates.X509ChainElement[] array, int index) { }
public System.Security.Cryptography.X509Certificates.X509ChainElementEnumerator GetEnumerator() { throw null; }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
}
public sealed partial class X509ChainElementEnumerator : System.Collections.IEnumerator
{
internal X509ChainElementEnumerator() { }
public System.Security.Cryptography.X509Certificates.X509ChainElement Current { get { throw null; } }
object System.Collections.IEnumerator.Current { get { throw null; } }
public bool MoveNext() { throw null; }
public void Reset() { }
}
public sealed partial class X509ChainPolicy
{
public X509ChainPolicy() { }
public System.Security.Cryptography.OidCollection ApplicationPolicy { get { throw null; } }
public System.Security.Cryptography.OidCollection CertificatePolicy { get { throw null; } }
public System.Security.Cryptography.X509Certificates.X509Certificate2Collection ExtraStore { get { throw null; } }
public System.Security.Cryptography.X509Certificates.X509RevocationFlag RevocationFlag { get { throw null; } set { } }
public System.Security.Cryptography.X509Certificates.X509RevocationMode RevocationMode { get { throw null; } set { } }
public System.TimeSpan UrlRetrievalTimeout { get { throw null; } set { } }
public System.Security.Cryptography.X509Certificates.X509VerificationFlags VerificationFlags { get { throw null; } set { } }
public System.DateTime VerificationTime { get { throw null; } set { } }
public void Reset() { }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct X509ChainStatus
{
public System.Security.Cryptography.X509Certificates.X509ChainStatusFlags Status { get { throw null; } set { } }
public string StatusInformation { get { throw null; } set { } }
}
[System.FlagsAttribute]
public enum X509ChainStatusFlags
{
CtlNotSignatureValid = 262144,
CtlNotTimeValid = 131072,
CtlNotValidForUsage = 524288,
Cyclic = 128,
ExplicitDistrust = 67108864,
HasExcludedNameConstraint = 32768,
HasNotDefinedNameConstraint = 8192,
HasNotPermittedNameConstraint = 16384,
HasNotSupportedCriticalExtension = 134217728,
HasNotSupportedNameConstraint = 4096,
HasWeakSignature = 1048576,
InvalidBasicConstraints = 1024,
InvalidExtension = 256,
InvalidNameConstraints = 2048,
InvalidPolicyConstraints = 512,
NoError = 0,
NoIssuanceChainPolicy = 33554432,
NotSignatureValid = 8,
NotTimeNested = 2,
NotTimeValid = 1,
NotValidForUsage = 16,
OfflineRevocation = 16777216,
PartialChain = 65536,
RevocationStatusUnknown = 64,
Revoked = 4,
UntrustedRoot = 32,
}
public enum X509ContentType
{
Authenticode = 6,
Cert = 1,
Pfx = 3,
Pkcs12 = 3,
Pkcs7 = 5,
SerializedCert = 2,
SerializedStore = 4,
Unknown = 0,
}
public sealed partial class X509EnhancedKeyUsageExtension : System.Security.Cryptography.X509Certificates.X509Extension
{
public X509EnhancedKeyUsageExtension() { }
public X509EnhancedKeyUsageExtension(System.Security.Cryptography.AsnEncodedData encodedEnhancedKeyUsages, bool critical) { }
public X509EnhancedKeyUsageExtension(System.Security.Cryptography.OidCollection enhancedKeyUsages, bool critical) { }
public System.Security.Cryptography.OidCollection EnhancedKeyUsages { get { throw null; } }
public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { }
}
public partial class X509Extension : System.Security.Cryptography.AsnEncodedData
{
protected X509Extension() { }
public X509Extension(System.Security.Cryptography.AsnEncodedData encodedExtension, bool critical) { }
public X509Extension(System.Security.Cryptography.Oid oid, byte[] rawData, bool critical) { }
public X509Extension(string oid, byte[] rawData, bool critical) { }
public bool Critical { get { throw null; } set { } }
public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { }
}
public sealed partial class X509ExtensionCollection : System.Collections.ICollection, System.Collections.IEnumerable
{
public X509ExtensionCollection() { }
public int Count { get { throw null; } }
public bool IsSynchronized { get { throw null; } }
public System.Security.Cryptography.X509Certificates.X509Extension this[int index] { get { throw null; } }
public System.Security.Cryptography.X509Certificates.X509Extension this[string oid] { get { throw null; } }
public object SyncRoot { get { throw null; } }
public int Add(System.Security.Cryptography.X509Certificates.X509Extension extension) { throw null; }
public void CopyTo(System.Security.Cryptography.X509Certificates.X509Extension[] array, int index) { }
public System.Security.Cryptography.X509Certificates.X509ExtensionEnumerator GetEnumerator() { throw null; }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
}
public sealed partial class X509ExtensionEnumerator : System.Collections.IEnumerator
{
internal X509ExtensionEnumerator() { }
public System.Security.Cryptography.X509Certificates.X509Extension Current { get { throw null; } }
object System.Collections.IEnumerator.Current { get { throw null; } }
public bool MoveNext() { throw null; }
public void Reset() { }
}
public enum X509FindType
{
FindByApplicationPolicy = 10,
FindByCertificatePolicy = 11,
FindByExtension = 12,
FindByIssuerDistinguishedName = 4,
FindByIssuerName = 3,
FindByKeyUsage = 13,
FindBySerialNumber = 5,
FindBySubjectDistinguishedName = 2,
FindBySubjectKeyIdentifier = 14,
FindBySubjectName = 1,
FindByTemplateName = 9,
FindByThumbprint = 0,
FindByTimeExpired = 8,
FindByTimeNotYetValid = 7,
FindByTimeValid = 6,
}
public enum X509IncludeOption
{
EndCertOnly = 2,
ExcludeRoot = 1,
None = 0,
WholeChain = 3,
}
[System.FlagsAttribute]
public enum X509KeyStorageFlags
{
DefaultKeySet = 0,
EphemeralKeySet = 32,
Exportable = 4,
MachineKeySet = 2,
PersistKeySet = 16,
UserKeySet = 1,
UserProtected = 8,
}
public sealed partial class X509KeyUsageExtension : System.Security.Cryptography.X509Certificates.X509Extension
{
public X509KeyUsageExtension() { }
public X509KeyUsageExtension(System.Security.Cryptography.AsnEncodedData encodedKeyUsage, bool critical) { }
public X509KeyUsageExtension(System.Security.Cryptography.X509Certificates.X509KeyUsageFlags keyUsages, bool critical) { }
public System.Security.Cryptography.X509Certificates.X509KeyUsageFlags KeyUsages { get { throw null; } }
public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { }
}
[System.FlagsAttribute]
public enum X509KeyUsageFlags
{
CrlSign = 2,
DataEncipherment = 16,
DecipherOnly = 32768,
DigitalSignature = 128,
EncipherOnly = 1,
KeyAgreement = 8,
KeyCertSign = 4,
KeyEncipherment = 32,
None = 0,
NonRepudiation = 64,
}
public enum X509NameType
{
DnsFromAlternativeName = 4,
DnsName = 3,
EmailName = 1,
SimpleName = 0,
UpnName = 2,
UrlName = 5,
}
public enum X509RevocationFlag
{
EndCertificateOnly = 0,
EntireChain = 1,
ExcludeRoot = 2,
}
public enum X509RevocationMode
{
NoCheck = 0,
Offline = 2,
Online = 1,
}
public abstract partial class X509SignatureGenerator
{
protected X509SignatureGenerator() { }
public System.Security.Cryptography.X509Certificates.PublicKey PublicKey { get { throw null; } }
protected abstract System.Security.Cryptography.X509Certificates.PublicKey BuildPublicKey();
public static System.Security.Cryptography.X509Certificates.X509SignatureGenerator CreateForECDsa(System.Security.Cryptography.ECDsa key) { throw null; }
public static System.Security.Cryptography.X509Certificates.X509SignatureGenerator CreateForRSA(System.Security.Cryptography.RSA key, System.Security.Cryptography.RSASignaturePadding signaturePadding) { throw null; }
public abstract byte[] GetSignatureAlgorithmIdentifier(System.Security.Cryptography.HashAlgorithmName hashAlgorithm);
public abstract byte[] SignData(byte[] data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm);
}
public sealed partial class X509Store : System.IDisposable
{
public X509Store() { }
public X509Store(System.IntPtr storeHandle) { }
public X509Store(System.Security.Cryptography.X509Certificates.StoreLocation storeLocation) { }
public X509Store(System.Security.Cryptography.X509Certificates.StoreName storeName) { }
public X509Store(System.Security.Cryptography.X509Certificates.StoreName storeName, System.Security.Cryptography.X509Certificates.StoreLocation storeLocation) { }
public X509Store(System.Security.Cryptography.X509Certificates.StoreName storeName, System.Security.Cryptography.X509Certificates.StoreLocation storeLocation, System.Security.Cryptography.X509Certificates.OpenFlags flags) { }
public X509Store(string storeName) { }
public X509Store(string storeName, System.Security.Cryptography.X509Certificates.StoreLocation storeLocation) { }
public X509Store(string storeName, System.Security.Cryptography.X509Certificates.StoreLocation storeLocation, System.Security.Cryptography.X509Certificates.OpenFlags flags) { }
public System.Security.Cryptography.X509Certificates.X509Certificate2Collection Certificates { get { throw null; } }
public bool IsOpen { get { throw null; } }
public System.Security.Cryptography.X509Certificates.StoreLocation Location { get { throw null; } }
public string Name { get { throw null; } }
public System.IntPtr StoreHandle { get { throw null; } }
public void Add(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { }
public void AddRange(System.Security.Cryptography.X509Certificates.X509Certificate2Collection certificates) { }
public void Close() { }
public void Dispose() { }
public void Open(System.Security.Cryptography.X509Certificates.OpenFlags flags) { }
public void Remove(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { }
public void RemoveRange(System.Security.Cryptography.X509Certificates.X509Certificate2Collection certificates) { }
}
public sealed partial class X509SubjectKeyIdentifierExtension : System.Security.Cryptography.X509Certificates.X509Extension
{
public X509SubjectKeyIdentifierExtension() { }
public X509SubjectKeyIdentifierExtension(byte[] subjectKeyIdentifier, bool critical) { }
public X509SubjectKeyIdentifierExtension(System.Security.Cryptography.AsnEncodedData encodedSubjectKeyIdentifier, bool critical) { }
public X509SubjectKeyIdentifierExtension(System.Security.Cryptography.X509Certificates.PublicKey key, bool critical) { }
public X509SubjectKeyIdentifierExtension(System.Security.Cryptography.X509Certificates.PublicKey key, System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierHashAlgorithm algorithm, bool critical) { }
public X509SubjectKeyIdentifierExtension(string subjectKeyIdentifier, bool critical) { }
public string SubjectKeyIdentifier { get { throw null; } }
public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { }
}
public enum X509SubjectKeyIdentifierHashAlgorithm
{
CapiSha1 = 2,
Sha1 = 0,
ShortSha1 = 1,
}
[System.FlagsAttribute]
public enum X509VerificationFlags
{
AllFlags = 4095,
AllowUnknownCertificateAuthority = 16,
IgnoreCertificateAuthorityRevocationUnknown = 1024,
IgnoreCtlNotTimeValid = 2,
IgnoreCtlSignerRevocationUnknown = 512,
IgnoreEndRevocationUnknown = 256,
IgnoreInvalidBasicConstraints = 8,
IgnoreInvalidName = 64,
IgnoreInvalidPolicy = 128,
IgnoreNotTimeNested = 4,
IgnoreNotTimeValid = 1,
IgnoreRootRevocationUnknown = 2048,
IgnoreWrongUsage = 32,
NoFlag = 0,
}
}
| |
// Copyright (c) Microsoft Corporation. All Rights Reserved.
// Licensed under the MIT License.
using System;
using System.Linq;
using System.Windows;
using System.Collections.Generic;
using System.Windows.Data;
using System.Collections.ObjectModel;
using System.Windows.Media;
using System.Collections;
using System.Globalization;
using System.Diagnostics;
using System.ComponentModel;
namespace InteractiveDataDisplay.WPF
{
/// <summary>
/// Represents one data series (or variable).
/// </summary>
public class DataSeries : DependencyObject
{
/// <summary>
/// Occurs when a value of <see cref="Data"/> property was changed.
/// </summary>
public event EventHandler DataChanged;
private double minValue = Double.NaN;
private double maxValue = Double.NaN;
private Array cachedEnum; // Cached values from IEnumerable
/// <summary>
/// Gets or sets the unique key of data series. Data series is accessed by this key when
/// drawing markers and composing a legend.
/// </summary>
public string Key { get; set; }
/// <summary>
/// Gets or sets the readable description of this data series. It is shown in legend by default.
/// <para>Default value is null.</para>
/// </summary>
public string Description
{
get { return (string)GetValue(DescriptionProperty); }
set { SetValue(DescriptionProperty, (string)value); }
}
/// <summary>
/// Identifies the <see cref="Description"/> dependency property.
/// </summary>
public static readonly DependencyProperty DescriptionProperty =
DependencyProperty.Register("Description", typeof(string), typeof(DataSeries),
new PropertyMetadata(null, OnDescriptionPropertyChanged));
private static void OnDescriptionPropertyChanged(object sender, DependencyPropertyChangedEventArgs e)
{
var ds = sender as DataSeries;
if (ds.DataChanged != null) ds.DataChanged(ds, new EventArgs());
}
/// <summary>
/// Gets or sets the data source for data series. This can be IEnumerable or 1D array for vector data or scalar objects.
/// <para>Default value is null.</para>
/// </summary>
public object Data
{
get { return GetValue(DataProperty); }
set { SetValue(DataProperty, value); }
}
/// <summary>
/// Identifies the <see cref="Data"/> dependency property.
/// </summary>
public static readonly DependencyProperty DataProperty =
DependencyProperty.Register("Data", typeof(object), typeof(DataSeries),
new PropertyMetadata(OnDataPropertyChanged));
private static void OnDataPropertyChanged(object sender, DependencyPropertyChangedEventArgs e)
{
((DataSeries)sender).Update();
}
/// <summary>
/// A method to raise <see cref="DataChanged"/> event.
/// </summary>
protected void RaiseDataChanged()
{
if (DataChanged != null)
DataChanged(this, EventArgs.Empty);
}
/// <summary>
/// Forces this data series to be updated.
/// Is usually called if items of data array were changed, but reference to array itself remained the same.
/// </summary>
public void Update()
{
minValue = Double.NaN;
maxValue = Double.NaN;
cachedEnum = null;
First = FindFirstDataItem();
RaiseDataChanged();
}
/// <summary>
/// Gets the first value in data series.
/// <para>Returns null if <see cref="Data"/> is null.</para>
/// </summary>
public object First
{
get { return (object)GetValue(FirstProperty); }
internal set { SetValue(FirstProperty, value); }
}
/// <summary>
/// Identifies the <see cref="First"/> dependency property.
/// </summary>
public static readonly DependencyProperty FirstProperty =
DependencyProperty.Register("First", typeof(object), typeof(DataSeries), new PropertyMetadata(null));
/// <summary>
/// Gets the first value in data series and converts it if <see cref="Converter"/> is specified.
/// </summary>
/// <returns>Converted first value.</returns>
public object FindFirstDataItem()
{
object uc = GetFirstUnconvertedDataItem();
if (uc != null && Converter != null)
return Converter.Convert(uc, null, this, CultureInfo.InvariantCulture);
else
return uc;
}
/// <summary>
/// Converts the elements of an System.Collection.IEnumerable to System.Array.
/// </summary>
/// <param name="enumerable">An instance of System.Collection.IEnumerable class.</param>
/// <returns>An instance of System.Array class.</returns>
public static Array GetArrayFromEnumerable(IEnumerable enumerable)
{
return enumerable.Cast<object>().ToArray();
}
internal Array GetCachedEnumerable(IEnumerable ie)
{
if (cachedEnum == null)
cachedEnum = GetArrayFromEnumerable(ie);
return cachedEnum;
}
private object GetFirstUnconvertedDataItem()
{
Array a = Data as Array;
if (a != null)
{
if (a.Length > 0)
return a.GetValue(0);
else
return null; // Data series has zero length - no first item available
}
else
{
IEnumerable ie = Data as IEnumerable;
if (ie != null && !(Data is string))
{
IEnumerator ir = ie.GetEnumerator();
if (ir.MoveNext())
return ir.Current;
else
return null; // Data series has no elements - no first item available
}
else if (Data != null)
return Data;
else
return null; // Data series is null - no first item available
}
}
/// <summary>
/// Returns the minimum value in data series if it is numeric or Double.NaN in other cases.
/// </summary>
public double MinValue
{
get
{
if (Double.IsNaN(minValue))
{
try
{
var a = Data as Array;
if (a == null)
{
var ie = Data as IEnumerable;
if(ie != null)
a = GetArrayFromEnumerable(ie);
}
if (a != null && !(Data is string))
{
double min = a.Length > 0 ? Convert.ToDouble(a.GetValue(0), CultureInfo.InvariantCulture) : Double.NaN;
double temp = 0;
foreach (object obj in a)
{
temp = Convert.ToDouble(obj, CultureInfo.InvariantCulture);
if (temp < min)
min = temp;
}
minValue = min;
}
else
{
if (this.Data is Byte || this.Data is SByte ||
this.Data is Int16 || this.Data is Int32 || this.Data is Int64 ||
this.Data is UInt16 || this.Data is UInt32 || this.Data is UInt64 ||
this.Data is Single || this.Data is Double || this.Data is Decimal)
{
double d = Convert.ToDouble(this.Data, CultureInfo.InvariantCulture);
minValue = d;
}
}
}
catch (Exception exc)
{
Debug.WriteLine("Cannot find Min in " + this.Key + " DataSeries: " + exc.Message);
minValue = Double.NaN;
}
}
return minValue;
}
}
/// <summary>
/// Returns the maximum value in data series if it is numeric or Double.NaN in other cases.
/// </summary>
public double MaxValue
{
get
{
if (Double.IsNaN(maxValue))
try
{
Array a = Data as Array;
if (a == null)
{
var ie = Data as IEnumerable;
if(ie != null)
a = GetArrayFromEnumerable(ie);
}
if (a != null && !(Data is string))
{
double max = a.Length > 0 ? Convert.ToDouble(a.GetValue(0), CultureInfo.InvariantCulture) : Double.NaN;
double temp = 0;
foreach (object obj in a)
{
temp = Convert.ToDouble(obj, CultureInfo.InvariantCulture);
if (temp > max)
max = temp;
}
maxValue = max;
}
else
{
if (this.Data is Byte || this.Data is SByte ||
this.Data is Int16 || this.Data is Int32 || this.Data is Int64 ||
this.Data is UInt16 || this.Data is UInt32 || this.Data is UInt64 ||
this.Data is Single || this.Data is Double || this.Data is Decimal)
{
double d = Convert.ToDouble(this.Data, CultureInfo.InvariantCulture);
maxValue = d;
}
}
}
catch (Exception exc)
{
Debug.WriteLine("Cannot find Max in " + this.Key + " DataSeries: " + exc.Message);
}
return maxValue;
}
}
/// <summary>
/// Gets data series length (the length of <see cref="Data"/> if it is vector or one if it is scalar).
/// Returns 0 for series with null <see cref="Data"/> properties.
/// </summary>
public int Length
{
get
{
var arr = Data as Array;
if (arr != null)
return arr.Length;
else
{
var ie = Data as IEnumerable;
if (ie != null && !(Data is string)) // String is also IEnumerable, but we tread them as scalars
return GetCachedEnumerable(ie).Length;
else
return (Data == null) ? (0) : (1);
}
}
}
/// <summary>
/// Returns true if data series is scalar or false otherwise.
/// Returns true for series with null <see cref="Data"/> properties.
/// </summary>
public bool IsScalar
{
get
{
if (Data == null || Data is string)
return true;
else if (Data is Array || Data is IEnumerable)
return false;
else
return true;
}
}
/// <summary>
/// Gets or sets the converter which is applied to all objects in data series before binding to marker template.
/// May be null, which means identity conversion.
/// </summary>
public IValueConverter Converter { get; set; }
/// <summary>
/// Gets the marker graph than owns that series.
/// </summary>
public MarkerGraph Owner { get; internal set; }
}
/// <summary>
/// Represents a collection of data series.
/// </summary>
public class DataCollection : ObservableCollection<DataSeries>
{
private Dictionary<string, DataSeries> lookup;
DynamicDataCollection dynamicCollection;
bool isValid;
int markerCount;
/// <summary>
/// Occurs when an item in the collection or entire collection changes.
/// </summary>
public event EventHandler<DataSeriesUpdatedEventArgs> DataSeriesUpdated;
/// <summary>
/// Initializes a new empty instance of <see cref="DataCollection"/> class.
/// </summary>
public DataCollection()
{ }
/// <summary>
/// Looks up for <see cref="DataSeries"/> with specified <see cref="Key"/>. If found assigns it to the
/// output parameter and returns true. Returns false if no series with specified name was found.
/// </summary>
/// <param name="name">The key of data series to search for.</param>
/// <param name="result">Output parameter for found series.</param>
/// <returns>True if data series was found or false otherwise.</returns>
public bool TryGetValue(string name, out DataSeries result)
{
if (lookup == null)
{
lookup = new Dictionary<string,DataSeries>();
foreach (var ds in this)
lookup.Add(ds.Key, ds);
}
return lookup.TryGetValue(name, out result);
}
/// <summary>
/// Checks whether a collection contains <see cref="DataSeries"/> with specified <see cref="Key"/>.
/// </summary>
/// <param name="name">The key of data series.</param>
/// <returns>True is data series is in collection or false otherwise.</returns>
public bool ContainsSeries(string name)
{
DataSeries dummy;
return TryGetValue(name, out dummy);
}
/// <summary>
/// Gets the index of <see cref="DataSeries"/> with <see cref="Key"/> "X". If there is no one returns -1.
/// </summary>
/// <returns>Index of X <see cref="DataSeries"/> in current collection.</returns>
public int XSeriesNumber
{
get
{
DataSeries dummy;
TryGetValue("X", out dummy);
if (dummy == null)
return -1;
else
return this.IndexOf(dummy);
}
}
/// <summary>
/// Gets the first <see cref="DataSeries"/> in collection with specified <see cref="Key"/>.
/// </summary>
/// <param name="name">The key of data series.</param>
/// <returns>The first data series in collection with specified key.</returns>
public DataSeries this[string name]
{
get
{
DataSeries result;
if (TryGetValue(name, out result))
return result;
else
return null;
}
}
/// <summary>
/// Gets <see cref="DynamicDataCollection"/> with generated properties to get data series by key.
/// Used in bindings in legend templates.
/// </summary>
public DynamicDataCollection Emitted
{
get { return dynamicCollection; }
}
/// <summary>
/// Return true if collection is valid and can be drawn, false otherwise.
/// <remarks>
/// Collection is valid if all the vector data of data series are of equal length and
/// all data series have a defined unique key.
/// </remarks>
/// </summary>
public bool IsValid
{
get { return isValid; }
}
/// <summary>
/// Gets the count of markers to draw.
/// <remarks>
/// If any data of data series in collection is a vector then the count of markers is vector's length.
/// Otherwise only one marker will be drawn.
/// If any data series (except for data series with key "X") has null data then no markers will be drawn.
/// </remarks>
/// </summary>
public int MarkerCount
{
get { return markerCount; }
}
/// <summary>
/// Raises the <see cref="DataCollection.DataSeriesUpdated"/> event with the provided event data.
/// </summary>
/// <param name="e">Provided data for collection changing event.</param>
protected override void OnCollectionChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
Type dynamic = DynamicTypeGenerator.GenerateDataCollectionType(this);
dynamicCollection = Activator.CreateInstance(dynamic, this) as DynamicDataCollection;
CheckDataCollection();
base.OnCollectionChanged(e);
if (e == null)
{
throw new ArgumentNullException("e");
}
if (e.OldItems != null)
foreach (DataSeries item in e.OldItems)
item.DataChanged -= OnSeriesDataChanged;
if (e.NewItems != null)
foreach (DataSeries item in e.NewItems)
item.DataChanged += OnSeriesDataChanged;
lookup = null;
OnPropertyChanged(new PropertyChangedEventArgs("Emitted"));
}
private void OnSeriesDataChanged(object sender, EventArgs e)
{
CheckDataCollection();
if (DataSeriesUpdated != null)
{
var ds = sender as DataSeries;
if (ds != null)
DataSeriesUpdated(this, new DataSeriesUpdatedEventArgs(ds.Key));
}
lookup = null;
}
private void CheckDataCollection()
{
int n = 0;
isValid = true;
var vs = this.Where(s => !s.IsScalar).FirstOrDefault();
if (vs != null)
n = vs.Length; // Take length of first vector series
else
{
var ns = this.Where(s => s.Data != null).FirstOrDefault(); // Find any scalar series with non-null data
if (ns != null)
n = 1;
}
var ser = this.Where(s => (s.Data == null && s.Key != "X")).FirstOrDefault();
if (ser == null)
markerCount = n;
else
markerCount = 0;
foreach (DataSeries ds in this)
{
if (!ds.IsScalar && n != ds.Length)
isValid = false;
if (String.IsNullOrEmpty(ds.Key))
isValid = false;
for (int i = 0; i < this.Count; i++)
if (this[i] != ds && this[i].Key == ds.Key)
{
this.Remove(ds);
isValid = false;
}
}
}
}
/// <summary>
/// Provides event data for the <see cref="DataCollection.DataSeriesUpdated"/> event.
/// </summary>
public class DataSeriesUpdatedEventArgs : EventArgs
{
private string key;
/// <summary>
/// Initializes a new instance of the <see cref="DataSeriesUpdatedEventArgs"/> class.
/// </summary>
/// <param name="key">The <see cref="DataSeries.Key"/> of the updated <see cref="DataSeries"/>.</param>
public DataSeriesUpdatedEventArgs(string key)
{
this.key = key;
}
/// <summary>
/// Gets the <see cref="DataSeries.Key"/> of the updated <see cref="DataSeries"/>.
/// </summary>
public string Key { get { return key; } }
}
/// <summary>
/// Provides an access to all the information about one specific marker.
/// </summary>
public class MarkerViewModel : INotifyPropertyChanged
{
int row;
bool useConverters = true;
DataCollection dataCollection;
MarkerViewModel sourceModel;
/// <summary>
/// Initializes a new instance of <see cref="MarkerViewModel"/> class that uses converters.
/// </summary>
/// <param name="row">The number of marker.</param>
/// <param name="collection">A collection of data series.</param>
public MarkerViewModel(int row, DataCollection collection) :
this(row, collection, true)
{ /* Nothing to do here */ }
/// <summary>
/// Initializes a new instance of <see cref="MarkerViewModel"/> class.
/// </summary>
/// <param name="row">The number of marker.</param>
/// <param name="collection">A collection of data series.</param>
/// <param name="converters">A value indicating should converters be used or not.</param>
protected MarkerViewModel(int row, DataCollection collection, bool converters)
{
this.row = row;
this.dataCollection = collection;
this.useConverters = converters;
}
/// <summary>
/// Gets the <see cref="DynamicDataCollection"/> (a specially created wrapper for <see cref="DataCollection"/>)
/// this instance of <see cref="MarkerViewModel"/> class is associated with.
/// </summary>
public DynamicDataCollection Series
{
get { return dataCollection.Emitted; }
}
/// <summary>
/// Gets a new instance of <see cref="MarkerViewModel"/> class with the same fields but which doesn't use converters.
/// </summary>
public MarkerViewModel Sources
{
get
{
if (sourceModel == null)
sourceModel = new MarkerViewModel(row, dataCollection, false);
return sourceModel;
}
}
internal int Row
{
get { return row; }
set
{
row = value;
if (sourceModel != null)
sourceModel.Row = value;
}
}
/// <summary>
/// Returns the value of a specific property.
/// </summary>
/// <param name="name">The <see cref="DataSeries.Key"/> of data series associated with the property.</param>
/// <returns></returns>
public object this[string name]
{
get
{
// Find data series by name
var dataSeries = dataCollection[name];
if (dataSeries == null || dataSeries.Data == null)
if(name == "X")
return row;
else
return null;
// Get value
object value = null;
var arr = dataSeries.Data as Array;
if (arr != null)
{
if(row < arr.Length)
value = arr.GetValue(row);
}
else
{
var ie = dataSeries.Data as IEnumerable;
if (ie != null && !(dataSeries.Data is string)) // String is also IEnumerable
{
var ce = dataSeries.GetCachedEnumerable(ie);
if (row < ce.Length)
value = ce.GetValue(row);
}
else
value = dataSeries.Data;
}
// Apply converter if needed
if (useConverters && value != null && dataSeries.Converter != null)
return dataSeries.Converter.Convert(value, typeof(object), dataSeries, null);
else
return value;
}
}
/// <summary>
/// Returns the value of a specific property.
/// </summary>
/// <param name="i">The index of <see cref="DataSeries"/> associated with the property.</param>
/// <returns>Value of a property with index <paramref name="i"/>.</returns>
public object GetValue(int i)
{
// Get data series by inex
var dataSeries = dataCollection[i];
if (dataSeries.Data == null)
if (dataSeries.Key == "X")
return row;
else
return null;
// Get value
object value = null;
var arr = dataSeries.Data as Array;
if (arr != null)
{
if(row < arr.Length)
value = arr.GetValue(row);
}
else
{
var ie = dataSeries.Data as IEnumerable;
if (ie != null && !(dataSeries.Data is string)) // String is also IEnumerable
{
var ce = dataSeries.GetCachedEnumerable(ie);
if(row < ce.Length)
value = ce.GetValue(row);
}
else
value = dataSeries.Data;
}
// Apply converter if needed
if (useConverters && value != null && dataSeries.Converter != null)
return dataSeries.Converter.Convert(value, typeof(object), dataSeries, null);
else
return value;
}
/// <summary>
/// Returns the value of a specific property without convertion.
/// </summary>
/// <param name="i">The index of data series associated with the property.</param>
/// <returns>Value of a property with index <paramref name="i"/> without convertion.</returns>
public object GetOriginalValue(int i)
{
return Sources.GetValue(i);
}
/// <summary>
/// Gets the value of <see cref="DataSeries"/> with key "X".
/// </summary>
public object X
{
get
{
int i = dataCollection.XSeriesNumber;
if (i == -1)
return row;
else
return GetValue(i);
}
}
/// <summary>
/// Gets the value of <see cref="DataSeries"/> with key "X" without convertion.
/// </summary>
public object OriginalX
{
get
{
int i = dataCollection.XSeriesNumber;
if (i == -1)
return row;
else
return GetOriginalValue(i);
}
}
/// <summary>
/// Gets the stroke of a parent <see cref="MarkerGraph"/> of <see cref="DataCollection"/>.
/// </summary>
public SolidColorBrush Stroke
{
get
{
if (dataCollection.Count > 0)
if (dataCollection[0].Owner != null)
return dataCollection[0].Owner.Stroke;
return null;
}
}
/// <summary>
/// Gets the stroke thickness of a parent <see cref="MarkerGraph"/> of <see cref="DataCollection"/>.
/// </summary>
public double StrokeThickness
{
get
{
if (dataCollection.Count > 0)
if (dataCollection[0].Owner != null)
return dataCollection[0].Owner.StrokeThickness;
return 0;
}
}
/// <summary>
/// Gets current instance of <see cref="MarkerViewModel"/>.
/// </summary>
public MarkerViewModel This
{
get { return this; }
}
/// <summary>
/// Event that occurs when a property value changes.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
/// <summary>
/// Notifies all bindings that all properies of <see cref="MarkerViewModel"/> have changed.
/// </summary>
public void Notify(string[] props)
{
if (props == null)
NotifyPropertyChanged(null);
else
{
foreach (var p in props)
NotifyPropertyChanged(p);
if(props.Length > 0)
NotifyPropertyChanged("This");
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using bv.common.Configuration;
using bv.common.Core;
using DevExpress.XtraPivotGrid;
using DevExpress.XtraPivotGrid.Data;
using eidss.avr.BaseComponents;
using eidss.avr.db.AvrEventArgs.DevExpressEventArgsWrappers;
using eidss.avr.db.Common;
using eidss.avr.db.Interfaces;
using eidss.model.Avr.Commands;
using eidss.model.Avr.Commands.Layout;
using eidss.model.Avr.Pivot;
using eidss.model.Avr.View;
using eidss.model.AVR.SourceData;
namespace eidss.avr.PivotComponents
{
public class AvrPivotGridPresenter : BaseAvrPresenter
{
private IAvrPivotGridView m_PivotGridView;
private Dictionary<string, string> m_CaptionDictionary;
public AvrPivotGridPresenter(SharedPresenter sharedPresenter, IAvrPivotGridView view)
: base(sharedPresenter)
{
m_PivotGridView = view;
}
public override void Process(Command cmd)
{
}
public override void Dispose()
{
try
{
m_PivotGridView = null;
}
finally
{
base.Dispose();
}
}
#region Prepare Avr View Data
public PivotGridDataLoadedCommand CreatePivotDataLoadedCommand(string layoutName, bool skipData = false)
{
var view = new AvrView(m_SharedPresenter.SharedModel.SelectedLayoutId, layoutName, m_SharedPresenter.SharedModel.SelectedQueryId);
CreateTotalSuffixForView(view);
bool isFlat = m_PivotGridView.PivotData.VisualItems.GetLevelCount(true) == 1;
CreateViewHeaderFromRowArea(view, isFlat);
CreateViewHeaderFromColumnArea(view, isFlat);
AddColumnsToEmptyBands(view.Bands);
view.RemoveHascFromDisplayText();
view.AssignOwnerAndUniquePath();
AssignCustomSummaryTypes(view);
DataTable dataSource = CreateViewDataSourceStructure(view);
CheckViewHeaderColumnCount(view);
if (!skipData)
{
FillViewDataSource(view, dataSource);
}
var model = new AvrPivotViewModel(view, dataSource);
// string viewXmlNew = AvrViewSerializer.Serialize(view);
// string data = DataTableSerializer.Serialize(dataSource);
return new PivotGridDataLoadedCommand(this, model);
}
private void CreateTotalSuffixForView(AvrView view)
{
List<CustomSummaryType> types = m_PivotGridView.DataAreaFields.Select(field => field.CustomSummaryType).ToList();
view.TotalSuffix = " " + m_PivotGridView.DisplayTextHandler.GetGrandTotalDisplayText(types, false);
view.GrandTotalSuffix = m_PivotGridView.DisplayTextHandler.GetGrandTotalDisplayText(types, true);
}
private void CreateViewHeaderFromRowArea(AvrView view, bool isFlat)
{
DataView dvMapFieldList = AvrPivotGridHelper.GetMapFiledView(SharedPresenter.SharedModel.SelectedQueryId, true);
AvrViewBand rowAreaRootBand = null;
if (!isFlat && m_PivotGridView.RowAreaFields.Count > 0)
{
var firstField = (PivotGridFieldBase) m_PivotGridView.RowAreaFields[0];
long fieldId = AvrPivotGridFieldHelper.GetIdFromFieldName(firstField.FieldName);
string fieldAlias = AvrPivotGridFieldHelper.GetOriginalNameFromFieldName(firstField.FieldName);
rowAreaRootBand = new AvrViewBand(fieldId, fieldAlias, string.Empty, 100);
view.Bands.Add(rowAreaRootBand);
}
foreach (IAvrPivotGridField field in m_PivotGridView.RowAreaFields)
{
AvrViewColumn column = CreateViewColumnInternal(field.FieldName, field.Caption, field.Width);
column.IsRowArea = true;
foreach (DataRowView rowView in dvMapFieldList)
{
string value = Utils.Str(rowView["FieldAlias"]);
if (field.FieldName.Contains(value))
{
column.GisReferenceTypeId = field.GisReferenceTypeId;
column.IsAdministrativeUnit = true;
column.MapDisplayOrder = rowView["intMapDisplayOrder"] is int
? (int) rowView["intMapDisplayOrder"]
: int.MaxValue;
}
}
if (rowAreaRootBand == null)
{
view.Columns.Add(column);
}
else
{
rowAreaRootBand.AddColumn(column);
}
}
}
private void CreateViewHeaderFromColumnArea(AvrView view, bool isFlat)
{
int columnItemCount = m_PivotGridView.PivotData.VisualItems.GetItemCount(true);
for (int i = 0; i < columnItemCount; i++)
{
PivotFieldValueItem item = m_PivotGridView.PivotData.VisualItems.GetItem(true, i);
long? gisReferenceTypeId = GetGisReferenceTypeId(item.ColumnField);
if (item.Level == 0)
{
if (isFlat)
{
string fieldName = GetFieldName(item);
int width = (m_PivotGridView.ColumnAreaFields.Count == 0)
? GetFieldWidth(item)
: GetBandWidth(item);
AvrViewColumn column = CreateViewColumnInternal(fieldName, item.DisplayText, width);
column.IsAdministrativeUnit = gisReferenceTypeId.HasValue;
view.Columns.Add(column);
}
else
{
string bandName = GetBandName(item);
string fieldName = GetFieldName(item);
int width = GetFieldWidth(item);
AvrViewBand band = CreateViewBandInternal(bandName, fieldName, item.DisplayText, width);
band.IsAdministrativeUnit = gisReferenceTypeId.HasValue;
view.Bands.Add(band);
CreateViewBandsAndColumns(band, item);
}
}
}
}
internal void CreateViewBandsAndColumns(AvrViewBand band, PivotFieldValueItem item)
{
Utils.CheckNotNull(band, "band");
Utils.CheckNotNull(item, "item");
var children = new List<PivotFieldValueItem>();
for (int i = 0; i < item.CellCount; i++)
{
children.Add(item.GetCell(i));
}
bool isChildrenHasChildren = children.Any(child => child.CellCount != 0);
foreach (PivotFieldValueItem child in children)
{
if (isChildrenHasChildren)
{
AvrViewBand childBand = CreateViewBand(band, child);
band.Bands.Add(childBand);
CreateViewBandsAndColumns(childBand, child);
}
else
{
AvrViewColumn childColumn = CreateViewColumn(band, child);
childColumn.GisReferenceTypeId = GetGisReferenceTypeId(child.ColumnField);
childColumn.IsAdministrativeUnit = childColumn.GisReferenceTypeId.HasValue;
band.Columns.Add(childColumn);
}
}
}
private void AssignCustomSummaryTypes(AvrView view)
{
List<AvrViewColumn> viewColumns = view.GetAllViewColumns();
foreach (AvrViewColumn column in viewColumns)
{
string fieldName = AvrPivotGridFieldHelper.CreateFieldName(column.LayoutSearchFieldName, column.LayoutSearchFieldId);
IAvrPivotGridField field = m_PivotGridView.DataAreaFields.FirstOrDefault(f => f.FieldName == fieldName);
column.CustomSummaryType = field != null
? field.CustomSummaryType
: CustomSummaryType.Undefined;
}
}
private DataTable CreateViewDataSourceStructure(AvrView view)
{
var dataSource = new DataTable("ViewData");
dataSource.BeginInit();
var fields = new List<IAvrPivotGridField>();
fields.AddRange(m_PivotGridView.RowAreaFields);
fields.AddRange(m_PivotGridView.DataAreaFields);
List<AvrViewColumn> viewColumns = view.GetAllViewColumns();
foreach (AvrViewColumn viewColumn in viewColumns)
{
viewColumn.FieldType = GetViewColumnType(viewColumn, fields);
DataColumn dataColumn = dataSource.Columns.Add(viewColumn.UniquePath, viewColumn.FieldType);
dataColumn.Caption = viewColumn.DisplayText;
}
dataSource.EndInit();
return dataSource;
}
private Type GetViewColumnType(AvrViewColumn column, IEnumerable<IAvrPivotGridField> fields)
{
Type type = typeof (string);
string fieldName = AvrPivotGridFieldHelper.CreateFieldName(column.LayoutSearchFieldName, column.LayoutSearchFieldId);
IAvrPivotGridField field = fields.FirstOrDefault(f => f.FieldName == fieldName);
if (field != null && field.Area == PivotArea.DataArea)
{
switch (field.CustomSummaryType)
{
case CustomSummaryType.Average:
case CustomSummaryType.Pop10000:
case CustomSummaryType.Pop100000:
case CustomSummaryType.PopGender100000:
case CustomSummaryType.PopAgeGroupGender100000:
case CustomSummaryType.PopAgeGroupGender10000:
case CustomSummaryType.StdDev:
case CustomSummaryType.Variance:
type = typeof (double);
break;
case CustomSummaryType.Count:
case CustomSummaryType.DistinctCount:
type = typeof (long);
break;
case CustomSummaryType.Sum:
type = field.DataType == typeof (double) ||
field.DataType == typeof (float) ||
field.DataType == typeof (decimal)
? field.DataType
: typeof (long);
break;
case CustomSummaryType.Max:
case CustomSummaryType.Min:
type = GetRealFieldType(field);
break;
}
}
return type;
}
private Type GetRealFieldType(IAvrPivotGridField field)
{
Utils.CheckNotNull(field, "field");
Type type;
if (field.GroupInterval.IsDate())
{
switch (field.GroupInterval)
{
case PivotGroupInterval.DateDayOfYear:
case PivotGroupInterval.DateQuarter:
case PivotGroupInterval.DateWeekOfYear:
case PivotGroupInterval.DateWeekOfMonth:
case PivotGroupInterval.DateYear:
case PivotGroupInterval.DateDay:
type = typeof (int);
break;
case PivotGroupInterval.Date:
type = typeof (DateTime);
break;
case PivotGroupInterval.DateDayOfWeek:
type = typeof (DayOfWeek);
break;
case PivotGroupInterval.DateMonth:
type = typeof (AvrMonth);
break;
default:
type = typeof (DateTime);
break;
}
}
else
{
type = field.DataType;
}
return type;
}
private void CheckViewHeaderColumnCount(AvrView view)
{
List<AvrViewColumn> viewColumns = view.GetAllViewColumns();
if (viewColumns.Count - m_PivotGridView.RowAreaFields.Count != m_PivotGridView.Cells.ColumnCount)
{
throw new AvrException("Internal Error. DataArea column count isn't equal to RowArea column count.");
}
}
// private void FillViewDataSource(AvrView view, DataTable dataSource)
// {
// var rowCount = m_PivotGridView.Cells.RowCount;
// if (rowCount > 0)
// {
// AvrCellInfo[,] infoDictionary = new AvrCellInfo[rowCount, m_PivotGridView.Cells.ColumnCount];
//
// Action<int, int> cellInfoCalculator = (min, max) =>
// {
// for (var rowIndex = min; rowIndex < max; rowIndex++)
// {
// for (var columnIndex = 0; columnIndex < m_PivotGridView.Cells.ColumnCount; columnIndex++)
// {
// var cellInfo = m_PivotGridView.Cells.GetCellInfo(columnIndex, rowIndex);
// infoDictionary[rowIndex, columnIndex] = new AvrCellInfo(cellInfo);
// }
// }
// };
//
// if (rowCount > 16)
// {
// var tasks = new[]
// {
// Task.Factory.StartNew(() => cellInfoCalculator(0, rowCount / 4)),
// Task.Factory.StartNew(() => cellInfoCalculator(rowCount / 4, rowCount / 2)),
// Task.Factory.StartNew(() => cellInfoCalculator(rowCount / 2, 3 * rowCount / 4)),
// Task.Factory.StartNew(() => cellInfoCalculator(3 * rowCount / 4, rowCount)),
// };
// Task.WaitAll(tasks);
// }
// else
// {
// cellInfoCalculator(0, rowCount);
// }
// Dictionary<string, CustomSummaryType> summaryTypes =
// m_PivotGridView.DataAreaFields.ToDictionary(field => field.FieldName, field => field.CustomSummaryType);
//
// dataSource.BeginLoadData();
// for (int rowIndex = 0; rowIndex < rowCount; rowIndex++)
// {
// DataRow dataRow = dataSource.NewRow();
// bool isRowAreaCreated = false;
// for (int columnIndex = 0; columnIndex < m_PivotGridView.Cells.ColumnCount; columnIndex++)
// {
// var avrCellInfo = infoDictionary[rowIndex, columnIndex];
// if (avrCellInfo != null && avrCellInfo.Info != null)
// {
// if (!isRowAreaCreated && m_PivotGridView.RowAreaFields.Count > 0)
// {
// isRowAreaCreated = CreateRowAreaCells(view, avrCellInfo.Info, m_PivotGridView.RowAreaFields, dataRow);
// }
//
// int currentRowIndex = m_PivotGridView.RowAreaFields.Count + columnIndex;
//
// CreateDataAreaCell(dataRow, currentRowIndex, avrCellInfo, summaryTypes);
// }
// }
// dataSource.Rows.Add(dataRow);
// }
// dataSource.EndLoadData();
// dataSource.AcceptChanges();
// }
// }
private void FillViewDataSource(AvrView view, DataTable dataSource)
{
if (m_PivotGridView.Cells.RowCount > 0)
{
Dictionary<string, CustomSummaryType> summaryTypes =
m_PivotGridView.DataAreaFields.ToDictionary(field => field.FieldName, field => field.CustomSummaryType);
dataSource.BeginLoadData();
for (int rowIndex = 0; rowIndex < m_PivotGridView.Cells.RowCount; rowIndex++)
{
DataRow dataRow = dataSource.NewRow();
bool isRowAreaCreated = false;
for (int columnIndex = 0; columnIndex < m_PivotGridView.Cells.ColumnCount; columnIndex++)
{
PivotCellEventArgs cellInfo = m_PivotGridView.Cells.GetCellInfo(columnIndex, rowIndex);
if (cellInfo != null)
{
if (!isRowAreaCreated && m_PivotGridView.RowAreaFields.Count > 0)
{
isRowAreaCreated = CreateRowAreaCells(view, cellInfo, m_PivotGridView.RowAreaFields, dataRow);
}
int currentRowIndex = m_PivotGridView.RowAreaFields.Count + columnIndex;
CreateDataAreaCell(dataRow, currentRowIndex, cellInfo, summaryTypes);
}
}
dataSource.Rows.Add(dataRow);
}
dataSource.EndLoadData();
dataSource.AcceptChanges();
}
}
private bool CreateRowAreaCells
(AvrView view, PivotCellEventArgs cellInfo, List<IAvrPivotGridField> avrRowFields, DataRow dataRow)
{
var infoRowFields = cellInfo.GetRowFields();
bool result = infoRowFields.Length > 0;
if (result)
{
int totalIndex = 0;
if (cellInfo.RowValueType == PivotGridValueType.Value)
{
totalIndex = infoRowFields.Length;
}
else if (cellInfo.RowField != null)
{
totalIndex = cellInfo.RowField.AreaIndex;
}
for (int i = 0; i < infoRowFields.Length; i++)
{
var rowField = infoRowFields[i];
object rowAreaValue = (i < totalIndex + 1)
? cellInfo.GetFieldValue(rowField)
: string.Empty;
var avrField = avrRowFields.Find(f => f.Name == rowField.Name);
if (avrField != null)
{
if (rowAreaValue == null
&& BaseSettings.ShowAvrAsterisk
&& cellInfo.RowValueType == PivotGridValueType.Value)
{
rowAreaValue = BaseSettings.Asterisk;
}
var displayTextArgs = new InternalPivotCellDisplayTextEventArgs(rowAreaValue, avrField, false);
m_PivotGridView.DisplayTextHandler.DisplayCellText(displayTextArgs, CustomSummaryType.Max, -1);
dataRow[i] = displayTextArgs.DisplayText;
}
}
if (cellInfo.RowValueType != PivotGridValueType.Value)
{
dataRow[totalIndex] += view.TotalSuffix;
}
}
else if (cellInfo.RowValueType == PivotGridValueType.GrandTotal)
{
dataRow[0] = view.GrandTotalSuffix;
}
return result;
}
private static void CreateDataAreaCell
(DataRow dataRow, int currentRowIndex, PivotCellEventArgs cellInfo, Dictionary<string, CustomSummaryType> summaryTypes)
{
object resultVal;
PivotGridField field = cellInfo.DataField;
var cellVal = cellInfo.Value;
if (cellVal != null)
{
resultVal = cellVal;
var avrField = field as IAvrPivotGridField;
if (avrField != null && avrField.GisReferenceTypeId != null && summaryTypes.ContainsKey(avrField.FieldName))
{
CustomSummaryType summaryType = summaryTypes[avrField.FieldName];
if (summaryType.IsMinMax())
{
resultVal = AvrViewHelper.RemoveHasc(resultVal);
}
}
}
else
{
resultVal = DBNull.Value;
CustomSummaryType summaryType;
if (field != null && summaryTypes.TryGetValue(field.FieldName, out summaryType))
{
if (!summaryType.IsMinMax() && !summaryType.IsAdmUnitOrGender())
{
resultVal = 0;
}
}
}
dataRow[currentRowIndex] = resultVal;
}
internal AvrViewBand CreateViewBand(AvrViewBand parentBand, PivotFieldValueItem item)
{
Utils.CheckNotNull(item, "item");
string bandName = GetBandName(item);
string fieldName = GetFieldName(item);
int width = GetBandWidth(item);
AvrViewBand band = CreateViewBandInternal(bandName, fieldName, item.DisplayText, width);
if (parentBand != null)
{
band.IsAdministrativeUnit = parentBand.IsAdministrativeUnit;
band.MapDisplayOrder = parentBand.MapDisplayOrder;
band.IsRowArea = parentBand.IsRowArea;
}
return band;
}
private AvrViewBand CreateViewBandInternal(string bandName, string fieldName, string caption, int width)
{
long bandId = AvrPivotGridFieldHelper.GetIdFromFieldName(bandName);
string bandAlias = AvrPivotGridFieldHelper.GetOriginalNameFromFieldName(bandName);
long fieldId = AvrPivotGridFieldHelper.GetIdFromFieldName(fieldName);
string fieldAlias = AvrPivotGridFieldHelper.GetOriginalNameFromFieldName(fieldName);
int? presicion = GetPrecisionByName(fieldName);
var band = new AvrViewBand(bandId, bandAlias, caption, width, presicion)
{
LayoutChildSearchFieldId = fieldId,
LayoutChildSearchFieldName = fieldAlias,
};
return band;
}
internal AvrViewColumn CreateViewColumn(AvrViewBand parentBand, PivotFieldValueItem item)
{
Utils.CheckNotNull(item, "item");
string fieldName = GetFieldName(item);
int width = GetFieldWidth(item);
AvrViewColumn column = CreateViewColumnInternal(fieldName, item.DisplayText, width);
if (parentBand != null)
{
column.IsAdministrativeUnit = parentBand.IsAdministrativeUnit;
column.MapDisplayOrder = parentBand.MapDisplayOrder;
column.IsRowArea = parentBand.IsRowArea;
}
return column;
}
private AvrViewColumn CreateViewColumnInternal(string fieldName, string caption, int width)
{
long fieldId = AvrPivotGridFieldHelper.GetIdFromFieldName(fieldName);
string fieldAlias = AvrPivotGridFieldHelper.GetOriginalNameFromFieldName(fieldName);
int? presicion = GetPrecisionByName(fieldName);
var column = new AvrViewColumn(fieldId, fieldAlias, caption, width, presicion);
return column;
}
private int? GetPrecisionByName(string fieldName)
{
var field = m_PivotGridView.BaseFields.GetFieldByName("field" + fieldName) as IAvrPivotGridField;
int? presicion = (field == null || field.IsDateTimeField)
? null
: field.Precision;
return presicion;
}
private long? GetGisReferenceTypeId(PivotFieldItemBase field)
{
if (field != null)
{
var avrField = m_PivotGridView.BaseFields.GetFieldByName("field" + field.FieldName) as IAvrPivotGridField;
if (avrField != null)
{
return avrField.GisReferenceTypeId;
}
}
return null;
}
internal static int GetFieldWidth(PivotFieldValueItem item)
{
PivotFieldItemBase field = GetCorrespondingField(item, true);
return field == null
? AvrView.DefaultFieldWidth
: field.Width;
}
internal static int GetBandWidth(PivotFieldValueItem item)
{
PivotFieldItemBase field = GetCorrespondingField(item, false);
return field == null
? AvrView.DefaultFieldWidth
: field.Width;
}
internal static string GetFieldName(PivotFieldValueItem item)
{
return GetName(item, true);
}
internal static string GetBandName(PivotFieldValueItem item)
{
return GetName(item, false);
}
private static string GetName(PivotFieldValueItem item, bool isColumn)
{
PivotFieldItemBase field = GetCorrespondingField(item, isColumn);
return field == null
? string.Empty
: field.FieldName;
}
private static PivotFieldItemBase GetCorrespondingField(PivotFieldValueItem item, bool isColumn)
{
Utils.CheckNotNull(item, "item");
PivotFieldItemBase primaryField = isColumn ? item.DataField : item.ColumnField;
PivotFieldItemBase secondaryField = isColumn ? item.ColumnField : item.DataField;
PivotFieldItemBase field = null;
if (primaryField != null)
{
field = primaryField;
}
else if (secondaryField != null)
{
field = secondaryField;
}
return field;
}
internal static void AddColumnsToEmptyBands(IEnumerable<AvrViewBand> avrViewBands)
{
foreach (AvrViewBand band in avrViewBands)
{
if (band.Bands.Count == 0 && band.Columns.Count == 0)
{
var column = new AvrViewColumn(band.LayoutChildSearchFieldId, band.LayoutChildSearchFieldName,
String.Empty, band.ColumnWidth, band.Precision)
{
IsAdministrativeUnit = band.IsAdministrativeUnit,
MapDisplayOrder = band.MapDisplayOrder,
IsRowArea = band.IsRowArea,
};
band.Columns.Add(column);
}
else
{
AddColumnsToEmptyBands(band.Bands);
}
}
}
#endregion
#region Pivot Captions
/// <summary>
/// Init captions given from data columns of data table
/// </summary>
public void InitPivotCaptions(AvrDataTable data)
{
m_CaptionDictionary = new Dictionary<string, string>();
foreach (AvrDataColumn column in data.Columns)
{
m_CaptionDictionary.Add(column.ColumnName, column.Caption);
}
}
/// <summary>
/// Update captions given from internal dictionary of fields of pivot grid
/// </summary>
public void UpdatePivotCaptions()
{
if (m_CaptionDictionary == null)
{
return;
}
using (m_PivotGridView.BeginTransaction())
{
foreach (PivotGridField field in m_PivotGridView.BaseFields)
{
if (!m_CaptionDictionary.ContainsKey(field.FieldName))
{
throw new AvrException("Pivot caption dictionary doesn't contains field " + field.FieldName);
}
field.Caption = m_CaptionDictionary[field.FieldName];
}
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Globalization;
using System.Collections.Generic;
using System.Reflection.Runtime.BindingFlagSupport;
namespace System.Reflection.Runtime.TypeInfos
{
internal abstract partial class RuntimeTypeInfo
{
public sealed override Object InvokeMember(
String name, BindingFlags bindingFlags, Binder binder, Object target,
Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
{
const BindingFlags MemberBindingMask = (BindingFlags)0x000000FF;
const BindingFlags InvocationMask = (BindingFlags)0x0000FF00;
const BindingFlags BinderGetSetProperty = BindingFlags.GetProperty | BindingFlags.SetProperty;
const BindingFlags BinderGetSetField = BindingFlags.GetField | BindingFlags.SetField;
const BindingFlags BinderNonFieldGetSet = (BindingFlags)0x00FFF300;
const BindingFlags BinderNonCreateInstance = BindingFlags.InvokeMethod | BinderGetSetField | BinderGetSetProperty;
if (IsGenericParameter)
throw new InvalidOperationException(SR.Arg_GenericParameter);
#region Preconditions
if ((bindingFlags & InvocationMask) == 0)
// "Must specify binding flags describing the invoke operation required."
throw new ArgumentException(SR.Arg_NoAccessSpec, nameof(bindingFlags));
// Provide a default binding mask if none is provided
if ((bindingFlags & MemberBindingMask) == 0)
{
bindingFlags |= BindingFlags.Instance | BindingFlags.Public;
if ((bindingFlags & BindingFlags.CreateInstance) == 0)
bindingFlags |= BindingFlags.Static;
}
// There must not be more named parameters than provided arguments
if (namedParams != null)
{
if (providedArgs != null)
{
if (namedParams.Length > providedArgs.Length)
// "Named parameter array can not be bigger than argument array."
throw new ArgumentException(SR.Arg_NamedParamTooBig, nameof(namedParams));
}
else
{
if (namedParams.Length != 0)
// "Named parameter array can not be bigger than argument array."
throw new ArgumentException(SR.Arg_NamedParamTooBig, nameof(namedParams));
}
}
#endregion
#region COM Interop
if (target != null && target.GetType().IsCOMObject)
throw new PlatformNotSupportedException(SR.Arg_PlatformNotSupportedInvokeMemberCom);
#endregion
#region Check that any named paramters are not null
if (namedParams != null && Array.IndexOf(namedParams, null) != -1)
// "Named parameter value must not be null."
throw new ArgumentException(SR.Arg_NamedParamNull, nameof(namedParams));
#endregion
int argCnt = (providedArgs != null) ? providedArgs.Length : 0;
#region Get a Binder
if (binder == null)
binder = DefaultBinder;
bool bDefaultBinder = (binder == DefaultBinder);
#endregion
#region Delegate to Activator.CreateInstance
if ((bindingFlags & BindingFlags.CreateInstance) != 0)
{
if ((bindingFlags & BindingFlags.CreateInstance) != 0 && (bindingFlags & BinderNonCreateInstance) != 0)
// "Can not specify both CreateInstance and another access type."
throw new ArgumentException(SR.Arg_CreatInstAccess, nameof(bindingFlags));
return Activator.CreateInstance(this, bindingFlags, binder, providedArgs, culture);
}
#endregion
// PutDispProperty and\or PutRefDispProperty ==> SetProperty.
if ((bindingFlags & (BindingFlags.PutDispProperty | BindingFlags.PutRefDispProperty)) != 0)
bindingFlags |= BindingFlags.SetProperty;
#region Name
if (name == null)
throw new ArgumentNullException(nameof(name));
if (name.Length == 0 || name.Equals(@"[DISPID=0]"))
{
name = GetDefaultMemberName();
if (name == null)
{
// in InvokeMember we always pretend there is a default member if none is provided and we make it ToString
name = "ToString";
}
}
#endregion
#region GetField or SetField
bool IsGetField = (bindingFlags & BindingFlags.GetField) != 0;
bool IsSetField = (bindingFlags & BindingFlags.SetField) != 0;
if (IsGetField || IsSetField)
{
#region Preconditions
if (IsGetField)
{
if (IsSetField)
// "Can not specify both Get and Set on a field."
throw new ArgumentException(SR.Arg_FldSetGet, nameof(bindingFlags));
if ((bindingFlags & BindingFlags.SetProperty) != 0)
// "Can not specify both GetField and SetProperty."
throw new ArgumentException(SR.Arg_FldGetPropSet, nameof(bindingFlags));
}
else
{
Debug.Assert(IsSetField);
if (providedArgs == null)
throw new ArgumentNullException(nameof(providedArgs));
if ((bindingFlags & BindingFlags.GetProperty) != 0)
// "Can not specify both SetField and GetProperty."
throw new ArgumentException(SR.Arg_FldSetPropGet, nameof(bindingFlags));
if ((bindingFlags & BindingFlags.InvokeMethod) != 0)
// "Can not specify Set on a Field and Invoke on a method."
throw new ArgumentException(SR.Arg_FldSetInvoke, nameof(bindingFlags));
}
#endregion
#region Lookup Field
FieldInfo selFld = null;
FieldInfo[] flds = GetMember(name, MemberTypes.Field, bindingFlags) as FieldInfo[];
Debug.Assert(flds != null);
if (flds.Length == 1)
{
selFld = flds[0];
}
else if (flds.Length > 0)
{
selFld = binder.BindToField(bindingFlags, flds, IsGetField ? Empty.Value : providedArgs[0], culture);
}
#endregion
if (selFld != null)
{
#region Invocation on a field
if (selFld.FieldType.IsArray || Object.ReferenceEquals(selFld.FieldType, CommonRuntimeTypes.Array))
{
#region Invocation of an array Field
int idxCnt;
if ((bindingFlags & BindingFlags.GetField) != 0)
{
idxCnt = argCnt;
}
else
{
idxCnt = argCnt - 1;
}
if (idxCnt > 0)
{
// Verify that all of the index values are ints
int[] idx = new int[idxCnt];
for (int i = 0; i < idxCnt; i++)
{
try
{
idx[i] = ((IConvertible)providedArgs[i]).ToInt32(null);
}
catch (InvalidCastException)
{
throw new ArgumentException(SR.Arg_IndexMustBeInt);
}
}
// Set or get the value...
Array a = (Array)selFld.GetValue(target);
// Set or get the value in the array
if ((bindingFlags & BindingFlags.GetField) != 0)
{
return a.GetValue(idx);
}
else
{
a.SetValue(providedArgs[idxCnt], idx);
return null;
}
}
#endregion
}
if (IsGetField)
{
#region Get the field value
if (argCnt != 0)
throw new ArgumentException(SR.Arg_FldGetArgErr, nameof(bindingFlags));
return selFld.GetValue(target);
#endregion
}
else
{
#region Set the field Value
if (argCnt != 1)
throw new ArgumentException(SR.Arg_FldSetArgErr, nameof(bindingFlags));
selFld.SetValue(target, providedArgs[0], bindingFlags, binder, culture);
return null;
#endregion
}
#endregion
}
if ((bindingFlags & BinderNonFieldGetSet) == 0)
throw new MissingFieldException(FullName, name);
}
#endregion
#region Property PreConditions
// @Legacy - This is RTM behavior
bool isGetProperty = (bindingFlags & BindingFlags.GetProperty) != 0;
bool isSetProperty = (bindingFlags & BindingFlags.SetProperty) != 0;
if (isGetProperty || isSetProperty)
{
#region Preconditions
if (isGetProperty)
{
Debug.Assert(!IsSetField);
if (isSetProperty)
throw new ArgumentException(SR.Arg_PropSetGet, nameof(bindingFlags));
}
else
{
Debug.Assert(isSetProperty);
Debug.Assert(!IsGetField);
if ((bindingFlags & BindingFlags.InvokeMethod) != 0)
throw new ArgumentException(SR.Arg_PropSetInvoke, nameof(bindingFlags));
}
#endregion
}
#endregion
MethodInfo[] finalists = null;
MethodInfo finalist = null;
#region BindingFlags.InvokeMethod
if ((bindingFlags & BindingFlags.InvokeMethod) != 0)
{
#region Lookup Methods
MethodInfo[] semiFinalists = GetMember(name, MemberTypes.Method, bindingFlags) as MethodInfo[];
LowLevelListWithIList<MethodInfo> results = null;
for (int i = 0; i < semiFinalists.Length; i++)
{
MethodInfo semiFinalist = semiFinalists[i];
Debug.Assert(semiFinalist != null);
if (!semiFinalist.QualifiesBasedOnParameterCount(bindingFlags, CallingConventions.Any, new Type[argCnt]))
continue;
if (finalist == null)
{
finalist = semiFinalist;
}
else
{
if (results == null)
{
results = new LowLevelListWithIList<MethodInfo>(semiFinalists.Length);
results.Add(finalist);
}
results.Add(semiFinalist);
}
}
if (results != null)
{
Debug.Assert(results.Count > 1);
finalists = new MethodInfo[results.Count];
results.CopyTo(finalists, 0);
}
#endregion
}
#endregion
Debug.Assert(finalists == null || finalist != null);
#region BindingFlags.GetProperty or BindingFlags.SetProperty
if (finalist == null && isGetProperty || isSetProperty)
{
#region Lookup Property
PropertyInfo[] semiFinalists = GetMember(name, MemberTypes.Property, bindingFlags) as PropertyInfo[];
LowLevelListWithIList<MethodInfo> results = null;
for (int i = 0; i < semiFinalists.Length; i++)
{
MethodInfo semiFinalist = null;
if (isSetProperty)
{
semiFinalist = semiFinalists[i].GetSetMethod(true);
}
else
{
semiFinalist = semiFinalists[i].GetGetMethod(true);
}
if (semiFinalist == null)
continue;
BindingFlags expectedBindingFlags = semiFinalist.IsPublic ? BindingFlags.Public : BindingFlags.NonPublic;
if ((bindingFlags & expectedBindingFlags) != expectedBindingFlags)
continue;
if (!semiFinalist.QualifiesBasedOnParameterCount(bindingFlags, CallingConventions.Any, new Type[argCnt]))
continue;
if (finalist == null)
{
finalist = semiFinalist;
}
else
{
if (results == null)
{
results = new LowLevelListWithIList<MethodInfo>(semiFinalists.Length);
results.Add(finalist);
}
results.Add(semiFinalist);
}
}
if (results != null)
{
Debug.Assert(results.Count > 1);
finalists = new MethodInfo[results.Count];
results.CopyTo(finalists, 0);
}
#endregion
}
#endregion
if (finalist != null)
{
#region Invoke
if (finalists == null &&
argCnt == 0 &&
finalist.GetParametersNoCopy().Length == 0 &&
(bindingFlags & BindingFlags.OptionalParamBinding) == 0)
{
//if (useCache && argCnt == props[0].GetParameters().Length)
// AddMethodToCache(name, bindingFlags, argCnt, providedArgs, props[0]);
return finalist.Invoke(target, bindingFlags, binder, providedArgs, culture);
}
if (finalists == null)
finalists = new MethodInfo[] { finalist };
if (providedArgs == null)
providedArgs = Array.Empty<object>();
Object state = null;
MethodBase invokeMethod = null;
try { invokeMethod = binder.BindToMethod(bindingFlags, finalists, ref providedArgs, modifiers, culture, namedParams, out state); }
catch (MissingMethodException) { }
if (invokeMethod == null)
throw new MissingMethodException(FullName, name);
//if (useCache && argCnt == invokeMethod.GetParameters().Length)
// AddMethodToCache(name, bindingFlags, argCnt, providedArgs, invokeMethod);
Object result = ((MethodInfo)invokeMethod).Invoke(target, bindingFlags, binder, providedArgs, culture);
if (state != null)
binder.ReorderArgumentArray(ref providedArgs, state);
return result;
#endregion
}
throw new MissingMethodException(FullName, name);
}
}
}
| |
/*
* 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 NodaTime;
namespace QuantConnect
{
/// <summary>
/// Provides access to common time zones
/// </summary>
public static class TimeZones
{
/// <summary>
/// Gets the Universal Coordinated time zone.
/// </summary>
public static readonly DateTimeZone Utc = DateTimeZone.Utc;
/// <summary>
/// Gets the time zone for New York City, USA. This is a daylight savings time zone.
/// </summary>
public static readonly DateTimeZone NewYork = DateTimeZoneProviders.Tzdb["America/New_York"];
/// <summary>
/// Get the Eastern Standard Time (EST) WITHOUT daylight savings, this is a constant -5 hour offset
/// </summary>
public static readonly DateTimeZone EasternStandard = DateTimeZoneProviders.Tzdb["UTC-05"];
/// <summary>
/// Gets the time zone for London, England. This is a daylight savings time zone.
/// </summary>
public static readonly DateTimeZone London = DateTimeZoneProviders.Tzdb["Europe/London"];
/// <summary>
/// Gets the time zone for Hong Kong, China.
/// </summary>
public static readonly DateTimeZone HongKong = DateTimeZoneProviders.Tzdb["Asia/Hong_Kong"];
/// <summary>
/// Gets the time zone for Tokyo, Japan.
/// </summary>
public static readonly DateTimeZone Tokyo = DateTimeZoneProviders.Tzdb["Asia/Tokyo"];
/// <summary>
/// Gets the time zone for Rome, Italy. This is a daylight savings time zone.
/// </summary>
public static readonly DateTimeZone Rome = DateTimeZoneProviders.Tzdb["Europe/Rome"];
/// <summary>
/// Gets the time zone for Sydney, Australia. This is a daylight savings time zone.
/// </summary>
public static readonly DateTimeZone Sydney = DateTimeZoneProviders.Tzdb["Australia/Sydney"];
/// <summary>
/// Gets the time zone for Vancouver, Canada.
/// </summary>
public static readonly DateTimeZone Vancouver = DateTimeZoneProviders.Tzdb["America/Vancouver"];
/// <summary>
/// Gets the time zone for Toronto, Canada. This is a daylight savings time zone.
/// </summary>
public static readonly DateTimeZone Toronto = DateTimeZoneProviders.Tzdb["America/Toronto"];
/// <summary>
/// Gets the time zone for Chicago, USA. This is a daylight savings time zone.
/// </summary>
public static readonly DateTimeZone Chicago = DateTimeZoneProviders.Tzdb["America/Chicago"];
/// <summary>
/// Gets the time zone for Los Angeles, USA. This is a daylight savings time zone.
/// </summary>
public static readonly DateTimeZone LosAngeles = DateTimeZoneProviders.Tzdb["America/Los_Angeles"];
/// <summary>
/// Gets the time zone for Phoenix, USA. This is a daylight savings time zone.
/// </summary>
public static readonly DateTimeZone Phoenix = DateTimeZoneProviders.Tzdb["America/Phoenix"];
/// <summary>
/// Gets the time zone for Auckland, New Zealand. This is a daylight savings time zone.
/// </summary>
public static readonly DateTimeZone Auckland = DateTimeZoneProviders.Tzdb["Pacific/Auckland"];
/// <summary>
/// Gets the time zone for Moscow, Russia.
/// </summary>
public static readonly DateTimeZone Moscow = DateTimeZoneProviders.Tzdb["Europe/Moscow"];
/// <summary>
/// Gets the time zone for Madrid, Span. This is a daylight savings time zone.
/// </summary>
public static readonly DateTimeZone Madrid = DateTimeZoneProviders.Tzdb["Europe/Madrid"];
/// <summary>
/// Gets the time zone for Buenos Aires, Argentia.
/// </summary>
public static readonly DateTimeZone BuenosAires = DateTimeZoneProviders.Tzdb["America/Argentina/Buenos_Aires"];
/// <summary>
/// Gets the time zone for Brisbane, Australia.
/// </summary>
public static readonly DateTimeZone Brisbane = DateTimeZoneProviders.Tzdb["Australia/Brisbane"];
/// <summary>
/// Gets the time zone for Sao Paulo, Brazil. This is a daylight savings time zone.
/// </summary>
public static readonly DateTimeZone SaoPaulo = DateTimeZoneProviders.Tzdb["America/Sao_Paulo"];
/// <summary>
/// Gets the time zone for Cairo, Egypt.
/// </summary>
public static readonly DateTimeZone Cairo = DateTimeZoneProviders.Tzdb["Africa/Cairo"];
/// <summary>
/// Gets the time zone for Johannesburg, South Africa.
/// </summary>
public static readonly DateTimeZone Johannesburg = DateTimeZoneProviders.Tzdb["Africa/Johannesburg"];
/// <summary>
/// Gets the time zone for Anchorage, USA. This is a daylight savings time zone.
/// </summary>
public static readonly DateTimeZone Anchorage = DateTimeZoneProviders.Tzdb["America/Anchorage"];
/// <summary>
/// Gets the time zone for Denver, USA. This is a daylight savings time zone.
/// </summary>
public static readonly DateTimeZone Denver = DateTimeZoneProviders.Tzdb["America/Denver"];
/// <summary>
/// Gets the time zone for Detroit, USA. This is a daylight savings time zone.
/// </summary>
public static readonly DateTimeZone Detroit = DateTimeZoneProviders.Tzdb["America/Detroit"];
/// <summary>
/// Gets the time zone for Mexico City, Mexico. This is a daylight savings time zone.
/// </summary>
public static readonly DateTimeZone MexicoCity = DateTimeZoneProviders.Tzdb["America/Mexico_City"];
/// <summary>
/// Gets the time zone for Jerusalem, Israel. This is a daylight savings time zone.
/// </summary>
public static readonly DateTimeZone Jerusalem = DateTimeZoneProviders.Tzdb["Asia/Jerusalem"];
/// <summary>
/// Gets the time zone for Shanghai, China.
/// </summary>
public static readonly DateTimeZone Shanghai = DateTimeZoneProviders.Tzdb["Asia/Shanghai"];
/// <summary>
/// Gets the time zone for Melbourne, Australia. This is a daylight savings time zone.
/// </summary>
public static readonly DateTimeZone Melbourne = DateTimeZoneProviders.Tzdb["Australia/Melbourne"];
/// <summary>
/// Gets the time zone for Amsterdam, Netherlands. This is a daylight savings time zone.
/// </summary>
public static readonly DateTimeZone Amsterdam = DateTimeZoneProviders.Tzdb["Europe/Amsterdam"];
/// <summary>
/// Gets the time zone for Athens, Greece. This is a daylight savings time zone.
/// </summary>
public static readonly DateTimeZone Athens = DateTimeZoneProviders.Tzdb["Europe/Athens"];
/// <summary>
/// Gets the time zone for Berlin, Germany. This is a daylight savings time zone.
/// </summary>
public static readonly DateTimeZone Berlin = DateTimeZoneProviders.Tzdb["Europe/Berlin"];
/// <summary>
/// Gets the time zone for Bucharest, Romania. This is a daylight savings time zone.
/// </summary>
public static readonly DateTimeZone Bucharest = DateTimeZoneProviders.Tzdb["Europe/Bucharest"];
/// <summary>
/// Gets the time zone for Dublin, Ireland. This is a daylight savings time zone.
/// </summary>
public static readonly DateTimeZone Dublin = DateTimeZoneProviders.Tzdb["Europe/Dublin"];
/// <summary>
/// Gets the time zone for Helsinki, Finland. This is a daylight savings time zone.
/// </summary>
public static readonly DateTimeZone Helsinki = DateTimeZoneProviders.Tzdb["Europe/Helsinki"];
/// <summary>
/// Gets the time zone for Istanbul, Turkey. This is a daylight savings time zone.
/// </summary>
public static readonly DateTimeZone Istanbul = DateTimeZoneProviders.Tzdb["Europe/Istanbul"];
/// <summary>
/// Gets the time zone for Minsk, Belarus.
/// </summary>
public static readonly DateTimeZone Minsk = DateTimeZoneProviders.Tzdb["Europe/Minsk"];
/// <summary>
/// Gets the time zone for Paris, France. This is a daylight savings time zone.
/// </summary>
public static readonly DateTimeZone Paris = DateTimeZoneProviders.Tzdb["Europe/Paris"];
/// <summary>
/// Gets the time zone for Zurich, Switzerland. This is a daylight savings time zone.
/// </summary>
public static readonly DateTimeZone Zurich = DateTimeZoneProviders.Tzdb["Europe/Zurich"];
/// <summary>
/// Gets the time zone for Honolulu, USA. This is a daylight savings time zone.
/// </summary>
public static readonly DateTimeZone Honolulu = DateTimeZoneProviders.Tzdb["Pacific/Honolulu"];
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="WebZone.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.UI.WebControls.WebParts {
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Design;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Util;
/// <devdoc>
/// Base class for all zone classes in the WebPart framework. Contains properties used to control the UI
/// which is common to all zone classes.
/// </devdoc>
[
Designer("System.Web.UI.Design.WebControls.WebParts.WebZoneDesigner, " + AssemblyRef.SystemDesign),
Bindable(false),
]
public abstract class WebZone : CompositeControl {
private WebPartManager _webPartManager;
private const int baseIndex = 0;
private const int emptyZoneTextStyleIndex = 1;
private const int footerStyleIndex = 2;
private const int partStyleIndex = 3;
private const int partChromeStyleIndex = 4;
private const int partTitleStyleIndex = 5;
private const int headerStyleIndex = 6;
private const int verbStyleIndex = 7;
private const int errorStyleIndex = 8;
private const int viewStateArrayLength = 9;
private Style _emptyZoneTextStyle;
private TitleStyle _footerStyle;
private TableStyle _partStyle;
private Style _partChromeStyle;
private TitleStyle _partTitleStyle;
private TitleStyle _headerStyle;
private Style _verbStyle;
private Style _errorStyle;
// Prevent class from being subclassed outside of our assembly
internal WebZone() {
}
/// <devdoc>
/// The URL of the background image for the control.
/// </devdoc>
[
DefaultValue(""),
Editor("System.Web.UI.Design.ImageUrlEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)),
UrlProperty(),
WebCategory("Appearance"),
WebSysDescription(SR.WebControl_BackImageUrl)
]
public virtual string BackImageUrl {
get {
string s = (string)ViewState["BackImageUrl"];
return((s == null) ? String.Empty : s);
}
set {
ViewState["BackImageUrl"] = value;
}
}
[
// Must use WebSysDefaultValue instead of DefaultValue, since it is overridden in extending classes
Localizable(true),
WebSysDefaultValue(""),
WebCategory("Behavior"),
WebSysDescription(SR.Zone_EmptyZoneText),
]
public virtual string EmptyZoneText {
get {
string s = (string)ViewState["EmptyZoneText"];
return((s == null) ? String.Empty : s);
}
set {
ViewState["EmptyZoneText"] = value;
}
}
[
DefaultValue(null),
NotifyParentProperty(true),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
PersistenceMode(PersistenceMode.InnerProperty),
WebCategory("Styles"),
WebSysDescription(SR.Zone_EmptyZoneTextStyle),
]
public Style EmptyZoneTextStyle {
get {
if (_emptyZoneTextStyle == null) {
_emptyZoneTextStyle = new Style();
if (IsTrackingViewState) {
((IStateManager)_emptyZoneTextStyle).TrackViewState();
}
}
return _emptyZoneTextStyle;
}
}
[
DefaultValue(null),
NotifyParentProperty(true),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
PersistenceMode(PersistenceMode.InnerProperty),
WebCategory("Styles"),
WebSysDescription(SR.Zone_ErrorStyle),
]
public Style ErrorStyle {
get {
if (_errorStyle == null) {
_errorStyle = new ErrorStyle();
if (IsTrackingViewState) {
((IStateManager)_errorStyle).TrackViewState();
}
}
return _errorStyle;
}
}
/// <devdoc>
/// Style for the footer of the zone.
/// </devdoc>
[
DefaultValue(null),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
NotifyParentProperty(true),
PersistenceMode(PersistenceMode.InnerProperty),
WebCategory("Styles"),
WebSysDescription(SR.Zone_FooterStyle)
]
public TitleStyle FooterStyle {
get {
if (_footerStyle == null) {
_footerStyle = new TitleStyle();
if (IsTrackingViewState) {
((IStateManager)_footerStyle).TrackViewState();
}
}
return _footerStyle;
}
}
protected virtual bool HasFooter {
get {
return true;
}
}
protected virtual bool HasHeader {
get {
return true;
}
}
/// <devdoc>
/// The header text of the zone.
/// </devdoc>
[
// Must use WebSysDefaultValue instead of DefaultValue, since it is overridden in extending classes
Localizable(true),
WebSysDefaultValue(""),
WebCategory("Appearance"),
WebSysDescription(SR.Zone_HeaderText)
]
public virtual string HeaderText {
get {
string s = (string)ViewState["HeaderText"];
return((s == null) ? String.Empty : s);
}
set {
ViewState["HeaderText"] = value;
}
}
/// <devdoc>
/// Style for the title bar of the zone.
/// </devdoc>
[
DefaultValue(null),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
NotifyParentProperty(true),
PersistenceMode(PersistenceMode.InnerProperty),
WebCategory("Styles"),
WebSysDescription(SR.Zone_HeaderStyle)
]
public TitleStyle HeaderStyle {
get {
if (_headerStyle == null) {
_headerStyle = new TitleStyle();
if (IsTrackingViewState) {
((IStateManager)_headerStyle).TrackViewState();
}
}
return _headerStyle;
}
}
/// <devdoc>
/// Padding for the contained parts.
/// </devdoc>
[
DefaultValue(typeof(Unit), "5px"),
WebCategory("WebPart"),
WebSysDescription(SR.Zone_PartChromePadding)
]
public Unit PartChromePadding {
get {
object obj = ViewState["PartChromePadding"];
return (obj == null) ? Unit.Pixel(5) : (Unit)obj;
}
set {
if (value.Value < 0) {
throw new ArgumentOutOfRangeException("value");
}
ViewState["PartChromePadding"] = value;
}
}
/// <devdoc>
/// Style for the contained parts.
/// </devdoc>
[
DefaultValue(null),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
NotifyParentProperty(true),
PersistenceMode(PersistenceMode.InnerProperty),
WebCategory("WebPart"),
WebSysDescription(SR.Zone_PartChromeStyle)
]
public Style PartChromeStyle {
get {
if (_partChromeStyle == null) {
_partChromeStyle = new Style();
if (IsTrackingViewState) {
((IStateManager)_partChromeStyle).TrackViewState();
}
}
return _partChromeStyle;
}
}
/// <devdoc>
/// The type of frame/border for the contained parts.
/// </devdoc>
[
DefaultValue(PartChromeType.Default),
WebCategory("WebPart"),
WebSysDescription(SR.Zone_PartChromeType)
]
public virtual PartChromeType PartChromeType {
get {
object o = ViewState["PartChromeType"];
return (o != null) ? (PartChromeType)(int)o : PartChromeType.Default;
}
set {
if ((value < PartChromeType.Default) || (value > PartChromeType.BorderOnly)) {
throw new ArgumentOutOfRangeException("value");
}
ViewState["PartChromeType"] = (int)value;
}
}
/// <devdoc>
/// Style for the contents of the contained parts.
/// </devdoc>
[
DefaultValue(null),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
NotifyParentProperty(true),
PersistenceMode(PersistenceMode.InnerProperty),
WebCategory("WebPart"),
WebSysDescription(SR.Zone_PartStyle)
]
public TableStyle PartStyle {
get {
if (_partStyle == null) {
_partStyle = new TableStyle();
if (IsTrackingViewState) {
((IStateManager)_partStyle).TrackViewState();
}
}
return _partStyle;
}
}
/// <devdoc>
/// Style for the title bars of the contained parts.
/// </devdoc>
[
DefaultValue(null),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
NotifyParentProperty(true),
PersistenceMode(PersistenceMode.InnerProperty),
WebCategory("WebPart"),
WebSysDescription(SR.Zone_PartTitleStyle)
]
public TitleStyle PartTitleStyle {
get {
if (_partTitleStyle == null) {
_partTitleStyle = new TitleStyle();
if (IsTrackingViewState) {
((IStateManager)_partTitleStyle).TrackViewState();
}
}
return _partTitleStyle;
}
}
protected override HtmlTextWriterTag TagKey {
get {
return HtmlTextWriterTag.Table;
}
}
// Padding = -1 means we will not render anything for the cellpadding attribute
[
DefaultValue(2),
WebCategory("Layout"),
WebSysDescription(SR.Zone_Padding),
]
public virtual int Padding {
get {
object obj = ViewState["Padding"];
return (obj == null) ? 2 : (int) obj;
}
set {
if (value < -1) {
throw new ArgumentOutOfRangeException("value");
}
ViewState["Padding"] = value;
}
}
// Called by WebPartZoneBase, EditorZoneBase, CatalogZoneBase, and ConnectionsZone.
internal void RenderBodyTableBeginTag(HtmlTextWriter writer) {
//
writer.AddAttribute(HtmlTextWriterAttribute.Cellspacing, "0");
int padding = Padding;
if (padding >= 0) {
writer.AddAttribute(HtmlTextWriterAttribute.Cellpadding, padding.ToString(CultureInfo.InvariantCulture));
}
writer.AddAttribute(HtmlTextWriterAttribute.Border, "0");
// Copied from Panel.cs
//
string backImageUrl = BackImageUrl;
// Whidbey 12856
if (backImageUrl.Trim().Length > 0)
writer.AddStyleAttribute(HtmlTextWriterStyle.BackgroundImage,"url(" + ResolveClientUrl(backImageUrl) + ")");
// Needed if Zone HeaderText is wider than contained Parts
writer.AddStyleAttribute(HtmlTextWriterStyle.Width, "100%");
// Needed if the height of the Zone is taller than the height of its contents
writer.AddStyleAttribute(HtmlTextWriterStyle.Height, "100%");
writer.RenderBeginTag(HtmlTextWriterTag.Table);
}
// Called by WebPartZoneBase, EditorZoneBase, CatalogZoneBase, and ConnectionsZone.
internal static void RenderBodyTableEndTag(HtmlTextWriter writer) {
writer.RenderEndTag(); // Table
}
// Called by WebPartZoneBase, EditorZoneBase, and CatalogZoneBase.
internal void RenderDesignerRegionBeginTag(HtmlTextWriter writer, Orientation orientation) {
writer.AddAttribute(HtmlTextWriterAttribute.Valign, "top");
writer.RenderBeginTag(HtmlTextWriterTag.Tr);
if (orientation == Orientation.Horizontal) {
writer.AddStyleAttribute(HtmlTextWriterStyle.WhiteSpace, "nowrap");
}
writer.AddAttribute(HtmlTextWriterAttribute.DesignerRegion, "0");
writer.RenderBeginTag(HtmlTextWriterTag.Td);
writer.AddAttribute(HtmlTextWriterAttribute.Cellspacing, "0");
writer.AddAttribute(HtmlTextWriterAttribute.Cellpadding, Padding.ToString(CultureInfo.InvariantCulture));
writer.AddAttribute(HtmlTextWriterAttribute.Border, "0");
if (orientation == Orientation.Vertical) {
writer.AddStyleAttribute(HtmlTextWriterStyle.Width, "100%");
}
else {
writer.AddStyleAttribute(HtmlTextWriterStyle.Height, "100%");
}
writer.RenderBeginTag(HtmlTextWriterTag.Table);
}
// Called by WebPartZoneBase, EditorZoneBase, and CatalogZoneBase.
internal static void RenderDesignerRegionEndTag(HtmlTextWriter writer) {
writer.RenderEndTag(); // Table
writer.RenderEndTag(); // Td
writer.RenderEndTag(); // Tr
}
protected internal bool RenderClientScript {
get {
bool renderClientScript = false;
if (DesignMode) {
renderClientScript = true;
}
else if (WebPartManager != null) {
renderClientScript = WebPartManager.RenderClientScript;
}
return renderClientScript;
}
}
/// <devdoc>
/// The type of the button rendered for each verb.
/// </devdoc>
[
DefaultValue(ButtonType.Button),
WebCategory("Appearance"),
WebSysDescription(SR.Zone_VerbButtonType),
]
public virtual ButtonType VerbButtonType {
get {
object obj = ViewState["VerbButtonType"];
return (obj == null) ? ButtonType.Button : (ButtonType)obj;
}
set {
if (value < ButtonType.Button || value > ButtonType.Link) {
throw new ArgumentOutOfRangeException("value");
}
ViewState["VerbButtonType"] = value;
}
}
[
DefaultValue(null),
NotifyParentProperty(true),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
PersistenceMode(PersistenceMode.InnerProperty),
WebCategory("Styles"),
WebSysDescription(SR.Zone_VerbStyle),
]
public Style VerbStyle {
get {
if (_verbStyle == null) {
_verbStyle = new Style();
if (IsTrackingViewState) {
((IStateManager)_verbStyle).TrackViewState();
}
}
return _verbStyle;
}
}
/// <devdoc>
/// The effective chrome type of a part, taking into consideration the PartChromeType
/// of the zone and the DisplayMode of the page.
/// </devdoc>
public virtual PartChromeType GetEffectiveChromeType(Part part) {
if (part == null) {
throw new ArgumentNullException("part");
}
PartChromeType chromeType = part.ChromeType;
if (chromeType == PartChromeType.Default) {
PartChromeType partChromeType = PartChromeType;
if (partChromeType == PartChromeType.Default) {
chromeType = PartChromeType.TitleAndBorder;
}
else {
chromeType = partChromeType;
}
}
Debug.Assert(chromeType != PartChromeType.Default);
return chromeType;
}
protected override void LoadViewState(object savedState) {
if (savedState == null) {
base.LoadViewState(null);
}
else {
object[] myState = (object[]) savedState;
if (myState.Length != viewStateArrayLength) {
throw new ArgumentException(SR.GetString(SR.ViewState_InvalidViewState));
}
base.LoadViewState(myState[baseIndex]);
if (myState[emptyZoneTextStyleIndex] != null) {
((IStateManager) EmptyZoneTextStyle).LoadViewState(myState[emptyZoneTextStyleIndex]);
}
if (myState[footerStyleIndex] != null) {
((IStateManager) FooterStyle).LoadViewState(myState[footerStyleIndex]);
}
if (myState[partStyleIndex] != null) {
((IStateManager) PartStyle).LoadViewState(myState[partStyleIndex]);
}
if (myState[partChromeStyleIndex] != null) {
((IStateManager) PartChromeStyle).LoadViewState(myState[partChromeStyleIndex]);
}
if (myState[partTitleStyleIndex] != null) {
((IStateManager) PartTitleStyle).LoadViewState(myState[partTitleStyleIndex]);
}
if (myState[headerStyleIndex] != null) {
((IStateManager) HeaderStyle).LoadViewState(myState[headerStyleIndex]);
}
if (myState[verbStyleIndex] != null) {
((IStateManager) VerbStyle).LoadViewState(myState[verbStyleIndex]);
}
if (myState[errorStyleIndex] != null) {
((IStateManager) ErrorStyle).LoadViewState(myState[errorStyleIndex]);
}
}
}
protected internal override void OnInit(EventArgs e) {
base.OnInit(e);
Page page = Page;
Debug.Assert(page != null);
if (page != null) {
if (page.ControlState >= ControlState.Initialized && !DesignMode) {
throw new InvalidOperationException(SR.GetString(SR.Zone_AddedTooLate));
}
if (!DesignMode) {
_webPartManager = WebPartManager.GetCurrentWebPartManager(page);
if (_webPartManager == null) {
throw new InvalidOperationException(SR.GetString(SR.WebPartManagerRequired));
}
_webPartManager.RegisterZone(this);
}
}
}
protected internal override void OnPreRender(EventArgs e) {
base.OnPreRender(e);
Control parent = Parent;
Debug.Assert(parent != null);
if (parent != null && (parent is WebZone || parent is Part)) {
throw new InvalidOperationException(SR.GetString(SR.Zone_InvalidParent));
}
}
public override void RenderBeginTag(HtmlTextWriter writer) {
writer.AddAttribute(HtmlTextWriterAttribute.Cellspacing, "0");
writer.AddAttribute(HtmlTextWriterAttribute.Cellpadding, "0");
writer.AddAttribute(HtmlTextWriterAttribute.Border, "0");
// On Mac IE, if height is not set, render height:1px, so the table sizes to contents.
// Otherwise, Mac IE may give the table an arbitrary height (equal to the width of its contents).
if (!DesignMode &&
Page != null &&
Page.Request.Browser.Type == "IE5" &&
Page.Request.Browser.Platform == "MacPPC" &&
(!ControlStyleCreated || ControlStyle.Height == Unit.Empty)) {
writer.AddStyleAttribute(HtmlTextWriterStyle.Height, "1px");
}
// Render <table>
base.RenderBeginTag(writer);
}
protected internal override void RenderContents(HtmlTextWriter writer) {
if (HasHeader) {
writer.RenderBeginTag(HtmlTextWriterTag.Tr);
TitleStyle headerStyle = HeaderStyle;
if (!headerStyle.IsEmpty) {
headerStyle.AddAttributesToRender(writer, this);
}
writer.RenderBeginTag(HtmlTextWriterTag.Td);
RenderHeader(writer);
writer.RenderEndTag(); // Td
writer.RenderEndTag(); // Tr
}
writer.RenderBeginTag(HtmlTextWriterTag.Tr);
// We want the body to fill the height of the zone, and squish the header and footer
// to the size of their contents
// Mac IE needs height=100% set on <td> instead of <tr>
writer.AddStyleAttribute(HtmlTextWriterStyle.Height, "100%");
writer.RenderBeginTag(HtmlTextWriterTag.Td);
RenderBody(writer);
writer.RenderEndTag(); // Td
writer.RenderEndTag(); // Tr
if (HasFooter) {
writer.RenderBeginTag(HtmlTextWriterTag.Tr);
TitleStyle footerStyle = FooterStyle;
if (!footerStyle.IsEmpty) {
footerStyle.AddAttributesToRender(writer, this);
}
writer.RenderBeginTag(HtmlTextWriterTag.Td);
RenderFooter(writer);
writer.RenderEndTag(); // Td
writer.RenderEndTag(); // Tr
}
}
protected virtual void RenderHeader(HtmlTextWriter writer) {
}
protected virtual void RenderBody(HtmlTextWriter writer) {
}
protected virtual void RenderFooter(HtmlTextWriter writer) {
}
protected override object SaveViewState() {
object[] myState = new object[viewStateArrayLength];
myState[baseIndex] = base.SaveViewState();
myState[emptyZoneTextStyleIndex] = (_emptyZoneTextStyle != null) ? ((IStateManager)_emptyZoneTextStyle).SaveViewState() : null;
myState[footerStyleIndex] = (_footerStyle != null) ? ((IStateManager)_footerStyle).SaveViewState() : null;
myState[partStyleIndex] = (_partStyle != null) ? ((IStateManager)_partStyle).SaveViewState() : null;
myState[partChromeStyleIndex] = (_partChromeStyle != null) ? ((IStateManager)_partChromeStyle).SaveViewState() : null;
myState[partTitleStyleIndex] = (_partTitleStyle != null) ? ((IStateManager)_partTitleStyle).SaveViewState() : null;
myState[headerStyleIndex] = (_headerStyle != null) ? ((IStateManager)_headerStyle).SaveViewState() : null;
myState[verbStyleIndex] = (_verbStyle != null) ? ((IStateManager)_verbStyle).SaveViewState() : null;
myState[errorStyleIndex] = (_errorStyle != null) ? ((IStateManager)_errorStyle).SaveViewState() : null;
for (int i=0; i < viewStateArrayLength; i++) {
if (myState[i] != null) {
return myState;
}
}
// More performant to return null than an array of null values
return null;
}
protected override void TrackViewState() {
base.TrackViewState();
if (_emptyZoneTextStyle != null) {
((IStateManager) _emptyZoneTextStyle).TrackViewState();
}
if (_footerStyle != null) {
((IStateManager) _footerStyle).TrackViewState();
}
if (_partStyle != null) {
((IStateManager) _partStyle).TrackViewState();
}
if (_partChromeStyle != null) {
((IStateManager) _partChromeStyle).TrackViewState();
}
if (_partTitleStyle != null) {
((IStateManager) _partTitleStyle).TrackViewState();
}
if (_headerStyle != null) {
((IStateManager) _headerStyle).TrackViewState();
}
if (_verbStyle != null) {
((IStateManager) _verbStyle).TrackViewState();
}
if (_errorStyle != null) {
((IStateManager) _errorStyle).TrackViewState();
}
}
protected WebPartManager WebPartManager {
get {
return _webPartManager;
}
}
}
}
| |
using System;
using System.Collections;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.Drawing;
using System.Text;
namespace SharpVectors.Dom.Svg
{
// TODO: should we check that the list starts with a M/m since that's required by the spec?
public class SvgPathSegList : ISvgPathSegList
{
#region Constructors
public SvgPathSegList(string d, bool readOnly)
{
parseString(d);
this.readOnly = readOnly;
}
#endregion
#region Private properties
private bool readOnly = false;
private ArrayList segments = new ArrayList();
private static Regex rePathCmd = new Regex(@"(?=[A-Za-z])");
private static Regex coordSplit = new Regex(@"(\s*,\s*)|(\s+)|((?<=[0-9])(?=-))", RegexOptions.ExplicitCapture);
#endregion
#region Private methods
private void parseString(string d)
{
ISvgPathSeg seg;
string[] segs = rePathCmd.Split(d);
foreach(string s in segs)
{
string segment = s.Trim();
if(segment.Length > 0)
{
char cmd = (char) segment.ToCharArray(0,1)[0];
float[] coords = getCoords(segment);
int length = coords.Length;
switch(cmd)
{
#region moveto
case 'M':
for(int i = 0; i<length; i+=2)
{
if(i == 0)
{
seg = new SvgPathSegMovetoAbs(
coords[i],
coords[i+1]
);
}
else
{
seg = new SvgPathSegLinetoAbs(
coords[i],
coords[i+1]
);
}
AppendItem(seg);
}
break;
case 'm':
for(int i = 0; i<length; i+=2)
{
if(i == 0)
{
seg = new SvgPathSegMovetoRel(
coords[i],
coords[i+1]
);
}
else
{
seg = new SvgPathSegLinetoRel(
coords[i],
coords[i+1]
);
}
AppendItem(seg);
}
break;
#endregion
#region lineto
case 'L':
for(int i = 0; i<length; i+=2)
{
seg = new SvgPathSegLinetoAbs(
coords[i],
coords[i+1]
);
AppendItem(seg);
}
break;
case 'l':
for(int i = 0; i<length; i+=2)
{
seg = new SvgPathSegLinetoRel(
coords[i],
coords[i+1]
);
AppendItem(seg);
}
break;
case 'H':
for(int i = 0; i<length; i++)
{
seg = new SvgPathSegLinetoHorizontalAbs(
coords[i]
);
AppendItem(seg);
}
break;
case 'h':
for(int i = 0; i<length; i++)
{
seg = new SvgPathSegLinetoHorizontalRel(
coords[i]
);
AppendItem(seg);
}
break;
case 'V':
for(int i = 0; i<length; i++)
{
seg = new SvgPathSegLinetoVerticalAbs(
coords[i]
);
AppendItem(seg);
}
break;
case'v':
for(int i = 0; i<length; i++)
{
seg = new SvgPathSegLinetoVerticalRel(
coords[i]
);
AppendItem(seg);
}
break;
#endregion
#region beziers
case 'C':
for(int i = 0; i<length; i+=6)
{
seg = new SvgPathSegCurvetoCubicAbs(
coords[i+4],
coords[i+5],
coords[i],
coords[i+1],
coords[i+2],
coords[i+3]
);
AppendItem(seg);
}
break;
case 'c':
for(int i = 0; i<length; i+=6)
{
seg = new SvgPathSegCurvetoCubicRel(
coords[i+4],
coords[i+5],
coords[i],
coords[i+1],
coords[i+2],
coords[i+3]
);
AppendItem(seg);
}
break;
case 'S':
for(int i = 0; i<length; i+=4)
{
seg = new SvgPathSegCurvetoCubicSmoothAbs(
coords[i+2],
coords[i+3],
coords[i],
coords[i+1]
);
AppendItem(seg);
}
break;
case's':
for(int i = 0; i<length; i+=4)
{
seg = new SvgPathSegCurvetoCubicSmoothRel(
coords[i+2],
coords[i+3],
coords[i],
coords[i+1]
);
AppendItem(seg);
}
break;
case 'Q':
for(int i = 0; i<length; i+=4)
{
seg = new SvgPathSegCurvetoQuadraticAbs(
coords[i+2],
coords[i+3],
coords[i],
coords[i+1]
);
AppendItem(seg);
}
break;
case 'q':
for(int i = 0; i<length; i+=4)
{
seg = new SvgPathSegCurvetoQuadraticRel(
coords[i+2],
coords[i+3],
coords[i],
coords[i+1]
);
AppendItem(seg);
}
break;
case 'T':
for(int i = 0; i<length; i+=2)
{
seg = new SvgPathSegCurvetoQuadraticSmoothAbs(
coords[i],
coords[i+1]
);
AppendItem(seg);
}
break;
case 't':
for(int i = 0; i<length; i+=2)
{
seg = new SvgPathSegCurvetoQuadraticSmoothRel(
coords[i],
coords[i+1]
);
AppendItem(seg);
}
break;
#endregion
#region arcs
case 'A':
case 'a':
for(int i = 0; i<length; i+=7)
{
if(cmd=='A')
{
seg = new SvgPathSegArcAbs(
coords[i+5],
coords[i+6],
coords[i],
coords[i+1],
coords[i+2],
(coords[i+3]!=0),
(coords[i+4]!=0)
);
}
else
{
seg = new SvgPathSegArcRel(
coords[i+5],
coords[i+6],
coords[i],
coords[i+1],
coords[i+2],
(coords[i+3]!=0),
(coords[i+4]!=0)
);
}
AppendItem(seg);
}
break;
#endregion
#region close
case 'z':
case 'Z':
seg = new SvgPathSegClosePath();
AppendItem(seg);
break;
#endregion
#region Unknown path command
default:
throw new ApplicationException("Unknown path command");
#endregion
}
}
}
}
private float[] getCoords(String segment)
{
float[] coords = new float[0];
segment = segment.Substring(1);
segment = segment.Trim();
segment = segment.Trim(new char[]{','});
if(segment.Length > 0)
{
string[] sCoords = coordSplit.Split(segment);
coords = new float[sCoords.Length];
for(int i = 0; i<sCoords.Length; i++)
{
coords[i] = SvgNumber.ParseToFloat(sCoords[i]);
}
}
return coords;
}
private void setListAndIndex(SvgPathSeg newItem, int index)
{
if(newItem != null)
{
newItem.setList(this);
newItem.setIndex(index);
}
else
{
throw new SvgException(SvgExceptionType.SvgWrongTypeErr, "Can only add SvgPathSeg subclasses to ISvgPathSegList");
}
}
private void changeIndexes(int startAt, int diff)
{
int count = segments.Count;
for(int i = startAt; i<count; i++)
{
SvgPathSeg seg = segments[i] as SvgPathSeg;
if(seg != null)
{
seg.setIndexWithDiff(diff);
}
}
}
#endregion
#region Implementation of ISvgPathSegList
public int NumberOfItems
{
get{
return segments.Count;
}
}
public void Clear ()
{
if(readOnly)
{
throw new DomException(DomExceptionType.NoModificationAllowedErr);
}
else
{
segments.Clear();
}
}
public ISvgPathSeg Initialize (ISvgPathSeg newItem )
{
Clear();
return AppendItem(newItem);
}
public ISvgPathSeg GetItem (int index )
{
if(index < 0 || index >= NumberOfItems)
{
throw new DomException(DomExceptionType.IndexSizeErr);
}
return (ISvgPathSeg) segments[index];
}
public ISvgPathSeg this[int index]
{
get
{
return GetItem(index);
}
set
{
ReplaceItem(value, index);
}
}
public ISvgPathSeg InsertItemBefore ( ISvgPathSeg newItem, int index )
{
if(readOnly)
{
throw new DomException(DomExceptionType.NoModificationAllowedErr);
}
else
{
segments.Insert(index, newItem);
setListAndIndex(newItem as SvgPathSeg, index);
changeIndexes(index+1, 1);
return newItem;
}
}
public ISvgPathSeg ReplaceItem (ISvgPathSeg newItem, int index )
{
if(readOnly)
{
throw new DomException(DomExceptionType.NoModificationAllowedErr);
}
else
{
ISvgPathSeg replacedItem = GetItem(index);
segments[index] = newItem;
setListAndIndex(newItem as SvgPathSeg, index);
return replacedItem;
}
}
public ISvgPathSeg RemoveItem (int index )
{
if(readOnly)
{
throw new DomException(DomExceptionType.NoModificationAllowedErr);
}
else
{
ISvgPathSeg result = GetItem(index);
segments.RemoveAt(index);
changeIndexes(index, -1);
return result;
}
}
public ISvgPathSeg AppendItem ( ISvgPathSeg newItem )
{
if(readOnly)
{
throw new DomException(DomExceptionType.NoModificationAllowedErr);
}
else
{
segments.Add(newItem);
setListAndIndex(newItem as SvgPathSeg, segments.Count - 1);
return newItem;
}
}
#endregion
#region Public members
public PointF[] Points
{
get
{
ArrayList ret = new ArrayList();
foreach(SvgPathSeg seg in segments)
{
ret.Add(seg.AbsXY);
}
return (PointF[])ret.ToArray(typeof(PointF));
}
}
internal SvgPathSeg GetPreviousSegment(SvgPathSeg seg)
{
int index = segments.IndexOf(seg);
if(index == -1)
{
throw new Exception("Path segment not part of this list");
}
else if(index == 0)
{
return null;
}
else
{
return (SvgPathSeg)GetItem(index - 1);
}
}
internal SvgPathSeg GetNextSegment(SvgPathSeg seg)
{
int index = segments.IndexOf(seg);
if(index == -1)
{
throw new Exception("Path segment not part of this list");
}
else if(index == segments.Count-1)
{
return null;
}
else
{
return (SvgPathSeg)this[index + 1];
}
}
public float GetStartAngle(int index)
{
return ((SvgPathSeg)this[index]).StartAngle;
}
public float GetEndAngle(int index)
{
return ((SvgPathSeg)this[index]).EndAngle;
}
public string PathText
{
get
{
StringBuilder sb = new StringBuilder();
foreach(SvgPathSeg seg in segments)
{
sb.Append(seg.PathText);
}
return sb.ToString();
}
}
internal float GetTotalLength()
{
float result = 0;
foreach(SvgPathSeg segment in segments)
{
result += segment.Length;
}
return result;
}
internal int GetPathSegAtLength(float distance)
{
float result = 0;
foreach(SvgPathSeg segment in segments)
{
result += segment.Length;
if(result > distance)
{
return segment.Index;
}
}
// distance was to big, return last item index
// TODO: is this correct?
return NumberOfItems - 1;
}
#endregion
}
}
| |
//
// Copyright 2011-2013, Xamarin Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Media.Plugin.Abstractions;
using System.Runtime.InteropServices;
using System.Threading;
using CoreImage;
using Photos;
#if __UNIFIED__
using CoreGraphics;
using AssetsLibrary;
using Foundation;
using UIKit;
using NSAction = global::System.Action;
using CoreLocation;
using ImageIO;
#else
using MonoTouch.AssetsLibrary;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using CGRect = global::System.Drawing.RectangleF;
using nfloat = global::System.Single;
#endif
namespace Media.Plugin
{
internal class MediaPickerDelegate
: UIImagePickerControllerDelegate
{
internal MediaPickerDelegate (UIViewController viewController, UIImagePickerControllerSourceType sourceType, StoreCameraMediaOptions options)
{
this.viewController = viewController;
this.source = sourceType;
this.options = options ?? new StoreCameraMediaOptions();
if (viewController != null) {
UIDevice.CurrentDevice.BeginGeneratingDeviceOrientationNotifications();
this.observer = NSNotificationCenter.DefaultCenter.AddObserver (UIDevice.OrientationDidChangeNotification, DidRotate);
}
}
public UIPopoverController Popover
{
get;
set;
}
public UIView View
{
get { return this.viewController.View; }
}
public Task<MediaFile> Task
{
get { return tcs.Task; }
}
public override async void FinishedPickingMedia (UIImagePickerController picker, NSDictionary info)
{
MediaFile mediaFile;
switch ((NSString)info[UIImagePickerController.MediaType])
{
case MediaImplementation.TypeImage:
mediaFile = await GetPictureMediaFileAsync (info);
break;
case MediaImplementation.TypeMovie:
mediaFile = GetMovieMediaFile (info);
break;
default:
throw new NotSupportedException();
}
Dismiss (picker, () => this.tcs.TrySetResult (mediaFile));
}
public override void Canceled (UIImagePickerController picker)
{
Dismiss (picker, () => this.tcs.SetResult(null));
}
public void DisplayPopover (bool hideFirst = false)
{
if (Popover == null)
return;
var swidth = UIScreen.MainScreen.Bounds.Width;
var sheight= UIScreen.MainScreen.Bounds.Height;
nfloat width = 400;
nfloat height = 300;
if (this.orientation == null)
{
if (IsValidInterfaceOrientation (UIDevice.CurrentDevice.Orientation))
this.orientation = UIDevice.CurrentDevice.Orientation;
else
this.orientation = GetDeviceOrientation (this.viewController.InterfaceOrientation);
}
nfloat x, y;
if (this.orientation == UIDeviceOrientation.LandscapeLeft || this.orientation == UIDeviceOrientation.LandscapeRight)
{
y = (swidth / 2) - (height / 2);
x = (sheight / 2) - (width / 2);
}
else
{
x = (swidth / 2) - (width / 2);
y = (sheight / 2) - (height / 2);
}
if (hideFirst && Popover.PopoverVisible)
Popover.Dismiss (animated: false);
Popover.PresentFromRect (new CGRect (x, y, width, height), View, 0, animated: true);
}
private UIDeviceOrientation? orientation;
private NSObject observer;
private readonly UIViewController viewController;
private readonly UIImagePickerControllerSourceType source;
private readonly TaskCompletionSource<MediaFile> tcs = new TaskCompletionSource<MediaFile>();
private readonly StoreCameraMediaOptions options;
private bool IsCaptured
{
get { return this.source == UIImagePickerControllerSourceType.Camera; }
}
private void Dismiss (UIImagePickerController picker, NSAction onDismiss)
{
if (this.viewController == null)
onDismiss();
else {
NSNotificationCenter.DefaultCenter.RemoveObserver (this.observer);
UIDevice.CurrentDevice.EndGeneratingDeviceOrientationNotifications();
this.observer.Dispose();
if (Popover != null) {
Popover.Dismiss (animated: true);
Popover.Dispose();
Popover = null;
onDismiss();
} else {
picker.DismissViewController (true, onDismiss);
picker.Dispose();
}
}
}
private void DidRotate (NSNotification notice)
{
UIDevice device = (UIDevice)notice.Object;
if (!IsValidInterfaceOrientation (device.Orientation) || Popover == null)
return;
if (this.orientation.HasValue && IsSameOrientationKind (this.orientation.Value, device.Orientation))
return;
if (UIDevice.CurrentDevice.CheckSystemVersion (6, 0))
{
if (!GetShouldRotate6 (device.Orientation))
return;
}
else if (!GetShouldRotate (device.Orientation))
return;
UIDeviceOrientation? co = this.orientation;
this.orientation = device.Orientation;
if (co == null)
return;
DisplayPopover (hideFirst: true);
}
private bool GetShouldRotate (UIDeviceOrientation orientation)
{
UIInterfaceOrientation iorientation = UIInterfaceOrientation.Portrait;
switch (orientation)
{
case UIDeviceOrientation.LandscapeLeft:
iorientation = UIInterfaceOrientation.LandscapeLeft;
break;
case UIDeviceOrientation.LandscapeRight:
iorientation = UIInterfaceOrientation.LandscapeRight;
break;
case UIDeviceOrientation.Portrait:
iorientation = UIInterfaceOrientation.Portrait;
break;
case UIDeviceOrientation.PortraitUpsideDown:
iorientation = UIInterfaceOrientation.PortraitUpsideDown;
break;
default: return false;
}
return this.viewController.ShouldAutorotateToInterfaceOrientation (iorientation);
}
private bool GetShouldRotate6 (UIDeviceOrientation orientation)
{
if (!this.viewController.ShouldAutorotate())
return false;
UIInterfaceOrientationMask mask = UIInterfaceOrientationMask.Portrait;
switch (orientation)
{
case UIDeviceOrientation.LandscapeLeft:
mask = UIInterfaceOrientationMask.LandscapeLeft;
break;
case UIDeviceOrientation.LandscapeRight:
mask = UIInterfaceOrientationMask.LandscapeRight;
break;
case UIDeviceOrientation.Portrait:
mask = UIInterfaceOrientationMask.Portrait;
break;
case UIDeviceOrientation.PortraitUpsideDown:
mask = UIInterfaceOrientationMask.PortraitUpsideDown;
break;
default: return false;
}
return this.viewController.GetSupportedInterfaceOrientations().HasFlag (mask);
}
private async Task<MediaFile> GetPictureMediaFileAsync (NSDictionary info)
{
var image = (UIImage)info[UIImagePickerController.EditedImage];
if (image == null)
image = (UIImage)info[UIImagePickerController.OriginalImage];
var library = new ALAssetsLibrary();
var assetUrlTCS = new TaskCompletionSource<NSUrl>();
if (this.source == UIImagePickerControllerSourceType.Camera)
{
// user took a picture
// get the metadata
var metadata = info[UIImagePickerController.MediaMetadata] as NSDictionary;
var newMetadata = new NSMutableDictionary(metadata);
if (!newMetadata.ContainsKey(ImageIO.CGImageProperties.GPSDictionary))
{
var gpsData = await BuildGPSDataAsync();
if (gpsData != null)
newMetadata.Add(ImageIO.CGImageProperties.GPSDictionary, gpsData);
}
// save to camera roll with metadata
library.WriteImageToSavedPhotosAlbum(image.CGImage, newMetadata, (newAssetUrl, error) =>
{
// any additional processing can go here
if (error == null)
assetUrlTCS.SetResult(newAssetUrl);
else
assetUrlTCS.SetException(new Exception(error.LocalizedFailureReason));
});
}
else
{
// get the assetUrl for the selected image
assetUrlTCS.SetResult(info[UIImagePickerController.ReferenceUrl] as NSUrl);
}
if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
{
var assetUrl = await assetUrlTCS.Task.ConfigureAwait(false);
var assets = PHAsset.FetchAssets(new NSUrl[] { assetUrl }, null);
if (assets.Count == 0)
throw new NullReferenceException("Unable to find the specified asset.");
var asset = (PHAsset)assets[0];
var imgMgr = new PHImageManager();
var imgTCS = new TaskCompletionSource<NSData>();
var imageName = "Unknown";
imgMgr.RequestImageData(asset, null, (data, uti, imageOrientation, dictionary) =>
{
var fileUrl = dictionary["PHImageFileURLKey"].ToString();
if (!string.IsNullOrWhiteSpace(fileUrl))
{
var slash = fileUrl.LastIndexOf('/');
if (slash > -1)
imageName = fileUrl.Substring(slash + 1);
}
imgTCS.SetResult(data);
});
var img = await imgTCS.Task.ConfigureAwait(false);
return new MediaFile(imageName, assetUrl.ToString(), () => img.AsStream(), true);
}
else
{
// get the default representation of the asset
var dRepTCS = new TaskCompletionSource<ALAssetRepresentation>();
var assetUrl = await assetUrlTCS.Task.ConfigureAwait(false);
library.AssetForUrl(
assetUrl,
(asset) => dRepTCS.SetResult(asset.DefaultRepresentation),
(error) => dRepTCS.SetException(new Exception(error.LocalizedFailureReason))
);
var rep = await dRepTCS.Task.ConfigureAwait(false);
// now some really ugly code to copy that as a byte array
var size = (uint)rep.Size;
//byte[] imgData = new byte[size];
IntPtr buffer = Marshal.AllocHGlobal((int)size);
NSError bError;
rep.GetBytes(buffer, 0, (uint)size, out bError);
//Marshal.Copy(buffer, imgData, 0, imgData.Length);
var imgData = NSData.FromBytes(buffer, (uint)size);
Marshal.FreeHGlobal(buffer);
return new MediaFile(rep.Filename, assetUrl.ToString(), imgData.AsStream);
}
// string path = GetOutputPath (MediaImplementation.TypeImage,
// options.Directory ?? ((IsCaptured) ? String.Empty : "temp"),
// options.Name);
//
// var jpegImage = image.AsJPEG();
// metadata = await metaDataTCS.Task.ConfigureAwait(false);
// if (metadata != null && metadata.Count > 0)
// // getting an error here - looks like some of the metadata is not valid for a jpeg
// jpegImage.SetValuesForKeysWithDictionary(metadata);
// using (FileStream fs = File.OpenWrite (path))
// using (Stream s = new NSDataStream (jpegImage))
// {
// s.CopyTo (fs);
// fs.Flush();
// }
//
// Action<bool> dispose = null;
// if (this.source != UIImagePickerControllerSourceType.Camera)
// dispose = d => File.Delete (path);
//
// return new MediaFile (path, () => File.OpenRead (path), dispose: dispose);
}
CLLocationManager _locationManager;
TaskCompletionSource<CLLocation> _locationTCS;
private async Task<NSDictionary> BuildGPSDataAsync()
{
// setup the location manager
if (_locationManager == null)
{
_locationManager = new CLLocationManager();
if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
_locationManager.RequestWhenInUseAuthorization();
_locationManager.DesiredAccuracy = 1; // in meters
}
// setup a task for getting the current location and a callback for receiving the location
_locationTCS = new TaskCompletionSource<CLLocation>();
_locationManager.LocationsUpdated += (sender, locationArgs) =>
{
if (locationArgs.Locations.Length > 0)
{
_locationManager.StopUpdatingLocation();
_locationTCS.SetResult(locationArgs.Locations[locationArgs.Locations.Length - 1]);
}
};
// start location monitoring
_locationManager.StartUpdatingLocation();
// create a timeout and location task to ensure we don't wait forever
var timeoutTask = System.Threading.Tasks.Task.Delay(5000); // 5 second wait
var locationTask = _locationTCS.Task;
// try and set a location based on whatever task ends first
CLLocation location;
var completeTask = await System.Threading.Tasks.Task.WhenAny(locationTask, timeoutTask);
if (completeTask == locationTask && completeTask.Status == TaskStatus.RanToCompletion)
{
// use the location result
location = locationTask.Result;
}
else
{
// timeout - stop the location manager and try and use the last location
_locationManager.StopUpdatingLocation();
location = _locationManager.Location;
}
if (location == null)
return null;
var gpsData = new NSDictionary(
ImageIO.CGImageProperties.GPSLatitude, Math.Abs(location.Coordinate.Latitude),
ImageIO.CGImageProperties.GPSLatitudeRef, (location.Coordinate.Latitude >= 0) ? "N" : "S",
ImageIO.CGImageProperties.GPSLongitude, Math.Abs(location.Coordinate.Longitude),
ImageIO.CGImageProperties.GPSLongitudeRef, (location.Coordinate.Longitude >= 0) ? "E" : "W",
ImageIO.CGImageProperties.GPSAltitude, Math.Abs(location.Altitude),
ImageIO.CGImageProperties.GPSDateStamp, DateTime.UtcNow.ToString("yyyy:MM:dd"),
ImageIO.CGImageProperties.GPSTimeStamp, DateTime.UtcNow.ToString("HH:mm:ss.ff")
);
return gpsData;
}
private MediaFile GetMovieMediaFile (NSDictionary info)
{
NSUrl url = (NSUrl)info[UIImagePickerController.MediaURL];
string name = this.options.Name ?? Path.GetFileName(url.Path);
string path = GetOutputPath(MediaImplementation.TypeMovie,
options.Directory ?? ((IsCaptured) ? String.Empty : "temp"),
this.options.Name ?? Path.GetFileName (url.Path));
File.Move (url.Path, path);
Action<bool> dispose = null;
if (this.source != UIImagePickerControllerSourceType.Camera)
dispose = d => File.Delete (path);
return new MediaFile (name, path, () => File.OpenRead (path), dispose: dispose);
}
private static string GetUniquePath (string type, string path, string name)
{
bool isPhoto = (type == MediaImplementation.TypeImage);
string ext = Path.GetExtension (name);
if (ext == String.Empty)
ext = ((isPhoto) ? ".jpg" : ".mp4");
name = Path.GetFileNameWithoutExtension (name);
string nname = name + ext;
int i = 1;
while (File.Exists (Path.Combine (path, nname)))
nname = name + "_" + (i++) + ext;
return Path.Combine (path, nname);
}
private static string GetOutputPath (string type, string path, string name)
{
path = Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.Personal), path);
Directory.CreateDirectory (path);
if (String.IsNullOrWhiteSpace (name))
{
string timestamp = DateTime.Now.ToString ("yyyMMdd_HHmmss");
if (type == MediaImplementation.TypeImage)
name = "IMG_" + timestamp + ".jpg";
else
name = "VID_" + timestamp + ".mp4";
}
return Path.Combine (path, GetUniquePath (type, path, name));
}
private static bool IsValidInterfaceOrientation (UIDeviceOrientation self)
{
return (self != UIDeviceOrientation.FaceUp && self != UIDeviceOrientation.FaceDown && self != UIDeviceOrientation.Unknown);
}
private static bool IsSameOrientationKind (UIDeviceOrientation o1, UIDeviceOrientation o2)
{
if (o1 == UIDeviceOrientation.FaceDown || o1 == UIDeviceOrientation.FaceUp)
return (o2 == UIDeviceOrientation.FaceDown || o2 == UIDeviceOrientation.FaceUp);
if (o1 == UIDeviceOrientation.LandscapeLeft || o1 == UIDeviceOrientation.LandscapeRight)
return (o2 == UIDeviceOrientation.LandscapeLeft || o2 == UIDeviceOrientation.LandscapeRight);
if (o1 == UIDeviceOrientation.Portrait || o1 == UIDeviceOrientation.PortraitUpsideDown)
return (o2 == UIDeviceOrientation.Portrait || o2 == UIDeviceOrientation.PortraitUpsideDown);
return false;
}
private static UIDeviceOrientation GetDeviceOrientation (UIInterfaceOrientation self)
{
switch (self)
{
case UIInterfaceOrientation.LandscapeLeft:
return UIDeviceOrientation.LandscapeLeft;
case UIInterfaceOrientation.LandscapeRight:
return UIDeviceOrientation.LandscapeRight;
case UIInterfaceOrientation.Portrait:
return UIDeviceOrientation.Portrait;
case UIInterfaceOrientation.PortraitUpsideDown:
return UIDeviceOrientation.PortraitUpsideDown;
default:
throw new InvalidOperationException();
}
}
}
}
| |
#pragma warning disable 1634, 1691
namespace System.Workflow.ComponentModel.Design
{
using System;
using System.IO;
using System.Drawing;
using System.CodeDom;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Windows.Forms;
using System.ComponentModel;
using System.Globalization;
using System.Drawing.Design;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Windows.Forms.Design;
using System.ComponentModel.Design;
using System.Collections.Specialized;
using System.ComponentModel.Design.Serialization;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Serialization;
using System.Collections.ObjectModel;
using System.Reflection;
using System.Workflow.ComponentModel.Design;
using System.Runtime.Serialization.Formatters.Binary;
//
#region CompositeActivityDesigner Class
/// <summary>
/// CompositeActivityDesigner provides a designer which allows user to visually design composite activities in the design mode.
/// CompositeActivityDesigner enables the user to customize layouting, drawing associated with the CompositeActivity, it also allows
/// managing the layouting, drawing and eventing for the contained activity designers.
/// </summary>
[ActivityDesignerTheme(typeof(CompositeDesignerTheme))]
[SRCategory("CompositeActivityDesigners", "System.Workflow.ComponentModel.Design.DesignerResources")]
[DesignerSerializer(typeof(CompositeActivityDesignerLayoutSerializer), typeof(WorkflowMarkupSerializer))]
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public abstract class CompositeActivityDesigner : ActivityDesigner
{
#region Fields
private const string CF_DESIGNER = "CF_WINOEDESIGNERCOMPONENTS";
private const string CF_DESIGNERSTATE = "CF_WINOEDESIGNERCOMPONENTSSTATE";
private const int MaximumCharsPerLine = 8;
private const int MaximumTextLines = 1;
private Size actualTextSize = Size.Empty;
private CompositeDesignerAccessibleObject accessibilityObject;
private List<ActivityDesigner> containedActivityDesigners;
private bool expanded = true;
#endregion
#region Construction / Destruction
/// <summary>
/// Default constructor for CompositeActivityDesigner
/// </summary>
protected CompositeActivityDesigner()
{
}
#endregion
#region Properties
#region Public Properties
/// <summary>
/// Gets if the activity associated with designer is structurally locked that is no activities can be added to it.
/// </summary>
public bool IsEditable
{
get
{
if (!(Activity is CompositeActivity))
return false;
if (IsLocked)
return false;
if (Helpers.IsCustomActivity(Activity as CompositeActivity))
return false;
return true;
}
}
/// <summary>
/// Gets if the designer can be collapsed, collapsed designer has expand/collapse button added to it
/// </summary>
public virtual bool CanExpandCollapse
{
get
{
return !IsRootDesigner;
}
}
/// <summary>
/// Gets or Sets if the designer currently in expanded state
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual bool Expanded
{
get
{
if (!CanExpandCollapse && !this.expanded)
Expanded = true;
return this.expanded;
}
set
{
if (this.expanded == value)
return;
//If the designer can not expand or collapse then we need to make sure that
//user does not collapse it
if (!CanExpandCollapse && !value)
return;
this.expanded = value;
PerformLayout();
}
}
/// <summary>
/// Gets the array of activity designer contained within.
/// </summary>
public virtual ReadOnlyCollection<ActivityDesigner> ContainedDesigners
{
get
{
List<ActivityDesigner> designers = new List<ActivityDesigner>();
CompositeActivity compositeActivity = Activity as CompositeActivity;
if (compositeActivity != null)
{
if (this.containedActivityDesigners == null)
{
bool foundAllDesigners = true;
//In certain cases users might try to access the activity designers
//in Initialize method of composite activity. In that case the child activities
//might not be inserted in the container. If this happens then we might not get the
//designer of the contained activity. When such a case happens we should not buffer the
//designers as it might lead to erroneous results
foreach (Activity activity in compositeActivity.Activities)
{
ActivityDesigner activityDesigner = ActivityDesigner.GetDesigner(activity);
if (activityDesigner != null)
designers.Add(activityDesigner);
else
foundAllDesigners = false;
}
if (foundAllDesigners)
this.containedActivityDesigners = designers;
}
else
{
designers = this.containedActivityDesigners;
}
}
return designers.AsReadOnly();
}
}
/// <summary>
/// Gets the first selectable object in the navigation order.
/// </summary>
public virtual object FirstSelectableObject
{
get
{
return null;
}
}
/// <summary>
/// Gets the last selected object in the navigation order
/// </summary>
public virtual object LastSelectableObject
{
get
{
return null;
}
}
public override AccessibleObject AccessibilityObject
{
get
{
if (this.accessibilityObject == null)
this.accessibilityObject = new CompositeDesignerAccessibleObject(this);
return this.accessibilityObject;
}
}
public override Point Location
{
get
{
return base.Location;
}
set
{
///If designers's location changes then we need to change location of children
if (base.Location == value)
return;
Size moveDelta = new Size(value.X - base.Location.X, value.Y - base.Location.Y);
foreach (ActivityDesigner activityDesigner in ContainedDesigners)
activityDesigner.Location = new Point(activityDesigner.Location.X + moveDelta.Width, activityDesigner.Location.Y + moveDelta.Height);
base.Location = value;
}
}
#endregion
#region Protected Properties
/// <summary>
/// Gets the rectangle associated with expand/collapse button
/// </summary>
protected virtual Rectangle ExpandButtonRectangle
{
get
{
if (!CanExpandCollapse)
return Rectangle.Empty;
CompositeDesignerTheme designerTheme = DesignerTheme as CompositeDesignerTheme;
if (designerTheme == null)
return Rectangle.Empty;
Size textSize = TextRectangle.Size;
Size imageSize = (Image != null) ? designerTheme.ImageSize : Size.Empty;
Rectangle bounds = Bounds;
Size anchorSize = (!textSize.IsEmpty) ? textSize : imageSize;
Rectangle expandButtonRectangle = new Rectangle(bounds.Location, designerTheme.ExpandButtonSize);
expandButtonRectangle.X += (bounds.Width - ((3 * designerTheme.ExpandButtonSize.Width / 2) + anchorSize.Width)) / 2;
expandButtonRectangle.Y += 2 * WorkflowTheme.CurrentTheme.AmbientTheme.Margin.Height;
if (anchorSize.Height > expandButtonRectangle.Height)
expandButtonRectangle.Y += (anchorSize.Height - expandButtonRectangle.Height) / 2;
return expandButtonRectangle;
}
}
/// <summary>
/// Gets the height for the title area of the designer, typically this can contain the heading, icon and expand/collapse button
/// </summary>
protected virtual int TitleHeight
{
get
{
Size margin = WorkflowTheme.CurrentTheme.AmbientTheme.Margin;
Rectangle expandButtonRectangle = ExpandButtonRectangle;
Rectangle textRectangle = TextRectangle;
Rectangle imageRectangle = ImageRectangle;
int titleHeight = 0;
if (!textRectangle.Size.IsEmpty)
{
titleHeight = Math.Max(expandButtonRectangle.Height, textRectangle.Height);
titleHeight += imageRectangle.Height;
}
else
{
titleHeight = Math.Max(expandButtonRectangle.Height, imageRectangle.Height);
}
if (!expandButtonRectangle.Size.IsEmpty || !textRectangle.Size.IsEmpty || !imageRectangle.Size.IsEmpty)
titleHeight += (Expanded ? 2 : 3) * margin.Height;
if (!imageRectangle.Size.IsEmpty && !textRectangle.Size.IsEmpty)
titleHeight += margin.Height;
return titleHeight;
}
}
protected override Rectangle ImageRectangle
{
get
{
if (Image == null)
return Rectangle.Empty;
CompositeDesignerTheme designerTheme = DesignerTheme as CompositeDesignerTheme;
if (designerTheme == null)
return Rectangle.Empty;
Rectangle bounds = Bounds;
Size expandButtonSize = ExpandButtonRectangle.Size;
Size imageSize = designerTheme.ImageSize;
Size textSize = TextRectangle.Size;
Size margin = WorkflowTheme.CurrentTheme.AmbientTheme.Margin;
Rectangle imageRectangle = new Rectangle(bounds.Location, imageSize);
if (textSize.Width > 0)
{
imageRectangle.X += (bounds.Width - imageSize.Width) / 2;
}
else
{
imageRectangle.X += (bounds.Width - (imageSize.Width + 3 * expandButtonSize.Width / 2)) / 2;
imageRectangle.X += 3 * expandButtonSize.Width / 2;
}
imageRectangle.Y += 2 * margin.Height;
if (textSize.Height > 0)
imageRectangle.Y += textSize.Height + margin.Height;
return imageRectangle;
}
}
protected override Rectangle TextRectangle
{
get
{
if (String.IsNullOrEmpty(Text))
return Rectangle.Empty;
CompositeDesignerTheme designerTheme = DesignerTheme as CompositeDesignerTheme;
if (designerTheme == null)
return Rectangle.Empty;
Rectangle bounds = Bounds;
Size margin = WorkflowTheme.CurrentTheme.AmbientTheme.Margin;
Size expandButtonSize = (CanExpandCollapse) ? designerTheme.ExpandButtonSize : Size.Empty;
//Calculate the text size
int maxAvailableWidth = bounds.Width - (2 * margin.Width + 3 * expandButtonSize.Width / 2);
Size requestedLineSize = this.actualTextSize;
requestedLineSize.Width /= Text.Length;
requestedLineSize.Width += ((requestedLineSize.Width % Text.Length) > 0) ? 1 : 0;
requestedLineSize.Width *= Math.Min(Text.Length, CompositeActivityDesigner.MaximumCharsPerLine - 1);
Size textSize = Size.Empty;
textSize.Width = Math.Min(maxAvailableWidth, this.actualTextSize.Width);
textSize.Width = Math.Max(1, Math.Max(textSize.Width, requestedLineSize.Width));
textSize.Height = requestedLineSize.Height;
int textLines = this.actualTextSize.Width / textSize.Width;
textLines += ((this.actualTextSize.Width % textSize.Width) > 0) ? 1 : 0;
textLines = Math.Min(textLines, CompositeActivityDesigner.MaximumTextLines);
textSize.Height *= textLines;
//Calculate the text rectangle
Rectangle textRectangle = new Rectangle(bounds.Location, textSize);
textRectangle.X += (bounds.Width - (3 * expandButtonSize.Width / 2 + textSize.Width)) / 2;
textRectangle.X += 3 * expandButtonSize.Width / 2;
textRectangle.Y += 2 * margin.Height;
if (expandButtonSize.Height > textSize.Height)
textRectangle.Y += (expandButtonSize.Height - textSize.Height) / 2;
textRectangle.Size = textSize;
return textRectangle;
}
}
protected internal override ActivityDesignerGlyphCollection Glyphs
{
get
{
ActivityDesignerGlyphCollection glyphs = new ActivityDesignerGlyphCollection();
glyphs.AddRange(base.Glyphs);
CompositeDesignerTheme compositeTheme = DesignerTheme as CompositeDesignerTheme;
if (compositeTheme != null && compositeTheme.ShowDropShadow)
glyphs.Add(ShadowGlyph.Default);
return glyphs;
}
}
#endregion
#region Private Properties
#region Properties used during serialization only
//NOTE THAT THIS WILL ONLY BE USED FOR SERIALIZATION PURPOSES
[EditorBrowsable(EditorBrowsableState.Never)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
internal List<ActivityDesigner> Designers
{
get
{
List<ActivityDesigner> childDesigners = new List<ActivityDesigner>();
CompositeActivity compositeActivity = Activity as CompositeActivity;
IDesignerHost host = GetService(typeof(IDesignerHost)) as IDesignerHost;
if (host != null && compositeActivity != null)
{
foreach (Activity childActivity in compositeActivity.Activities)
{
ActivityDesigner designer = host.GetDesigner(childActivity) as ActivityDesigner;
if (designer != null)
childDesigners.Add(designer);
}
}
return childDesigners;
}
}
#endregion
#endregion
#endregion
#region Methods
#region Public Static Methods
/// <summary>
/// Inserts activities in specified composite activity designer by creating transaction
/// </summary>
/// <param name="compositeActivityDesigner">Designer in which to insert the activities</param>
/// <param name="insertLocation">Insertion location</param>
/// <param name="activitiesToInsert">Array of activities to insert</param>
/// <param name="undoTransactionDescription">Text for the designer transaction which will be created</param>
public static void InsertActivities(CompositeActivityDesigner compositeActivityDesigner, HitTestInfo insertLocation, ReadOnlyCollection<Activity> activitiesToInsert, string undoTransactionDescription)
{
if (compositeActivityDesigner == null)
throw new ArgumentNullException("compositeActivityDesigner");
if (compositeActivityDesigner.Activity == null ||
compositeActivityDesigner.Activity.Site == null ||
!(compositeActivityDesigner.Activity is CompositeActivity))
throw new ArgumentException("compositeActivityDesigner");
if (insertLocation == null)
throw new ArgumentNullException("insertLocation");
if (activitiesToInsert == null)
throw new ArgumentNullException("activitiesToInsert");
ISite site = compositeActivityDesigner.Activity.Site;
// now insert the actual activities
IDesignerHost designerHost = site.GetService(typeof(IDesignerHost)) as IDesignerHost;
DesignerTransaction trans = null;
if (designerHost != null && !string.IsNullOrEmpty(undoTransactionDescription))
trans = designerHost.CreateTransaction(undoTransactionDescription);
bool moveCase = false;
try
{
//Detect if the activities are being moved or inserted
foreach (Activity activity in activitiesToInsert)
{
if (activity == null)
throw new ArgumentException("activitiesToInsert", SR.GetString(SR.Error_CollectionHasNullEntry));
moveCase = ((IComponent)activity).Site != null;
break;
}
//We purposely create a new instance of activities list so that we do not modify the original one
if (moveCase)
compositeActivityDesigner.MoveActivities(insertLocation, activitiesToInsert);
else
compositeActivityDesigner.InsertActivities(insertLocation, activitiesToInsert);
if (trans != null)
trans.Commit();
}
catch (Exception e)
{
if (trans != null)
trans.Cancel();
throw e;
}
//If we are just moving the activities then we do not need to emit the class
//for scopes; only when we are adding the activities the class needs to be emitted for
//scope in code beside file
if (!moveCase)
{
// if everything was successful then generate classes correposnding to new scopes
// get all the activities underneath the child activities
ArrayList allActivities = new ArrayList();
foreach (Activity activity in activitiesToInsert)
{
allActivities.Add(activity);
if (activity is CompositeActivity)
allActivities.AddRange(Helpers.GetNestedActivities((CompositeActivity)activity));
}
}
}
/// <summary>
/// Removes activities from designer by creating designer transaction
/// </summary>
/// <param name="serviceProvider">Service Provider associated to providing services</param>
/// <param name="activitiesToRemove">Array of activities to remove</param>
/// <param name="transactionDescription">Transaction text used to name the designer transaction</param>
public static void RemoveActivities(IServiceProvider serviceProvider, ReadOnlyCollection<Activity> activitiesToRemove, string transactionDescription)
{
if (serviceProvider == null)
throw new ArgumentNullException();
if (activitiesToRemove == null)
throw new ArgumentNullException("activitiesToRemove");
Activity nextSelectableActivity = null;
IDesignerHost designerHost = serviceProvider.GetService(typeof(IDesignerHost)) as IDesignerHost;
DesignerTransaction trans = null;
if (designerHost != null && !string.IsNullOrEmpty(transactionDescription))
trans = designerHost.CreateTransaction(transactionDescription);
try
{
foreach (Activity activity in activitiesToRemove)
{
ActivityDesigner designer = ActivityDesigner.GetDesigner(activity);
if (designer != null)
{
CompositeActivityDesigner parentDesigner = designer.ParentDesigner;
if (parentDesigner != null)
{
nextSelectableActivity = DesignerHelpers.GetNextSelectableActivity(activity);
parentDesigner.RemoveActivities(new List<Activity>(new Activity[] { activity }).AsReadOnly());
}
}
}
if (trans != null)
trans.Commit();
}
catch
{
if (trans != null)
trans.Cancel();
throw;
}
if (nextSelectableActivity != null && nextSelectableActivity.Site != null)
{
ISelectionService selectionService = nextSelectableActivity.Site.GetService(typeof(ISelectionService)) as ISelectionService;
if (selectionService != null)
selectionService.SetSelectedComponents(new Activity[] { nextSelectableActivity }, SelectionTypes.Replace);
}
}
public static IDataObject SerializeActivitiesToDataObject(IServiceProvider serviceProvider, Activity[] activities)
{
if (serviceProvider == null)
throw new ArgumentNullException("serviceProvider");
if (activities == null)
throw new ArgumentNullException("activities");
// get component serialization service
ComponentSerializationService css = (ComponentSerializationService)serviceProvider.GetService(typeof(ComponentSerializationService));
if (css == null)
throw new InvalidOperationException(SR.GetString(SR.General_MissingService, typeof(ComponentSerializationService).Name));
// serialize all activities to the store
SerializationStore store = css.CreateStore();
using (store)
{
foreach (Activity activity in activities)
css.Serialize(store, activity);
}
// wrap it with clipboard style object
Stream stream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, store);
stream.Seek(0, SeekOrigin.Begin);
DataObject dataObject = new DataObject(CF_DESIGNER, stream);
dataObject.SetData(CF_DESIGNERSTATE, Helpers.SerializeDesignersToStream(activities));
return dataObject;
}
public static Activity[] DeserializeActivitiesFromDataObject(IServiceProvider serviceProvider, IDataObject dataObj)
{
return DeserializeActivitiesFromDataObject(serviceProvider, dataObj, false);
}
internal static Activity[] DeserializeActivitiesFromDataObject(IServiceProvider serviceProvider, IDataObject dataObj, bool addAssemblyReference)
{
if (serviceProvider == null)
throw new ArgumentNullException("serviceProvider");
if (dataObj == null)
return new Activity[] { };
IDesignerHost designerHost = (IDesignerHost)serviceProvider.GetService(typeof(IDesignerHost));
if (designerHost == null)
throw new InvalidOperationException(SR.GetString(SR.General_MissingService, typeof(IDesignerHost).Name));
object data = dataObj.GetData(CF_DESIGNER);
ICollection activities = null;
if (data is Stream)
{
BinaryFormatter formatter = new BinaryFormatter();
((Stream)data).Seek(0, SeekOrigin.Begin);
object serializationData = formatter.Deserialize((Stream)data);
if (serializationData is SerializationStore)
{
// get component serialization service
ComponentSerializationService css = serviceProvider.GetService(typeof(ComponentSerializationService)) as ComponentSerializationService;
if (css == null)
throw new Exception(SR.GetString(SR.General_MissingService, typeof(ComponentSerializationService).Name));
// deserialize data
activities = css.Deserialize((SerializationStore)serializationData);
}
}
else
{
// Now check for a toolbox item.
IToolboxService ts = (IToolboxService)serviceProvider.GetService(typeof(IToolboxService));
if (ts != null && ts.IsSupported(dataObj, designerHost))
{
ToolboxItem toolBoxItem = ts.DeserializeToolboxItem(dataObj, designerHost);
if (toolBoxItem != null)
{
activities = GetActivitiesFromToolboxItem(serviceProvider, addAssemblyReference, designerHost, activities, toolBoxItem);
}
}
}
if (activities != null && Helpers.AreAllActivities(activities))
return (Activity[])new ArrayList(activities).ToArray(typeof(Activity));
else
return new Activity[] { };
}
private static ICollection GetActivitiesFromToolboxItem(IServiceProvider serviceProvider, bool addAssemblyReference, IDesignerHost designerHost, ICollection activities, ToolboxItem toolBoxItem)
{
// this will make sure that we add the assembly reference to project
if (addAssemblyReference && toolBoxItem.AssemblyName != null)
{
ITypeResolutionService trs = serviceProvider.GetService(typeof(ITypeResolutionService)) as ITypeResolutionService;
if (trs != null)
trs.ReferenceAssembly(toolBoxItem.AssemblyName);
}
ActivityToolboxItem ActivityToolboxItem = toolBoxItem as ActivityToolboxItem;
if (addAssemblyReference && ActivityToolboxItem != null)
activities = ActivityToolboxItem.CreateComponentsWithUI(designerHost);
else
activities = toolBoxItem.CreateComponents(designerHost);
return activities;
}
internal static Activity[] DeserializeActivitiesFromToolboxItem(IServiceProvider serviceProvider, ToolboxItem toolboxItem, bool addAssemblyReference)
{
if (serviceProvider == null)
throw new ArgumentNullException("serviceProvider");
IDesignerHost designerHost = (IDesignerHost)serviceProvider.GetService(typeof(IDesignerHost));
if (designerHost == null)
throw new InvalidOperationException(SR.GetString(SR.General_MissingService, typeof(IDesignerHost).Name));
ICollection activities = null;
if (toolboxItem != null)
{
activities = GetActivitiesFromToolboxItem(serviceProvider, addAssemblyReference, designerHost, activities, toolboxItem);
}
if (activities != null && Helpers.AreAllActivities(activities))
return (Activity[])new ArrayList(activities).ToArray(typeof(Activity));
else
return new Activity[] { };
}
public static ActivityDesigner[] GetIntersectingDesigners(ActivityDesigner topLevelDesigner, Rectangle rectangle)
{
if (topLevelDesigner == null)
throw new ArgumentNullException("topLevelDesigner");
List<ActivityDesigner> intersectingDesigners = new List<ActivityDesigner>();
if (!rectangle.IntersectsWith(topLevelDesigner.Bounds))
return intersectingDesigners.ToArray();
if (!topLevelDesigner.Bounds.Contains(rectangle))
intersectingDesigners.Add(topLevelDesigner);
if (topLevelDesigner is CompositeActivityDesigner)
{
Queue compositeDesigners = new Queue();
compositeDesigners.Enqueue(topLevelDesigner);
while (compositeDesigners.Count > 0)
{
CompositeActivityDesigner compositeDesigner = compositeDesigners.Dequeue() as CompositeActivityDesigner;
if (compositeDesigner != null)
{
bool bDrawingVisibleChildren = false;
foreach (ActivityDesigner activityDesigner in compositeDesigner.ContainedDesigners)
{
if (activityDesigner.IsVisible && rectangle.IntersectsWith(activityDesigner.Bounds))
{
bDrawingVisibleChildren = true;
if (!activityDesigner.Bounds.Contains(rectangle))
intersectingDesigners.Add(activityDesigner);
if (activityDesigner is CompositeActivityDesigner)
compositeDesigners.Enqueue(activityDesigner);
}
else
{
if ((!(compositeDesigner is FreeformActivityDesigner)) && bDrawingVisibleChildren)
break;
}
}
}
}
}
return intersectingDesigners.ToArray();
}
#endregion
#region Public Methods
/// <summary>
/// Checks if the activities can be inserted into the composite activity associated with the designer
/// </summary>
/// <param name="insertLocation">Location at which to insert activities</param>
/// <param name="activitiesToInsert">Array of activities to be inserted</param>
/// <returns>True of activities can be inserted, false otherwise</returns>
public virtual bool CanInsertActivities(HitTestInfo insertLocation, ReadOnlyCollection<Activity> activitiesToInsert)
{
if (insertLocation == null)
throw new ArgumentNullException("insertLocation");
if (activitiesToInsert == null)
throw new ArgumentNullException("activitiesToInsert");
CompositeActivity compositeActivity = Activity as CompositeActivity;
if (compositeActivity == null)
return false;
//If the activity state is locked then we can not insert activities.
if (!IsEditable)
return false;
IExtendedUIService2 extendedUIService = this.GetService(typeof(IExtendedUIService2)) as IExtendedUIService2;
foreach (Activity activity in activitiesToInsert)
{
if (activity == null)
throw new ArgumentException("activitiesToInsert", SR.GetString(SR.Error_CollectionHasNullEntry));
if (extendedUIService != null)
{
if (!extendedUIService.IsSupportedType(activity.GetType()))
{
return false;
}
}
if (activity is CompositeActivity && Helpers.IsAlternateFlowActivity(activity))
return false;
ActivityDesigner designerToInsert = null;
#pragma warning disable 56506//bug in presharp, activity has already been checked for null value
if (activity.Site != null)
{
//get an existing designer
IDesignerHost designerHost = activity.Site.GetService(typeof(IDesignerHost)) as IDesignerHost;
designerToInsert = (designerHost != null) ? designerHost.GetDesigner((IComponent)activity) as ActivityDesigner : null;
}
else
{
//we dont want to create a designer instance every time, so we'll cache it
//this is a fix for a perf issue - this function gets called in a loop when doing drag'n'drop operation
//from a toolbox
if (activity.UserData.Contains(typeof(ActivityDesigner)))
{
designerToInsert = activity.UserData[typeof(ActivityDesigner)] as ActivityDesigner;
}
else
{
//create a new one
designerToInsert = ActivityDesigner.CreateDesigner(Activity.Site, activity);
activity.UserData[typeof(ActivityDesigner)] = designerToInsert;
}
}
#pragma warning restore 56506//bug in presharp
if (designerToInsert == null)
return false;
if (!designerToInsert.CanBeParentedTo(this))
return false;
}
return true;
}
/// <summary>
/// Inserts activity at specified location within designer
/// </summary>
/// <param name="insertLocation">Location at which to insert activities</param>
/// <param name="activitiesToInsert">Array of activities to insert</param>
public virtual void InsertActivities(HitTestInfo insertLocation, ReadOnlyCollection<Activity> activitiesToInsert)
{
if (insertLocation == null)
throw new ArgumentNullException("insertLocation");
if (activitiesToInsert == null)
throw new ArgumentNullException("activitiesToInsert");
CompositeActivity compositeActivity = Activity as CompositeActivity;
if (compositeActivity == null)
throw new Exception(SR.GetString(SR.Error_DragDropInvalid));
int index = insertLocation.MapToIndex();
IIdentifierCreationService identifierCreationService = GetService(typeof(IIdentifierCreationService)) as IIdentifierCreationService;
if (identifierCreationService != null)
identifierCreationService.EnsureUniqueIdentifiers(compositeActivity, activitiesToInsert);
else
throw new InvalidOperationException(SR.GetString(SR.General_MissingService, typeof(IIdentifierCreationService).FullName));
foreach (Activity activity in activitiesToInsert)
{
if (activity == null)
throw new ArgumentException("activitiesToInsert", SR.GetString(SR.Error_CollectionHasNullEntry));
if (activity.Parent == null)
{
compositeActivity.Activities.Insert(index++, activity);
WorkflowDesignerLoader.AddActivityToDesigner(Activity.Site, activity);
}
}
// filter out unsupported Dependency properties
foreach (Activity activity in activitiesToInsert)
{
Walker walker = new Walker();
walker.FoundActivity += delegate(Walker w, WalkerEventArgs walkerEventArgs)
{
ExtenderHelpers.FilterDependencyProperties(this.Activity.Site, walkerEventArgs.CurrentActivity);
};
walker.Walk(activity);
}
}
/// <summary>
/// Checks if the activities can be moved out from the composite activity associated with designer
/// </summary>
/// <param name="moveLocation">Location from which to move the activities</param>
/// <param name="activitiesToMove">Array of activities to move</param>
/// <returns></returns>
public virtual bool CanMoveActivities(HitTestInfo moveLocation, ReadOnlyCollection<Activity> activitiesToMove)
{
if (moveLocation == null)
throw new ArgumentNullException("moveLocation");
if (activitiesToMove == null)
throw new ArgumentNullException("activitiesToMove");
//If the activity has locked structure then we do not allow user to move the activity out
if (!IsEditable)
return false;
//Now go through all the movable activities and check if their position is locked
foreach (Activity activity in activitiesToMove)
{
ActivityDesigner designer = ActivityDesigner.GetDesigner(activity);
if (designer == null || designer.IsLocked)
return false;
}
return true;
}
/// <summary>
/// Moves activities from one designer to other
/// </summary>
/// <param name="moveLocation">Location at which to move the activities</param>
/// <param name="activitiesToMove">Array of activities to move</param>
public virtual void MoveActivities(HitTestInfo moveLocation, ReadOnlyCollection<Activity> activitiesToMove)
{
if (moveLocation == null)
throw new ArgumentNullException("moveLocation");
if (activitiesToMove == null)
throw new ArgumentNullException("activitiesToMove");
//Make sure that we get the composite activity
CompositeActivity compositeActivity = Activity as CompositeActivity;
if (compositeActivity == null)
throw new Exception(SR.GetString(SR.Error_DragDropInvalid));
IIdentifierCreationService identifierCreationService = GetService(typeof(IIdentifierCreationService)) as IIdentifierCreationService;
if (identifierCreationService == null)
throw new InvalidOperationException(SR.GetString(SR.General_MissingService, typeof(IIdentifierCreationService).FullName));
IDesignerHost designerHost = GetService(typeof(IDesignerHost)) as IDesignerHost;
if (designerHost == null)
throw new InvalidOperationException(SR.GetString(SR.General_MissingService, typeof(IDesignerHost).FullName));
int index = moveLocation.MapToIndex();
foreach (Activity activity in activitiesToMove)
{
ActivityDesigner designer = ActivityDesigner.GetDesigner(activity);
if (designer != null)
{
CompositeActivityDesigner parentDesigner = designer.ParentDesigner;
if (parentDesigner == this)
{
int originalIndex = compositeActivity.Activities.IndexOf(activity);
if (index > originalIndex)
index--;
}
}
//In some cases we might get activities which are added newly, in such cases we check if the activity
//is existing activity or new one based on this decision we add it to the designer host.
Debug.Assert(activity.Parent != null);
CompositeActivity parentActivity = activity.Parent;
int positionInParent = parentActivity.Activities.IndexOf(activity);
activity.Parent.Activities.Remove(activity);
//We need to make sure that the activity is going to have unique identifier
//This might just cause problems
identifierCreationService.EnsureUniqueIdentifiers(compositeActivity, new Activity[] { activity });
//We do not need to read the activity in the designer host as this is move operation
//assign unique temporary name to avoid conflicts
DesignerHelpers.UpdateSiteName(activity, "_activityonthemove_");
CompositeActivity compositeActivityMoved = activity as CompositeActivity;
if (compositeActivityMoved != null)
{
int i = 1;
foreach (Activity nestedActivity in Helpers.GetNestedActivities(compositeActivityMoved))
{
DesignerHelpers.UpdateSiteName(nestedActivity, "_activityonthemove_" + i.ToString(CultureInfo.InvariantCulture));
i += 1;
}
}
try
{
compositeActivity.Activities.Insert(index++, activity);
}
catch (Exception ex)
{
// reconnect the activity
parentActivity.Activities.Insert(positionInParent, activity);
//
throw ex;
}
DesignerHelpers.UpdateSiteName(activity, activity.Name);
if (compositeActivityMoved != null)
{
foreach (Activity nestedActivity in Helpers.GetNestedActivities(compositeActivityMoved))
DesignerHelpers.UpdateSiteName(nestedActivity, nestedActivity.Name);
}
}
// filter out unsupported Dependency properties and refresh propertyDescriptors
foreach (Activity activity in activitiesToMove)
{
Walker walker = new Walker();
walker.FoundActivity += delegate(Walker w, WalkerEventArgs walkerEventArgs)
{
ExtenderHelpers.FilterDependencyProperties(this.Activity.Site, walkerEventArgs.CurrentActivity);
TypeDescriptor.Refresh(walkerEventArgs.CurrentActivity);
};
walker.Walk(activity);
}
}
/// <summary>
/// Checks if activities can be removed from the activity associated with the designer
/// </summary>
/// <param name="activitiesToRemove">Array of activities to remove</param>
/// <returns>True of the activities can be removed, False otherwise.</returns>
public virtual bool CanRemoveActivities(ReadOnlyCollection<Activity> activitiesToRemove)
{
if (activitiesToRemove == null)
throw new ArgumentNullException("activitiesToRemove");
if (!IsEditable)
return false;
foreach (Activity activity in activitiesToRemove)
{
ActivityDesigner designer = ActivityDesigner.GetDesigner(activity);
if (designer == null || designer.IsLocked)
return false;
}
return true;
}
/// <summary>
/// Removes activities from composite activity associated with the designer
/// </summary>
/// <param name="activitiesToRemove">Array of activities to remove</param>
public virtual void RemoveActivities(ReadOnlyCollection<Activity> activitiesToRemove)
{
if (activitiesToRemove == null)
throw new ArgumentNullException("activitiesToRemove");
CompositeActivity compositeActivity = Activity as CompositeActivity;
if (compositeActivity == null)
throw new Exception(SR.GetString(SR.Error_DragDropInvalid));
foreach (Activity activity in activitiesToRemove)
{
compositeActivity.Activities.Remove(activity);
//Before we destroy the activity make sure that the references it and its child activities store to its parent
//are set to null or else an undo unit will be created
//For details look at,
//\\cpvsbuild\drops\whidbey\pd6\raw\40903.19\sources\ndp\fx\src\Designer\Host\UndoEngine.cs
//OnComponentRemoving function which retains the references we hold to the parent
//This bug can be reproed by deleting a compositeactivity from design surface and then doing an undo
//VSWhidbey #312230
activity.SetParent(null);
if (activity is CompositeActivity)
{
foreach (Activity nestedActivity in Helpers.GetNestedActivities(activity as CompositeActivity))
nestedActivity.SetParent(null);
}
WorkflowDesignerLoader.RemoveActivityFromDesigner(Activity.Site, activity);
}
}
/// <summary>
/// Checks if the contained designer is to be made visible
/// </summary>
/// <param name="containedDesigner">Contained designer to check for visibility</param>
/// <returns></returns>
public virtual bool IsContainedDesignerVisible(ActivityDesigner containedDesigner)
{
if (containedDesigner == null)
throw new ArgumentNullException("containedDesigner");
return true;
}
/// <summary>
/// Makes sure that the child designer will be made visible
/// </summary>
/// <param name="containedDesigner">Contained designer to make visible</param>
public virtual void EnsureVisibleContainedDesigner(ActivityDesigner containedDesigner)
{
if (containedDesigner == null)
throw new ArgumentNullException("containedDesigner");
Expanded = true;
}
/// <summary>
/// Gets the object which is next in the order of navigation
/// </summary>
/// <param name="current">Current object in the navigation order</param>
/// <param name="navigate">Navigation direction</param>
/// <returns></returns>
public virtual object GetNextSelectableObject(object current, DesignerNavigationDirection direction)
{
return null;
}
public override HitTestInfo HitTest(Point point)
{
HitTestInfo hitInfo = HitTestInfo.Nowhere;
if (ExpandButtonRectangle.Contains(point))
{
hitInfo = new HitTestInfo(this, HitTestLocations.Designer | HitTestLocations.ActionArea);
}
else if (Expanded && Bounds.Contains(point))
{
//First check if any of our children are hit.
ReadOnlyCollection<ActivityDesigner> containedDesigners = ContainedDesigners;
for (int i = containedDesigners.Count - 1; i >= 0; i--)
{
ActivityDesigner activityDesigner = containedDesigners[i] as ActivityDesigner;
if (activityDesigner != null && activityDesigner.IsVisible)
{
hitInfo = activityDesigner.HitTest(point);
if (hitInfo.HitLocation != HitTestLocations.None)
break;
}
}
}
//If no children are hit then call base class's hittest
if (hitInfo == HitTestInfo.Nowhere)
hitInfo = base.HitTest(point);
//This is to create default hittest info in case the drawing state is invalid
if (hitInfo.AssociatedDesigner != null && hitInfo.AssociatedDesigner.DrawingState != DrawingStates.Valid)
hitInfo = new HitTestInfo(hitInfo.AssociatedDesigner, HitTestLocations.Designer | HitTestLocations.ActionArea);
return hitInfo;
}
#endregion
#region Protected Methods
/// <summary>
/// Notifies that the activity associated with contained designer has changed.
/// </summary>
/// <param name="e">ActivityChangedEventArgs containing information about the change.</param>
protected virtual void OnContainedActivityChanged(ActivityChangedEventArgs e)
{
if (e == null)
throw new ArgumentNullException("e");
}
/// <summary>
/// Notifies that number of activities contained within the designers are changing
/// </summary>
/// <param name="listChangeArgs">ActivityCollectionChangeEventArgs containing information about what is about to change</param>
protected virtual void OnContainedActivitiesChanging(ActivityCollectionChangeEventArgs listChangeArgs)
{
if (listChangeArgs == null)
throw new ArgumentNullException("listChangeArgs");
}
/// <summary>
/// Notifies that number of activities contained within the designers have changed
/// </summary>
/// <param name="listChangeArgs">ItemListChangeEventArgs containing information about what has changed</param>
protected virtual void OnContainedActivitiesChanged(ActivityCollectionChangeEventArgs listChangeArgs)
{
if (listChangeArgs == null)
throw new ArgumentNullException("listChangeArgs");
// Update the status of all the designers
foreach (ActivityDesigner activityDesigner in ContainedDesigners)
{
foreach (DesignerVerb designerVerb in ((IDesigner)activityDesigner).Verbs)
{
int status = designerVerb.OleStatus;
status = 0;
}
}
RefreshDesignerVerbs();
//clear the list of activity designers (force to create the new list the next time it is requested)
this.containedActivityDesigners = null;
PerformLayout();
}
protected override void Initialize(Activity activity)
{
base.Initialize(activity);
///
CompositeActivity compositeActivity = activity as CompositeActivity;
if (compositeActivity != null)
{
compositeActivity.Activities.ListChanging += new EventHandler<ActivityCollectionChangeEventArgs>(OnActivityListChanging);
compositeActivity.Activities.ListChanged += new EventHandler<ActivityCollectionChangeEventArgs>(OnActivityListChanged);
}
if (IsRootDesigner)
{
IComponentChangeService componentChangeService = GetService(typeof(IComponentChangeService)) as IComponentChangeService;
if (componentChangeService != null)
{
componentChangeService.ComponentAdded += new ComponentEventHandler(OnComponentAdded);
componentChangeService.ComponentChanged += new ComponentChangedEventHandler(OnComponentChanged);
}
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
CompositeActivity compositeActivity = Activity as CompositeActivity;
if (compositeActivity != null)
{
compositeActivity.Activities.ListChanging -= new EventHandler<ActivityCollectionChangeEventArgs>(OnActivityListChanging);
compositeActivity.Activities.ListChanged -= new EventHandler<ActivityCollectionChangeEventArgs>(OnActivityListChanged);
}
if (IsRootDesigner)
{
IComponentChangeService componentChangeService = GetService(typeof(IComponentChangeService)) as IComponentChangeService;
if (componentChangeService != null)
{
componentChangeService.ComponentAdded -= new ComponentEventHandler(OnComponentAdded);
componentChangeService.ComponentChanged -= new ComponentChangedEventHandler(OnComponentChanged);
}
}
}
base.Dispose(disposing);
}
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
if (ExpandButtonRectangle.Contains(new Point(e.X, e.Y)))
{
//In order to property update the menu items for expand collapse, rather than setting the property
//directly we go thru menu command service
IMenuCommandService menuCommandService = GetService(typeof(IMenuCommandService)) as IMenuCommandService;
if (menuCommandService != null)
menuCommandService.GlobalInvoke((Expanded) ? WorkflowMenuCommands.Collapse : WorkflowMenuCommands.Expand);
else
Expanded = !Expanded;
}
}
protected override void OnPaint(ActivityDesignerPaintEventArgs e)
{
base.OnPaint(e);
CompositeDesignerTheme compositeDesignerTheme = e.DesignerTheme as CompositeDesignerTheme;
if (compositeDesignerTheme == null)
return;
//Draw the expand collapse button and the connection
if (CanExpandCollapse)
{
Rectangle expandButtonRectangle = ExpandButtonRectangle;
if (!expandButtonRectangle.Size.IsEmpty)
{
ActivityDesignerPaint.DrawExpandButton(e.Graphics, expandButtonRectangle, !Expanded, compositeDesignerTheme);
}
}
if (Expanded)
PaintContainedDesigners(e);
}
protected override void OnLayoutPosition(ActivityDesignerLayoutEventArgs e)
{
if (e == null)
throw new ArgumentNullException("e");
base.OnLayoutPosition(e);
foreach (ActivityDesigner activityDesigner in ContainedDesigners)
{
try
{
((IWorkflowDesignerMessageSink)activityDesigner).OnLayoutPosition(e.Graphics);
activityDesigner.DrawingState &= (~DrawingStates.InvalidPosition);
}
catch
{
//Eat the exception thrown
activityDesigner.DrawingState |= DrawingStates.InvalidPosition;
}
}
}
protected override Size OnLayoutSize(ActivityDesignerLayoutEventArgs e)
{
Size containerSize = base.OnLayoutSize(e);
//Calculate the size of internal designers
foreach (ActivityDesigner activityDesigner in ContainedDesigners)
{
try
{
((IWorkflowDesignerMessageSink)activityDesigner).OnLayoutSize(e.Graphics);
activityDesigner.DrawingState &= (~DrawingStates.InvalidSize);
}
catch
{
//Eat the exception thrown
activityDesigner.Size = activityDesigner.DesignerTheme.Size;
activityDesigner.DrawingState |= DrawingStates.InvalidSize;
}
}
if (!String.IsNullOrEmpty(Text))
this.actualTextSize = ActivityDesignerPaint.MeasureString(e.Graphics, e.DesignerTheme.BoldFont, Text, StringAlignment.Center, Size.Empty);
else
this.actualTextSize = Size.Empty;
if (Expanded)
containerSize.Height = TitleHeight;
else
containerSize.Height = TitleHeight + WorkflowTheme.CurrentTheme.AmbientTheme.Margin.Height;
return containerSize;
}
protected override void SaveViewState(BinaryWriter writer)
{
if (writer == null)
throw new ArgumentNullException("writer");
writer.Write(Expanded);
base.SaveViewState(writer);
}
protected override void LoadViewState(BinaryReader reader)
{
if (reader == null)
throw new ArgumentNullException("reader");
Expanded = reader.ReadBoolean();
base.LoadViewState(reader);
}
protected override void OnThemeChange(ActivityDesignerTheme designerTheme)
{
base.OnThemeChange(designerTheme);
CompositeActivity compositeActivity = Activity as CompositeActivity;
if (compositeActivity != null)
{
foreach (Activity activity in compositeActivity.Activities)
{
IWorkflowDesignerMessageSink containedDesigner = ActivityDesigner.GetDesigner(activity) as IWorkflowDesignerMessageSink;
if (containedDesigner != null)
containedDesigner.OnThemeChange();
}
}
}
/// <summary>
/// Call the OnPaint on the contained designers
/// </summary>
/// <param name="e">EventArgs to be used for painting</param>
protected void PaintContainedDesigners(ActivityDesignerPaintEventArgs e)
{
OnPaintContainedDesigners(e);
}
protected override void OnKeyDown(KeyEventArgs e)
{
if (e == null)
throw new ArgumentNullException("e");
ISelectionService selectionService = GetService(typeof(ISelectionService)) as ISelectionService;
object selectedObject = (selectionService != null) ? selectionService.PrimarySelection : null;
if (selectedObject == null)
return;
//handling of the key move events for all designers
//the freeform designer will override that to allow moving of the designers vs moving selection
object nextSelectedObject = null;
if (e.KeyCode == Keys.Down ||
(e.KeyCode == Keys.Tab && !e.Shift))
{
CompositeActivityDesigner selectedDesigner = ActivityDesigner.GetDesigner(selectedObject as Activity) as CompositeActivityDesigner;
if (selectedDesigner != null)
nextSelectedObject = selectedDesigner.FirstSelectableObject;
if (nextSelectedObject == null)
{
do
{
// get parent designer
CompositeActivityDesigner parentDesigner = ActivityDesigner.GetParentDesigner(selectedObject);
if (parentDesigner == null)
{
// IMPORTANT: This will only happen when the focus is on the last connector in ServiceDesigner
nextSelectedObject = selectedObject;
break;
}
nextSelectedObject = parentDesigner.GetNextSelectableObject(selectedObject, DesignerNavigationDirection.Down);
if (nextSelectedObject != null)
break;
selectedObject = parentDesigner.Activity;
} while (true);
}
}
else if (e.KeyCode == Keys.Up ||
(e.KeyCode == Keys.Tab && e.Shift))
{
// get parent designer
CompositeActivityDesigner parentDesigner = ActivityDesigner.GetParentDesigner(selectedObject);
if (parentDesigner == null)
{
// IMPORTANT: This will only happen when the focus is on the ServiceDesigner it self
CompositeActivityDesigner selectedDesigner = ActivityDesigner.GetDesigner(selectedObject as Activity) as CompositeActivityDesigner;
if (selectedDesigner != null)
nextSelectedObject = selectedDesigner.LastSelectableObject;
}
else
{
// ask for previous component
nextSelectedObject = parentDesigner.GetNextSelectableObject(selectedObject, DesignerNavigationDirection.Up);
if (nextSelectedObject != null)
{
CompositeActivityDesigner nextSelectedDesigner = ActivityDesigner.GetDesigner(nextSelectedObject as Activity) as CompositeActivityDesigner;
// when we go up, and then upper selection is parent designer then we look for last component
if (nextSelectedDesigner != null)
{
object lastObject = nextSelectedDesigner.LastSelectableObject;
if (lastObject != null)
nextSelectedObject = lastObject;
}
}
else
{
nextSelectedObject = parentDesigner.Activity;
}
}
}
else if (e.KeyCode == Keys.Left)
{
do
{
CompositeActivityDesigner parentDesigner = ActivityDesigner.GetParentDesigner(selectedObject);
if (parentDesigner == null)
break;
nextSelectedObject = parentDesigner.GetNextSelectableObject(selectedObject, DesignerNavigationDirection.Left);
if (nextSelectedObject != null)
break;
selectedObject = parentDesigner.Activity;
} while (true);
}
else if (e.KeyCode == Keys.Right)
{
do
{
CompositeActivityDesigner parentDesigner = ActivityDesigner.GetParentDesigner(selectedObject);
if (parentDesigner == null)
break;
nextSelectedObject = parentDesigner.GetNextSelectableObject(selectedObject, DesignerNavigationDirection.Right);
if (nextSelectedObject != null)
break;
selectedObject = parentDesigner.Activity;
} while (true);
}
// now select the component
if (nextSelectedObject != null)
{
selectionService.SetSelectedComponents(new object[] { nextSelectedObject }, SelectionTypes.Replace);
// make the selected designer visible
ParentView.EnsureVisible(nextSelectedObject);
}
}
#endregion
#region Private Methods
internal virtual void OnPaintContainedDesigners(ActivityDesignerPaintEventArgs e)
{
foreach (ActivityDesigner activityDesigner in ContainedDesigners)
{
using (PaintEventArgs paintEventArgs = new PaintEventArgs(e.Graphics, e.ViewPort))
{
((IWorkflowDesignerMessageSink)activityDesigner).OnPaint(paintEventArgs, e.ViewPort);
}
}
}
private void OnComponentAdded(object sender, ComponentEventArgs e)
{
ActivityDesigner designer = ActivityDesigner.GetDesigner(e.Component as Activity);
if (Activity != e.Component && designer != null && designer.IsLocked)
DesignerHelpers.MakePropertiesReadOnly(e.Component.Site, designer.Activity);
}
private void OnComponentChanged(object sender, ComponentChangedEventArgs e)
{
IReferenceService referenceService = GetService(typeof(IReferenceService)) as IReferenceService;
Activity changedActivity = (referenceService != null) ? referenceService.GetComponent(e.Component) as Activity : e.Component as Activity;
if (changedActivity != null)
{
ActivityDesigner designer = ActivityDesigner.GetDesigner(changedActivity);
if (designer != null)
{
CompositeActivityDesigner parentDesigner = designer.ParentDesigner;
if (parentDesigner != null)
parentDesigner.OnContainedActivityChanged(new ActivityChangedEventArgs(changedActivity, e.Member, e.OldValue, e.NewValue));
}
}
}
private void OnActivityListChanging(object sender, ActivityCollectionChangeEventArgs e)
{
OnContainedActivitiesChanging(e);
}
private void OnActivityListChanged(object sender, ActivityCollectionChangeEventArgs e)
{
OnContainedActivitiesChanged(e);
}
#endregion
#endregion
#region Properties and Methods
//
public static void MoveDesigners(ActivityDesigner activityDesigner, bool moveBack)
{
if (activityDesigner == null)
throw new ArgumentNullException("activityDesigner");
Activity activity = activityDesigner.Activity as Activity;
if (activity == null || activity.Parent == null)
return;
CompositeActivity compositeActivity = activity.Parent as CompositeActivity;
if (compositeActivity == null || !compositeActivity.Activities.Contains(activity))
return;
int index = compositeActivity.Activities.IndexOf(activity);
index += (moveBack) ? -1 : 1;
if (index < 0 || index >= compositeActivity.Activities.Count)
return;
IDesignerHost designerHost = compositeActivity.Site.GetService(typeof(IDesignerHost)) as IDesignerHost;
if (designerHost == null)
return;
DesignerTransaction trans = designerHost.CreateTransaction(SR.GetString(SR.MovingActivities));
try
{
compositeActivity.Activities.Remove(activity);
compositeActivity.Activities.Insert(index, activity);
ISelectionService selectionService = compositeActivity.Site.GetService(typeof(ISelectionService)) as ISelectionService;
if (selectionService != null)
selectionService.SetSelectedComponents(new object[] { activity });
if (trans != null)
trans.Commit();
}
catch
{
if (trans != null)
trans.Cancel();
throw;
}
CompositeActivityDesigner compositeDesigner = ActivityDesigner.GetDesigner(compositeActivity) as CompositeActivityDesigner;
if (compositeDesigner != null)
compositeDesigner.PerformLayout();
}
#endregion
}
#endregion
}
| |
using System.Threading;
using Pathfinding;
namespace Pathfinding {
/** Queue of paths to be processed by the system */
public class ThreadControlQueue {
public class QueueTerminationException : System.Exception {
}
Path head;
Path tail;
readonly System.Object lockObj = new System.Object();
readonly int numReceivers;
bool blocked;
/** Number of receiver threads that are currently blocked.
* This is only modified while a thread has a lock on lockObj
*/
int blockedReceivers;
/** True while head == null.
* This is only modified while a thread has a lock on lockObj
*/
bool starving;
/** True after TerminateReceivers has been called.
* All receivers will be terminated when they next call Pop.
*/
bool terminate;
ManualResetEvent block = new ManualResetEvent(true);
/** Create a new queue with the specified number of receivers.
* It is important that the number of receivers is fixed.
* Properties like AllReceiversBlocked rely on knowing the exact number of receivers using the Pop (or PopNoBlock) methods.
*/
public ThreadControlQueue (int numReceivers) {
this.numReceivers = numReceivers;
}
/** True if the queue is empty */
public bool IsEmpty {
get {
return head == null;
}
}
/** True if TerminateReceivers has been called */
public bool IsTerminating {
get {
return terminate;
}
}
/** Block queue, all calls to Pop will block until Unblock is called */
public void Block () {
lock (lockObj) {
blocked = true;
block.Reset();
}
}
/** Unblock queue.
* Calls to Pop will not block anymore.
* \see Block
*/
public void Unblock () {
lock (lockObj) {
blocked = false;
block.Set();
}
}
/** Aquires a lock on this queue.
* Must be paired with a call to #Unlock */
public void Lock () {
Monitor.Enter(lockObj);
}
/** Releases the lock on this queue */
public void Unlock () {
Monitor.Exit(lockObj);
}
/** True if blocking and all receivers are waiting for unblocking */
public bool AllReceiversBlocked {
get {
lock (lockObj) {
return blocked && blockedReceivers == numReceivers;
}
}
}
/** Push a path to the front of the queue */
public void PushFront (Path p) {
lock (lockObj) {
// If termination is due, why add stuff to a queue which will not be read from anyway
if (terminate) return;
if (tail == null) {// (tail == null) ==> (head == null)
head = p;
tail = p;
if (starving && !blocked) {
starving = false;
block.Set();
} else {
starving = false;
}
} else {
p.next = head;
head = p;
}
}
}
/** Push a path to the end of the queue */
public void Push (Path p) {
lock (lockObj) {
// If termination is due, why add stuff to a queue which will not be read from anyway
if (terminate) return;
if (tail == null) {// (tail == null) ==> (head == null)
head = p;
tail = p;
if (starving && !blocked) {
starving = false;
block.Set();
} else {
starving = false;
}
} else {
tail.next = p;
tail = p;
}
}
}
void Starving () {
starving = true;
block.Reset();
}
/** All calls to Pop and PopNoBlock will now generate exceptions */
public void TerminateReceivers () {
lock (lockObj) {
terminate = true;
block.Set();
}
}
/** Pops the next item off the queue.
* This call will block if there are no items in the queue or if the queue is currently blocked.
*
* \returns A Path object, guaranteed to be not null.
* \throws QueueTerminationException if #TerminateReceivers has been called.
* \throws System.InvalidOperationException if more receivers get blocked than the fixed count sent to the constructor
*/
public Path Pop () {
Monitor.Enter(lockObj);
try {
if (terminate) {
blockedReceivers++;
throw new QueueTerminationException();
}
if (head == null) {
Starving ();
}
while (blocked || starving) {
blockedReceivers++;
if (blockedReceivers == numReceivers) {
//Last alive
} else if (blockedReceivers > numReceivers) {
throw new System.InvalidOperationException ("More receivers are blocked than specified in constructor ("+blockedReceivers + " > " + numReceivers+")");
}
Monitor.Exit (lockObj);
block.WaitOne();
Monitor.Enter (lockObj);
if (terminate) {
throw new QueueTerminationException();
}
blockedReceivers--;
if (head == null) {
Starving ();
}
}
Path p = head;
if (head.next == null) {
tail = null;
}
head = head.next;
return p;
} finally {
Monitor.Exit(lockObj);
}
}
/** Call when a receiver was terminated in other ways than by a QueueTerminationException.
*
* After this call, the receiver should be dead and not call anything else in this class.
*/
public void ReceiverTerminated () {
Monitor.Enter(lockObj);
blockedReceivers++;
Monitor.Exit (lockObj);
}
/** Pops the next item off the queue, this call will not block.
* To ensure stability, the caller must follow this pattern.
* 1. Call PopNoBlock(false), if a null value is returned, wait for a bit (e.g yield return null in a Unity coroutine)
* 2. try again with PopNoBlock(true), if still null, wait for a bit
* 3. Repeat from step 2.
*
* \throws QueueTerminationException if #TerminateReceivers has been called.
* \throws System.InvalidOperationException if more receivers get blocked than the fixed count sent to the constructor
*/
public Path PopNoBlock (bool blockedBefore) {
Monitor.Enter(lockObj);
try {
if (terminate) {
blockedReceivers++;
throw new QueueTerminationException();
}
if (head == null) {
Starving ();
}
if (blocked || starving) {
if (!blockedBefore) {
blockedReceivers++;
if (terminate) throw new QueueTerminationException();
if (blockedReceivers == numReceivers) {
//Last alive
} else if (blockedReceivers > numReceivers) {
throw new System.InvalidOperationException ("More receivers are blocked than specified in constructor ("+blockedReceivers + " > " + numReceivers+")");
}
}
return null;
}
if (blockedBefore) {
blockedReceivers--;
}
Path p = head;
if (head.next == null) {
tail = null;
}
head = head.next;
return p;
} finally {
Monitor.Exit (lockObj);
}
}
}
}
| |
using System;
using System.IO;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.Extensions.Configuration;
using Toucan.Common;
using Toucan.Contract.Security;
using Toucan.Data.Model;
namespace Toucan.Data
{
public sealed class MsSqlContext : DbContextBase, IDesignTimeDbContextFactory<MsSqlContext>
{
public MsSqlContext() : base()
{
}
public MsSqlContext(DbContextOptions<MsSqlContext> options) : base(options)
{
}
public MsSqlContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<MsSqlContext>();
optionsBuilder.UseSqlServer(this.DesignTimeConfig?.ConnectionString, o =>
{
string assemblyName = typeof(MsSqlContext).GetAssemblyName();
o.MigrationsAssembly(assemblyName);
});
return new MsSqlContext(optionsBuilder.Options);
}
protected sealed override void OnModelCreating(ModelBuilder modelBuilder)
{
base.BeforeModelCreated(modelBuilder);
CreateModel(modelBuilder);
base.AfterModelCreated(modelBuilder);
}
private static void CreateModel(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Provider>(entity =>
{
entity.Property(e => e.ProviderId).HasMaxLength(64);
entity.Property(e => e.Description)
.IsRequired()
.HasMaxLength(512);
entity.Property(e => e.Enabled);
entity.Property(e => e.Name)
.IsRequired()
.HasMaxLength(128);
});
modelBuilder.Entity<Role>(entity =>
{
entity.HasKey(e => e.RoleId)
.HasName("PK_RoleId");
entity.Property(e => e.RoleId)
.IsRequired()
.HasMaxLength(32);
entity.Property(e => e.ParentRoleId)
.HasMaxLength(32);
entity.HasOne(e => e.Parent)
.WithMany(p => p.Children)
.HasForeignKey(o => o.ParentRoleId)
.IsRequired(false);
entity.Property(e => e.Enabled);
entity.Property(e => e.Name)
.IsRequired()
.HasMaxLength(64);
entity.AddAuditColumns();
});
modelBuilder.Entity<SecurityClaim>(entity =>
{
entity.Property(e => e.SecurityClaimId)
.IsRequired()
.HasMaxLength(32);
entity.Property(e => e.Origin)
.IsRequired()
.HasMaxLength(32);
entity.Property(e => e.ValidationPattern)
.IsRequired()
.HasMaxLength(256);
entity.Property(e => e.Description)
.IsRequired()
.HasMaxLength(512);
entity.AddAuditColumns();
});
modelBuilder.Entity<RoleSecurityClaim>(entity =>
{
entity.HasKey(e => new { e.RoleId, e.SecurityClaimId})
.HasName("PK_RoleSecurityClaim");
entity.Property(e => e.RoleId)
.IsRequired()
.HasMaxLength(32);
entity.HasOne(e => e.Role)
.WithMany(p => p.SecurityClaims)
.HasForeignKey(o => o.RoleId);
entity.Property(e => e.SecurityClaimId)
.IsRequired()
.HasMaxLength(32);
entity.HasOne(e => e.SecurityClaim)
.WithMany(p => p.Roles)
.HasForeignKey(o => o.SecurityClaimId);
entity.Property(e => e.Value)
.IsRequired()
.HasMaxLength(64);
});
modelBuilder.Entity<User>(entity =>
{
entity.Property(e => e.CultureName)
.IsRequired();
entity.Property(e => e.DisplayName)
.IsRequired()
.HasMaxLength(128);
entity.Property(e => e.Enabled);
entity.Property(e => e.Username)
.IsRequired()
.HasMaxLength(128);
entity.Property(e => e.TimeZoneId)
.IsRequired()
.HasMaxLength(32);
entity.Property(e => e.CreatedOn)
.IsRequired()
.HasDefaultValueSql("GETUTCDATE()");
entity.Property(e => e.CreatedBy).IsRequired(false);
entity.Property(e => e.LastUpdatedOn)
.IsRequired(false)
.HasColumnType("DATETIME2(7)")
.HasDefaultValueSql("GETUTCDATE()");
entity.Property(e => e.LastUpdatedBy).IsRequired(false);
entity.HasOne(e => e.CreatedByUser)
.WithMany()
.HasForeignKey(o => o.CreatedBy);
entity.HasOne(e => e.LastUpdatedByUser)
.WithMany()
.HasForeignKey(o => o.LastUpdatedBy);
});
modelBuilder.Entity<UserProvider>(entity =>
{
entity.HasKey(e => new { e.ProviderId, e.UserId })
.HasName("PK_UserProvider");
entity.Property(e => e.ProviderId)
.HasMaxLength(64);
entity.Property(e => e.CreatedOn)
.HasColumnType("DATETIME2(7)")
.HasDefaultValueSql("GETUTCDATE()");
entity.Property(e => e.ExternalId)
.HasMaxLength(64);
entity.HasOne(d => d.Provider)
.WithMany(p => p.Users)
.HasForeignKey(d => d.ProviderId)
.HasConstraintName("FK_UserProvider_Provider");
entity.HasOne(d => d.User)
.WithMany(p => p.Providers)
.HasForeignKey(d => d.UserId)
.HasConstraintName("FK_UserProvider_User");
entity.HasDiscriminator<string>("UserProviderType")
.HasValue<UserProvider>("External")
.HasValue<UserProviderLocal>("Local");
});
modelBuilder.Entity<Verification>(entity =>
{
entity.HasKey(e => e.Code)
.HasName("PK_Verification");
entity.HasIndex(e => e.UserId)
.HasName("IX_Verification_UserId");
entity.Property(e => e.Code)
.IsRequired(true)
.HasMaxLength(64);
entity.Property(e => e.Fingerprint)
.IsRequired(true)
.HasMaxLength(256);
entity.Property(e => e.ProviderKey)
.IsRequired(true)
.HasMaxLength(64);
entity.Property(e => e.IssuedAt)
.HasColumnType("DATETIME2(7)")
.HasDefaultValueSql("GETUTCDATE()");
entity.Property(e => e.RedeemedAt)
.IsRequired(false)
.HasColumnType("DATETIME2(7)");
entity.HasOne(d => d.User)
.WithMany(d => d.Verifications)
.HasForeignKey(d => d.UserId)
.HasConstraintName("FK_Verification_User");
});
modelBuilder.Entity<UserProviderLocal>(entity =>
{
entity.Property(e => e.PasswordSalt)
.HasMaxLength(128);
entity.Property(e => e.PasswordHash)
.HasMaxLength(256);
});
modelBuilder.Entity<UserRole>(entity =>
{
entity.HasKey(e => new { e.RoleId, e.UserId })
.HasName("PK_UserRole");
entity.HasIndex(e => e.UserId)
.HasName("IX_UserRole_UserId");
entity.Property(e => e.RoleId).HasMaxLength(32);
entity.HasOne(d => d.Role)
.WithMany(p => p.Users)
.HasForeignKey(d => d.RoleId)
.HasConstraintName("FK_UserRole_Role")
.OnDelete(DeleteBehavior.ClientSetNull);
entity.HasOne(d => d.User)
.WithMany(p => p.Roles)
.HasForeignKey(d => d.UserId)
.HasConstraintName("FK_UserRole_User");
});
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudioTools.Project {
#region structures
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct _DROPFILES {
public Int32 pFiles;
public Int32 X;
public Int32 Y;
public Int32 fNC;
public Int32 fWide;
}
#endregion
#region enums
/// <summary>
/// Defines the currect state of a property page.
/// </summary>
[Flags]
public enum PropPageStatus {
Dirty = 0x1,
Validate = 0x2,
Clean = 0x4
}
/// <summary>
/// Defines the status of the command being queried
/// </summary>
[Flags]
public enum QueryStatusResult {
/// <summary>
/// The command is not supported.
/// </summary>
NOTSUPPORTED = 0,
/// <summary>
/// The command is supported
/// </summary>
SUPPORTED = 1,
/// <summary>
/// The command is enabled
/// </summary>
ENABLED = 2,
/// <summary>
/// The command is toggled on
/// </summary>
LATCHED = 4,
/// <summary>
/// The command is toggled off (the opposite of LATCHED).
/// </summary>
NINCHED = 8,
/// <summary>
/// The command is invisible.
/// </summary>
INVISIBLE = 16
}
/// <summary>
/// Defines the type of item to be added to the hierarchy.
/// </summary>
public enum HierarchyAddType {
AddNewItem,
AddExistingItem
}
/// <summary>
/// Defines the component from which a command was issued.
/// </summary>
public enum CommandOrigin {
UiHierarchy,
OleCommandTarget
}
/// <summary>
/// Defines the current status of the build process.
/// </summary>
public enum MSBuildResult {
/// <summary>
/// The build is currently suspended.
/// </summary>
Suspended,
/// <summary>
/// The build has been restarted.
/// </summary>
Resumed,
/// <summary>
/// The build failed.
/// </summary>
Failed,
/// <summary>
/// The build was successful.
/// </summary>
Successful,
}
/// <summary>
/// Defines the type of action to be taken in showing the window frame.
/// </summary>
public enum WindowFrameShowAction {
DoNotShow,
Show,
ShowNoActivate,
Hide,
}
/// <summary>
/// Defines drop types
/// </summary>
internal enum DropDataType {
None,
Shell,
VsStg,
VsRef
}
/// <summary>
/// Used by the hierarchy node to decide which element to redraw.
/// </summary>
[Flags]
public enum UIHierarchyElement {
None = 0,
/// <summary>
/// This will be translated to VSHPROPID_IconIndex
/// </summary>
Icon = 1,
/// <summary>
/// This will be translated to VSHPROPID_StateIconIndex
/// </summary>
SccState = 2,
/// <summary>
/// This will be translated to VSHPROPID_Caption
/// </summary>
Caption = 4,
/// <summary>
/// This will be translated to VSHPROPID_OverlayIconIndex
/// </summary>
OverlayIcon = 8
}
/// <summary>
/// Defines the global propeties used by the msbuild project.
/// </summary>
public enum GlobalProperty {
/// <summary>
/// Property specifying that we are building inside VS.
/// </summary>
BuildingInsideVisualStudio,
/// <summary>
/// The VS installation directory. This is the same as the $(DevEnvDir) macro.
/// </summary>
DevEnvDir,
/// <summary>
/// The name of the solution the project is created. This is the same as the $(SolutionName) macro.
/// </summary>
SolutionName,
/// <summary>
/// The file name of the solution. This is the same as $(SolutionFileName) macro.
/// </summary>
SolutionFileName,
/// <summary>
/// The full path of the solution. This is the same as the $(SolutionPath) macro.
/// </summary>
SolutionPath,
/// <summary>
/// The directory of the solution. This is the same as the $(SolutionDir) macro.
/// </summary>
SolutionDir,
/// <summary>
/// The extension of teh directory. This is the same as the $(SolutionExt) macro.
/// </summary>
SolutionExt,
/// <summary>
/// The fxcop installation directory.
/// </summary>
FxCopDir,
/// <summary>
/// The ResolvedNonMSBuildProjectOutputs msbuild property
/// </summary>
VSIDEResolvedNonMSBuildProjectOutputs,
/// <summary>
/// The Configuartion property.
/// </summary>
Configuration,
/// <summary>
/// The platform property.
/// </summary>
Platform,
/// <summary>
/// The RunCodeAnalysisOnce property
/// </summary>
RunCodeAnalysisOnce,
/// <summary>
/// The VisualStudioStyleErrors property
/// </summary>
VisualStudioStyleErrors,
}
#endregion
public class AfterProjectFileOpenedEventArgs : EventArgs {
}
public class BeforeProjectFileClosedEventArgs : EventArgs {
#region fields
private bool _removed;
private IVsHierarchy _hierarchy;
#endregion
#region properties
/// <summary>
/// true if the project was removed from the solution before the solution was closed. false if the project was removed from the solution while the solution was being closed.
/// </summary>
internal bool Removed {
get { return _removed; }
}
internal IVsHierarchy Hierarchy {
get {
return _hierarchy;
}
}
#endregion
#region ctor
internal BeforeProjectFileClosedEventArgs(IVsHierarchy hierarchy, bool removed) {
this._removed = removed;
_hierarchy = hierarchy;
}
#endregion
}
/// <summary>
/// Argument of the event raised when a project property is changed.
/// </summary>
public class ProjectPropertyChangedArgs : EventArgs {
private string propertyName;
private string oldValue;
private string newValue;
internal ProjectPropertyChangedArgs(string propertyName, string oldValue, string newValue) {
this.propertyName = propertyName;
this.oldValue = oldValue;
this.newValue = newValue;
}
public string NewValue {
get { return newValue; }
}
public string OldValue {
get { return oldValue; }
}
public string PropertyName {
get { return propertyName; }
}
}
/// <summary>
/// This class is used for the events raised by a HierarchyNode object.
/// </summary>
internal class HierarchyNodeEventArgs : EventArgs {
private HierarchyNode child;
internal HierarchyNodeEventArgs(HierarchyNode child) {
this.child = child;
}
public HierarchyNode Child {
get { return this.child; }
}
}
/// <summary>
/// Event args class for triggering file change event arguments.
/// </summary>
public class FileChangedOnDiskEventArgs : EventArgs {
#region Private fields
/// <summary>
/// File name that was changed on disk.
/// </summary>
private string fileName;
/// <summary>
/// The item ide of the file that has changed.
/// </summary>
private uint itemID;
/// <summary>
/// The reason the file has changed on disk.
/// </summary>
private _VSFILECHANGEFLAGS fileChangeFlag;
#endregion
/// <summary>
/// Constructs a new event args.
/// </summary>
/// <param name="fileName">File name that was changed on disk.</param>
/// <param name="id">The item id of the file that was changed on disk.</param>
internal FileChangedOnDiskEventArgs(string fileName, uint id, _VSFILECHANGEFLAGS flag) {
this.fileName = fileName;
this.itemID = id;
this.fileChangeFlag = flag;
}
/// <summary>
/// Gets the file name that was changed on disk.
/// </summary>
/// <value>The file that was changed on disk.</value>
public string FileName {
get {
return this.fileName;
}
}
/// <summary>
/// Gets item id of the file that has changed
/// </summary>
/// <value>The file that was changed on disk.</value>
internal uint ItemID {
get {
return this.itemID;
}
}
/// <summary>
/// The reason while the file has chnaged on disk.
/// </summary>
/// <value>The reason while the file has chnaged on disk.</value>
public _VSFILECHANGEFLAGS FileChangeFlag {
get {
return this.fileChangeFlag;
}
}
}
}
| |
/*
Copyright 2014 David Bordoley
Copyright 2014 Zumero, 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
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 Xunit;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace SQLitePCL.pretty.tests
{
public class SQLiteDatabaseConnectionTests
{
private static string GetTempFile()
{
using (var db = SQLite3.OpenInMemory())
{
return "tmp" + db.Query("SELECT lower(hex(randomblob(16)));").SelectScalarString().First();
}
}
[Fact]
public void TestFinalize()
{
// There is no way to assert, so this test is primarily for code coverage.
var db = SQLite3.OpenInMemory();
var stmt = db.PrepareStatement("SELECT 1;");
GC.Collect();
}
[Fact]
public void TestDispose()
{
var db = SQLite3.OpenInMemory();
// This is for test purposes only, never prepare a statement and dispose the db before the statements.
db.PrepareStatement("Select 1");
db.PrepareStatement("Select 2");
db.Dispose();
Assert.Throws<ObjectDisposedException>(() => { var x = db.Changes; });
Assert.Throws<ObjectDisposedException>(() => { var x = db.TotalChanges; });
Assert.Throws<ObjectDisposedException>(() => { var x = db.IsAutoCommit; });
Assert.Throws<ObjectDisposedException>(() => { var x = db.IsReadOnly; });
Assert.Throws<ObjectDisposedException>(() => { var x = db.LastInsertedRowId; });
Assert.Throws<ObjectDisposedException>(() => { var x = db.Statements; });
using (var db2 = SQLite3.OpenInMemory())
{
Assert.Throws<ObjectDisposedException>(() => { db.Backup("main", db2, "main"); });
}
Assert.Throws<ObjectDisposedException>(() => { var x = db.IsDatabaseReadOnly("main"); });
Assert.Throws<ObjectDisposedException>(() => { var x = db.GetFileName("main"); });
Assert.Throws<ObjectDisposedException>(() => { var x = db.OpenBlob("db", "tn", "cn", 0, false); });
Assert.Throws<ObjectDisposedException>(() => { var x = db.PrepareStatement("SELECT 1"); });
int current;
int highwater;
Assert.Throws<ObjectDisposedException>(() => { db.Status(DatabaseConnectionStatusCode.CacheMiss, out current, out highwater, false); });
Assert.Throws<ObjectDisposedException>(() => { db.WalCheckPoint("main"); });
}
[Fact]
public void TestIsDatabaseReadonly()
{
using (var db = SQLite3.Open(":memory:", ConnectionFlags.ReadOnly, null))
{
Assert.True(db.IsReadOnly);
Assert.True(db.IsDatabaseReadOnly("main"));
Assert.Throws<ArgumentException>(() => db.IsDatabaseReadOnly("baz"));
}
using (var db = SQLite3.OpenInMemory())
{
Assert.False(db.IsDatabaseReadOnly("main"));
}
}
[Fact]
public void TestInterrupt()
{
using (var db = SQLite3.OpenInMemory())
{
db.Execute("CREATE TABLE foo (x int);");
db.Execute("INSERT INTO foo (x) VALUES (1);");
db.Execute("INSERT INTO foo (x) VALUES (2);");
db.Execute("INSERT INTO foo (x) VALUES (3);");
using (var stmt = db.PrepareStatement("SELECT x FROM foo;"))
{
stmt.MoveNext();
db.Interrupt();
Assert.Throws<OperationCanceledException>(() => stmt.MoveNext());
}
}
}
[Fact]
public void TestRollbackEvent()
{
using (var db = SQLite3.OpenInMemory())
{
var rollbacks = 0;
db.Rollback += (o, e) => rollbacks++;
Assert.Equal(rollbacks, 0);
db.ExecuteAll(
@"CREATE TABLE foo (x int);
INSERT INTO foo (x) VALUES (1);
BEGIN TRANSACTION;
INSERT INTO foo (x) VALUES (2);
ROLLBACK TRANSACTION;
BEGIN TRANSACTION;
INSERT INTO foo (x) VALUES (2);
ROLLBACK TRANSACTION;");
Assert.Equal(rollbacks, 2);
}
}
[Fact]
public void TestProfileEvent()
{
using (var db = SQLite3.OpenInMemory())
{
var statement = "CREATE TABLE foo (x int);";
db.Profile += (o, e) =>
{
Assert.Equal(statement, e.Statement);
Assert.True(TimeSpan.MinValue < e.ExecutionTime);
};
db.Execute(statement);
}
}
[Fact]
public void TestTraceEvent()
{
using (var db = SQLite3.OpenInMemory())
{
var statement = "CREATE TABLE foo (x int);";
db.Trace += (o, e) =>
{
Assert.Equal(statement, e.Statement);
};
db.Execute(statement);
statement = "INSERT INTO foo (x) VALUES (1);";
db.Execute(statement);
}
}
[Fact]
public void TestUpdateEvent()
{
using (var db = SQLite3.OpenInMemory())
{
var currentAction = ActionCode.CreateTable;
var rowid = 1;
db.Update += (o, e) =>
{
Assert.Equal(currentAction, e.Action);
Assert.Equal("main", e.Database);
Assert.Equal("foo", e.Table);
Assert.Equal(rowid, e.RowId);
};
currentAction = ActionCode.CreateTable;
rowid = 1;
db.Execute("CREATE TABLE foo (x int);");
currentAction = ActionCode.Insert;
rowid = 1;
db.Execute("INSERT INTO foo (x) VALUES (1);");
currentAction = ActionCode.Insert;
rowid = 2;
db.Execute("INSERT INTO foo (x) VALUES (2);");
currentAction = ActionCode.DropTable;
rowid = 2;
db.Execute("DROP TABLE foo");
}
}
[Fact]
public void TestBusyTimeout()
{
//Assert.Fail("Implement me");
}
[Fact]
public void TestChanges()
{
using (var db = SQLite3.OpenInMemory())
{
Assert.Equal(db.TotalChanges, 0);
Assert.Equal(db.Changes, 0);
db.Execute("CREATE TABLE foo (x int);");
Assert.Equal(db.TotalChanges, 0);
Assert.Equal(db.Changes, 0);
db.Execute("INSERT INTO foo (x) VALUES (1);");
Assert.Equal(db.TotalChanges, 1);
Assert.Equal(db.Changes, 1);
db.Execute("INSERT INTO foo (x) VALUES (2);");
db.Execute("INSERT INTO foo (x) VALUES (3);");
Assert.Equal(db.TotalChanges, 3);
Assert.Equal(db.Changes, 1);
db.Execute("UPDATE foo SET x=5;");
Assert.Equal(db.TotalChanges, 6);
Assert.Equal(db.Changes, 3);
}
}
[Fact]
public void TestIsAutoCommit()
{
using (var db = SQLite3.OpenInMemory())
{
Assert.True(db.IsAutoCommit);
db.Execute("BEGIN TRANSACTION;");
Assert.False(db.IsAutoCommit);
}
}
[Fact]
public void TestSetBusyTimeout()
{
var builder = SQLiteDatabaseConnectionBuilder.InMemory.With(busyTimeout: new TimeSpan(100));
using (var db = builder.Build())
{
// FIXME: Not the best test without Asserts.
}
}
[Fact]
public void TestStatements()
{
using (var db = SQLite3.OpenInMemory())
{
Assert.Equal(db.Statements.Count(), 0);
using (IStatement stmt0 = db.PrepareStatement("SELECT 5;"),
stmt1 = db.PrepareStatement("SELECT 6;"),
stmt2 = db.PrepareStatement("SELECT 7;"))
{
Assert.Equal(db.Statements.Count(), 3);
IStatement[] stmts = { stmt2, stmt1, stmt0 };
// IStatement can't sanely implement equality at the
// interface level. Doing so would tightly bind the
// interface to the underlying SQLite implementation
// which we don't want to do.
foreach (var pair in Enumerable.Zip(stmts, db.Statements, (a, b) => Tuple.Create(a.SQL, b.SQL)))
{
Assert.Equal(pair.Item1, pair.Item2);
}
}
}
}
// FIXME: This test creates a file which isn't PCL friendly. Need to update.
[Fact]
public void TestTryGetFileName()
{
using (var db = SQLite3.OpenInMemory())
{
db.Execute("CREATE TABLE foo (x int);");
string filename = null;
Assert.False(db.TryGetFileName("foo", out filename));
Assert.True(filename == null);
Assert.Throws<InvalidOperationException>(() => db.GetFileName("main"));
}
var tempFile = GetTempFile();
using (var db = SQLite3.Open(tempFile))
{
db.Execute("CREATE TABLE foo (x int);");
string filename = null;
Assert.True(db.TryGetFileName("main", out filename));
Assert.True(filename.EndsWith(tempFile));
Assert.Equal(db.GetFileName("main"), filename);
}
raw.sqlite3__vfs__delete(null, tempFile, 1);
}
[Fact]
public void TestWithCollation()
{
var builder = SQLiteDatabaseConnectionBuilder.InMemory.WithCollation("e2a", (string s1, string s2) =>
{
s1 = s1.Replace('e', 'a');
s2 = s2.Replace('e', 'a');
return String.CompareOrdinal(s1, s2);
});
using (var db = builder.Build())
{
db.Execute("CREATE TABLE foo (x text COLLATE e2a);");
db.Execute("INSERT INTO foo (x) VALUES ('b')");
db.Execute("INSERT INTO foo (x) VALUES ('c')");
db.Execute("INSERT INTO foo (x) VALUES ('d')");
db.Execute("INSERT INTO foo (x) VALUES ('e')");
db.Execute("INSERT INTO foo (x) VALUES ('f')");
string top =
db.Query("SELECT x FROM foo ORDER BY x ASC LIMIT 1;").SelectScalarString().First();
Assert.Equal(top, "e");
}
builder = builder.WithoutCollation("e2a");
using (var db = builder.Build())
{
Assert.Throws<SQLiteException>(() => db.Execute("CREATE TABLE bar (x text COLLATE e2a);"));
}
}
[Fact]
public void TestWithCommitHook()
{
var commits = 0;
var tmpFile = GetTempFile();
var builder =
SQLiteDatabaseConnectionBuilder.Create(tmpFile,
commitHook: () =>
{
commits++;
return false;
});
using (var db = builder.Build())
{
db.Execute("CREATE TABLE foo (x int);");
db.Execute("INSERT INTO foo (x) VALUES (1);");
Assert.Equal(2, commits);
}
builder = builder.Without(commitHook: true);
using (var db = builder.Build())
{
db.Execute("INSERT INTO foo (x) VALUES (1);");
db.Execute("INSERT INTO foo (x) VALUES (1);");
Assert.Equal(2, commits);
}
builder = builder.With(commitHook: () => true);
using (var db = builder.Build())
{
try
{
db.Execute("INSERT INTO foo (x) VALUES (1);");
Assert.True(false, "Expected exception to be thrown");
}
catch (SQLiteException e)
{
Assert.Equal(ErrorCode.ConstraintCommitHook, e.ExtendedErrorCode);
}
var count =
db.Query("SELECT COUNT(*) from foo")
.Select(row => row.First().ToInt())
.First();
Assert.Equal(3, count);
}
raw.sqlite3__vfs__delete(null, tmpFile, 1);
}
[Fact]
public void TestWithAggregateFunc()
{
var builder = SQLiteDatabaseConnectionBuilder.InMemory.WithAggregateFunc(
"sum_plus_count",
Tuple.Create(0L, 0L),
(Tuple<long, long> acc, ISQLiteValue arg) => Tuple.Create(acc.Item1 + arg.ToInt64(), acc.Item2 + 1L),
(Tuple<long, long> acc) => (acc.Item1 + acc.Item2).ToSQLiteValue());
using (var db = builder.Build())
{
db.Execute("CREATE TABLE foo (x int);");
for (int i = 0; i < 5; i++)
{
db.Execute("INSERT INTO foo (x) VALUES (?);", i);
}
long c = db.Query("SELECT sum_plus_count(x) FROM foo;").SelectScalarInt64().First();
Assert.Equal(c, (0 + 1 + 2 + 3 + 4) + 5);
}
builder = builder.WithoutFunc("sum_plus_count", 1);
using (var db = builder.Build())
{
db.Execute("CREATE TABLE foo (x int);");
for (int i = 0; i < 5; i++)
{
db.Execute("INSERT INTO foo (x) VALUES (?);", i);
}
Assert.Throws<SQLiteException>(() =>
db.Query("SELECT sum_plus_count(x) FROM foo;").SelectScalarInt64().First());
}
builder = builder
.WithAggregateFunc("row_count", 0, i => i + 1, i => i.ToSQLiteValue())
.WithAggregateFunc("row_count", 0, (int i, ISQLiteValue _v0) => i + 1, i => i.ToSQLiteValue())
.WithAggregateFunc("row_count", 0, (i, _v0, _v1) => i + 1, i => i.ToSQLiteValue())
.WithAggregateFunc("row_count", 0, (i, _v0, _v1, _v2) => i + 1, i => i.ToSQLiteValue())
.WithAggregateFunc("row_count", 0, (i, _v0, _v1, _v2, _v3) => i + 1, i => i.ToSQLiteValue())
.WithAggregateFunc("row_count", 0, (i, _v0, _v1, _v2, _v3, _v4) => i + 1, i => i.ToSQLiteValue())
.WithAggregateFunc("row_count", 0, (i, _v0, _v1, _v2, _v3, _v4, _v5) => i + 1, i => i.ToSQLiteValue())
.WithAggregateFunc("row_count", 0, (i, _v0, _v1, _v2, _v3, _v4, _v5, _v6) => i + 1, i => i.ToSQLiteValue())
.WithAggregateFunc("row_count", 0, (i, _v0, _v1, _v2, _v3, _v4, _v5, _v6, _v7) => i + 1, i => i.ToSQLiteValue())
.WithAggregateFunc("row_count", 0, (int i, IReadOnlyList<ISQLiteValue> v) => i + 1, i => i.ToSQLiteValue());
using (var db = builder.Build())
{
db.Execute("CREATE TABLE foo (x int);");
using (var stmt = db.PrepareStatement("INSERT INTO foo (x) VALUES (?);"))
{
for (int i = 0; i < 5; i++)
{
stmt.Execute(1);
}
}
var result = db.Query("SELECT row_count() FROM foo;").SelectScalarInt64().First();
Assert.Equal(result, 5);
result = db.Query("SELECT row_count(x) FROM foo;").SelectScalarInt64().First();
Assert.Equal(result, 5);
result = db.Query("SELECT row_count(x, 1) FROM foo;").SelectScalarInt64().First();
Assert.Equal(result, 5);
result = db.Query("SELECT row_count(x, 1, 2) FROM foo;").SelectScalarInt64().First();
Assert.Equal(result, 5);
result = db.Query("SELECT row_count(x, 1, 2, 3) FROM foo;").SelectScalarInt64().First();
Assert.Equal(result, 5);
result = db.Query("SELECT row_count(x, 1, 2, 3, 4) FROM foo;").SelectScalarInt64().First();
Assert.Equal(result, 5);
result = db.Query("SELECT row_count(x, 1, 2, 3, 4, 5) FROM foo;").SelectScalarInt64().First();
Assert.Equal(result, 5);
result = db.Query("SELECT row_count(x, 1, 2, 3, 4, 5, 6) FROM foo;").SelectScalarInt64().First();
Assert.Equal(result, 5);
result = db.Query("SELECT row_count(x, 1, 2, 3, 4, 5, 6, 7) FROM foo;").SelectScalarInt64().First();
Assert.Equal(result, 5);
result = db.Query("SELECT row_count(x, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) FROM foo;").SelectScalarInt64().First();
Assert.Equal(result, 5);
}
}
[Fact]
public void TestWithScalarFunc()
{
var builder = SQLiteDatabaseConnectionBuilder.InMemory.WithScalarFunc(
"count_nulls",
(IReadOnlyList<ISQLiteValue> vals) =>
vals.Count(val => val.SQLiteType == SQLiteType.Null).ToSQLiteValue());
using (var db = builder.Build())
{
Assert.Equal(0, db.Query("SELECT count_nulls(1,2,3,4,5,6,7,8);").SelectScalarInt().First());
Assert.Equal(0, db.Query("SELECT count_nulls();").SelectScalarInt().First());
Assert.Equal(1, db.Query("SELECT count_nulls(null);").SelectScalarInt().First());
Assert.Equal(2, db.Query("SELECT count_nulls(1,null,3,null,5);").SelectScalarInt().First());
}
builder = builder.WithoutFunc("count_nulls", -1);
using (var db = builder.Build())
{
Assert.Throws<SQLiteException>(() =>
db.Query("SELECT count_nulls(1,2,3,4,5,6,7,8);")
.Select(row => row[0].ToInt64())
.First());
}
builder = builder
.WithScalarFunc("count_args", (IReadOnlyList<ISQLiteValue> values) => values.Count.ToSQLiteValue())
.WithScalarFunc("len_as_blobs", (IReadOnlyList<ISQLiteValue> values) =>
values.Where(v => v.SQLiteType != SQLiteType.Null).Aggregate(0, (acc, val) => acc + val.Length).ToSQLiteValue())
.WithScalarFunc("my_concat", (IReadOnlyList<ISQLiteValue> values) =>
string.Join("", values.Select(v => v.ToString())).ToSQLiteValue())
.WithScalarFunc("my_mean", (IReadOnlyList<ISQLiteValue> values) =>
(values.Aggregate(0d, (acc, v) => acc + v.ToDouble()) / values.Count).ToSQLiteValue())
.WithScalarFunc("makeblob", (ISQLiteValue v) =>
{
byte[] b = new byte[v.ToInt()];
for (int i = 0; i < b.Length; i++)
{
b[i] = (byte)(i % 256);
}
return b.ToSQLiteValue();
})
.WithScalarFunc("cube", (ISQLiteValue x) => (x.ToInt64() * x.ToInt64() * x.ToInt64()).ToSQLiteValue())
.WithScalarFunc("num_var", () => (0).ToSQLiteValue())
.WithScalarFunc("num_var", (ISQLiteValue _1) => (1).ToSQLiteValue())
.WithScalarFunc("num_var", (_1, _2) => (2).ToSQLiteValue())
.WithScalarFunc("num_var", (_1, _2, _3) => (3).ToSQLiteValue())
.WithScalarFunc("num_var", (_1, _2, _3, _4) => (4).ToSQLiteValue())
.WithScalarFunc("num_var", (_1, _2, _3, _4, _5) => (5).ToSQLiteValue())
.WithScalarFunc("num_var", (_1, _2, _3, _4, _5, _6) => (6).ToSQLiteValue())
.WithScalarFunc("num_var", (_1, _2, _3, _4, _5, _6, _7) => (7).ToSQLiteValue())
.WithScalarFunc("num_var", (_1, _2, _3, _4, _5, _6, _7, _8) => (8).ToSQLiteValue())
.WithScalarFunc("zeroblob", (ISQLiteValue i) => SQLiteValue.ZeroBlob(i.ToInt()))
.WithScalarFunc("nullFunc", () => SQLiteValue.Null);
using (var db = builder.Build())
{
Assert.Equal(8, db.Query("SELECT count_args(1,2,3,4,5,6,7,8);").SelectScalarInt().First());
Assert.Equal(0, db.Query("SELECT count_args();").SelectScalarInt().First());
Assert.Equal(1, db.Query("SELECT count_args(null);").SelectScalarInt().First());
Assert.Equal(0, db.Query("SELECT len_as_blobs();").SelectScalarInt().First());
Assert.Equal(0, db.Query("SELECT len_as_blobs(null);").SelectScalarInt().First());
Assert.True(8 <= db.Query("SELECT len_as_blobs(1,2,3,4,5,6,7,8);").SelectScalarInt().First());
Assert.Equal("foobar", db.Query("SELECT my_concat('foo', 'bar');").SelectScalarString().First());
Assert.Equal("abc", db.Query("SELECT my_concat('a', 'b', 'c');").SelectScalarString().First());
{
var result = db.Query("SELECT my_mean(1,2,3,4,5,6,7,8);").SelectScalarDouble().First();
Assert.True(result >= (36 / 8));
Assert.True(result <= (36 / 8 + 1));
}
{
int val = 5;
var c = db.Query("SELECT makeblob(?);", val).SelectScalarBlob().First();
Assert.Equal(c.Length, val);
}
{
int val = 5;
var c = db.Query("SELECT cube(?);", val).SelectScalarInt64().First();
Assert.Equal(c, val * val * val);
}
// Test all the extension methods.
{
var result = db.Query("SELECT num_var();").SelectScalarInt().First();
Assert.Equal(result, 0);
result = db.Query("SELECT num_var(1);").SelectScalarInt().First();
Assert.Equal(result, 1);
result = db.Query("SELECT num_var(1, 2);").SelectScalarInt().First();
Assert.Equal(result, 2);
result = db.Query("SELECT num_var(1, 2, 3);").SelectScalarInt().First();
Assert.Equal(result, 3);
result = db.Query("SELECT num_var(1, 2, 3, 4);").SelectScalarInt().First();
Assert.Equal(result, 4);
result = db.Query("SELECT num_var(1, 2, 3, 4, 5);").SelectScalarInt().First();
Assert.Equal(result, 5);
result = db.Query("SELECT num_var(1, 2, 3, 4, 5, 6);").SelectScalarInt().First();
Assert.Equal(result, 6);
result = db.Query("SELECT num_var(1, 2, 3, 4, 5, 6, 7);").SelectScalarInt().First();
Assert.Equal(result, 7);
result = db.Query("SELECT num_var(1, 2, 3, 4, 5, 6, 7, 8);").SelectScalarInt().First();
Assert.Equal(result, 8);
}
{
int length = 10;
var result = db.Query("SELECT zeroblob(?);", length).Select(rs => rs[0].Length).First();
Assert.Equal(result, length);
}
{
var result = db.Query("SELECT nullFunc();").Select(rs => rs[0].SQLiteType).First();
Assert.Equal(result, SQLiteType.Null);
}
}
}
[Fact]
public void TestWalCheckpoint()
{
var tmpFile = GetTempFile();
using (var db = SQLite3.Open(tmpFile))
{
db.Execute("PRAGMA journal_mode=WAL;");
// CREATE TABLE results in 2 frames check pointed and increaseses the log size by 2
// so manually do a checkpoint to reset the counters thus testing both
// sqlite3_wal_checkpoint and sqlite3_wal_checkpoint_v2.
db.Execute("CREATE TABLE foo (x int);");
db.WalCheckPoint("main");
db.Execute("INSERT INTO foo (x) VALUES (1);");
db.Execute("INSERT INTO foo (x) VALUES (2);");
int logSize;
int framesCheckPointed;
db.WalCheckPoint("main", WalCheckPointMode.Full, out logSize, out framesCheckPointed);
Assert.Equal(2, logSize);
Assert.Equal(2, framesCheckPointed);
}
// Set autocheckpoint to 1 so that regardless of the number of
// commits, explicit checkpoints only checkpoint the last update.
var builder = SQLiteDatabaseConnectionBuilder.Create(
tmpFile,
autoCheckPointCount: 1);
using (var db = builder.Build())
{
db.Execute("INSERT INTO foo (x) VALUES (3);");
db.Execute("INSERT INTO foo (x) VALUES (4);");
db.Execute("INSERT INTO foo (x) VALUES (5);");
int logSize;
int framesCheckPointed;
db.WalCheckPoint("main", WalCheckPointMode.Passive, out logSize, out framesCheckPointed);
Assert.Equal(1, logSize);
Assert.Equal(1, framesCheckPointed);
}
builder = builder.With(autoCheckPointCount: 0);
using (var db = builder.Build())
{
db.Execute("INSERT INTO foo (x) VALUES (3);");
db.Execute("INSERT INTO foo (x) VALUES (4);");
db.Execute("INSERT INTO foo (x) VALUES (5);");
int logSize;
int framesCheckPointed;
db.WalCheckPoint("main", WalCheckPointMode.Passive, out logSize, out framesCheckPointed);
Assert.True(logSize > 1);
Assert.True(framesCheckPointed > 1);
}
raw.sqlite3__vfs__delete(null, tmpFile, 1);
}
[Fact]
public void TestTableColumnMetadata()
{
using (var db = SQLite3.OpenInMemory())
{
// out string dataType, out string collSeq, out int notNull, out int primaryKey, out int autoInc
db.Execute("CREATE TABLE foo (rowid integer primary key asc autoincrement, x int not null);");
var metadata = db.GetTableColumnMetadata("main", "foo", "x");
Assert.Equal(metadata.DeclaredType, "int");
Assert.Equal(metadata.CollationSequence, "BINARY");
Assert.True(metadata.HasNotNullConstraint);
Assert.False(metadata.IsPrimaryKeyPart);
Assert.False(metadata.IsAutoIncrement);
metadata = db.GetTableColumnMetadata("main", "foo", "rowid");
Assert.Equal(metadata.DeclaredType, "integer");
Assert.Equal(metadata.CollationSequence, "BINARY");
Assert.False(metadata.HasNotNullConstraint);
Assert.True(metadata.IsPrimaryKeyPart);
Assert.True(metadata.IsAutoIncrement);
}
}
[Fact]
public void TestProgressHandler()
{
int count = 0;
var builder = SQLiteDatabaseConnectionBuilder.InMemory.With(
progressHandler: () =>
{
count++;
return false;
},
progressHandlerInterval: 1);
using (var db = builder.Build())
{
using (var stmt = db.PrepareStatement("SELECT 1;"))
{
stmt.MoveNext();
}
Assert.True(count > 0);
}
builder = builder.With(progressHandler: () => true);
using (var db = builder.Build())
{
using (var stmt = db.PrepareStatement("SELECT 1;"))
{
Assert.Throws<OperationCanceledException>(() => stmt.MoveNext());
}
}
// Test that assigning null to the handler removes the progress handler.
builder = builder.Without(progressHandler: true);
using (var db = builder.Build())
{
using (var stmt = db.PrepareStatement("SELECT 1;"))
{
stmt.MoveNext();
}
}
}
[Fact]
public void TestAuthorizer()
{
var tmpFile = GetTempFile();
var builder = SQLiteDatabaseConnectionBuilder.Create(tmpFile,
authorizer: (actionCode, p0, p1, dbName, triggerOrView) =>
{
switch (actionCode)
{
// When creating a table an insert is first done.
case ActionCode.Insert:
Assert.Equal(p0, "sqlite_master");
Assert.Null(p1);
Assert.Equal(dbName, "main");
Assert.Null(triggerOrView);
break;
case ActionCode.CreateTable:
Assert.Equal(p0, "foo");
Assert.Null(p1);
Assert.Equal(dbName, "main");
Assert.Null(triggerOrView);
break;
case ActionCode.Read:
Assert.NotNull(p0);
Assert.NotNull(p1);
Assert.Equal(dbName, "main");
Assert.Null(triggerOrView);
break;
}
return AuthorizerReturnCode.Ok;
});
using (var db = builder.Build())
{
db.ExecuteAll(
@"CREATE TABLE foo (x int);
SELECT * FROM foo;
CREATE VIEW TEST_VIEW AS SELECT * FROM foo;");
}
// View authorizer
builder = builder.With(authorizer: (actionCode, p0, p1, dbName, triggerOrView) =>
{
switch (actionCode)
{
case ActionCode.Read:
Assert.NotNull(p0);
Assert.NotNull(p1);
Assert.Equal(dbName, "main");
// A Hack. Goal is to prove that inner_most_trigger_or_view is not null when it is returned in the callback
if (p0 == "foo") { Assert.NotNull(triggerOrView); }
break;
}
return AuthorizerReturnCode.Ok;
});
using (var db = builder.Build())
{
db.Execute("SELECT * FROM TEST_VIEW;");
}
// Denied authorizer
builder = builder.With(authorizer: (actionCode, p0, p1, dbName, triggerOrView) => AuthorizerReturnCode.Deny);
using (var db = builder.Build())
{
try
{
db.Execute("SELECT * FROM TEST_VIEW;");
Assert.True(false);
}
catch (SQLiteException e)
{
Assert.Equal(e.ErrorCode, ErrorCode.NotAuthorized);
}
}
builder = builder.Without(authorizer: true);
using (var db = builder.Build())
{
db.Execute("SELECT * FROM TEST_VIEW;");
}
raw.sqlite3__vfs__delete(null, tmpFile, 1);
}
[Fact]
public void TestStatus()
{
using (var db = SQLite3.OpenInMemory())
{
int current;
int highwater;
db.Status(DatabaseConnectionStatusCode.CacheUsed, out current, out highwater, false);
Assert.True(current > 0);
Assert.Equal(highwater, 0);
}
}
[Fact]
public void TestVacuum()
{
using (var db = SQLite3.OpenInMemory())
{
// VACUUM can't be called during a transaction so its a good negative confirmation test.
Assert.Throws<SQLiteException>(() => db.RunInTransaction(tdb => tdb.Vacuum()));
db.Vacuum();
}
}
[Fact]
public void TestTransaction()
{
using (var db = SQLite3.OpenInMemory())
{
var result = db.RunInTransaction(tdb =>
{
tdb.RunInTransaction(_tdb => _tdb.Execute("CREATE TABLE foo (x int);"));
tdb.TryRunInTransaction(_tdb =>
{
_tdb.Execute("INSERT INTO foo (x) VALUES (1);");
_tdb.Execute("INSERT INTO foo (x) VALUES (2);");
_tdb.Execute("INSERT INTO foo (x) VALUES (3);");
});
Assert.Equal(tdb.Query("SELECT * FROM foo").SelectScalarInt().ToList(), new int[]{ 1, 2, 3 });
var failedResult = tdb.TryRunInTransaction(_tdb =>
{
_tdb.Execute("INSERT INTO foo (x) VALUES (1);");
_tdb.Execute("INSERT INTO foo (x) VALUES (2);");
_tdb.Execute("INSERT INTO foo (x) VALUES (3);");
throw new Exception();
});
Assert.False(failedResult);
Assert.Equal(tdb.Query("SELECT * FROM foo").SelectScalarInt().ToList(), new int[]{ 1, 2, 3 });
string successResult;
if(tdb.TryRunInTransaction(_tdb =>
{
_tdb.Execute("INSERT INTO foo (x) VALUES (1);");
_tdb.Execute("INSERT INTO foo (x) VALUES (2);");
_tdb.Execute("INSERT INTO foo (x) VALUES (3);");
return "SUCCESS";
}, out successResult))
{
Assert.Equal(successResult, "SUCCESS");
}
else
{
Assert.True(false, "expect the transaction to succeed");
}
return "SUCCESS";
});
Assert.Equal(result, "SUCCESS");
db.RunInTransaction(_ => {}, TransactionMode.Exclusive);
db.RunInTransaction(_ => {}, TransactionMode.Immediate);
Assert.Throws<ArgumentException>(() => db.RunInTransaction(_ => {}, (TransactionMode) int.MaxValue));
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.