context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
using System;
using System.Data;
using Csla;
using Csla.Data;
using ParentLoadSoftDelete.DataAccess;
using ParentLoadSoftDelete.DataAccess.ERCLevel;
namespace ParentLoadSoftDelete.Business.ERCLevel
{
/// <summary>
/// F05_SubContinent_Child (editable child object).<br/>
/// This is a generated base class of <see cref="F05_SubContinent_Child"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="F04_SubContinent"/> collection.
/// </remarks>
[Serializable]
public partial class F05_SubContinent_Child : BusinessBase<F05_SubContinent_Child>
{
#region State Fields
[NotUndoable]
[NonSerialized]
internal int subContinent_ID1 = 0;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="SubContinent_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> SubContinent_Child_NameProperty = RegisterProperty<string>(p => p.SubContinent_Child_Name, "Sub Continent Child Name");
/// <summary>
/// Gets or sets the Sub Continent Child Name.
/// </summary>
/// <value>The Sub Continent Child Name.</value>
public string SubContinent_Child_Name
{
get { return GetProperty(SubContinent_Child_NameProperty); }
set { SetProperty(SubContinent_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="F05_SubContinent_Child"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="F05_SubContinent_Child"/> object.</returns>
internal static F05_SubContinent_Child NewF05_SubContinent_Child()
{
return DataPortal.CreateChild<F05_SubContinent_Child>();
}
/// <summary>
/// Factory method. Loads a <see cref="F05_SubContinent_Child"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="F05_SubContinent_Child"/> object.</returns>
internal static F05_SubContinent_Child GetF05_SubContinent_Child(SafeDataReader dr)
{
F05_SubContinent_Child obj = new F05_SubContinent_Child();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
obj.MarkOld();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="F05_SubContinent_Child"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public F05_SubContinent_Child()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="F05_SubContinent_Child"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="F05_SubContinent_Child"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(SubContinent_Child_NameProperty, dr.GetString("SubContinent_Child_Name"));
// parent properties
subContinent_ID1 = dr.GetInt32("SubContinent_ID1");
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="F05_SubContinent_Child"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(F04_SubContinent parent)
{
using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
OnInsertPre(args);
var dal = dalManager.GetProvider<IF05_SubContinent_ChildDal>();
using (BypassPropertyChecks)
{
dal.Insert(
parent.SubContinent_ID,
SubContinent_Child_Name
);
}
OnInsertPost(args);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="F05_SubContinent_Child"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(F04_SubContinent parent)
{
if (!IsDirty)
return;
using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
OnUpdatePre(args);
var dal = dalManager.GetProvider<IF05_SubContinent_ChildDal>();
using (BypassPropertyChecks)
{
dal.Update(
parent.SubContinent_ID,
SubContinent_Child_Name
);
}
OnUpdatePost(args);
}
}
/// <summary>
/// Self deletes the <see cref="F05_SubContinent_Child"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(F04_SubContinent parent)
{
using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
OnDeletePre(args);
var dal = dalManager.GetProvider<IF05_SubContinent_ChildDal>();
using (BypassPropertyChecks)
{
dal.Delete(parent.SubContinent_ID);
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
// 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 MinDouble()
{
var test = new SimpleBinaryOpTest__MinDouble();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Avx.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__MinDouble
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Double> _fld1;
public Vector256<Double> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__MinDouble testClass)
{
var result = Avx.Min(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__MinDouble testClass)
{
fixed (Vector256<Double>* pFld1 = &_fld1)
fixed (Vector256<Double>* pFld2 = &_fld2)
{
var result = Avx.Min(
Avx.LoadVector256((Double*)(pFld1)),
Avx.LoadVector256((Double*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Vector256<Double> _clsVar1;
private static Vector256<Double> _clsVar2;
private Vector256<Double> _fld1;
private Vector256<Double> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__MinDouble()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
}
public SimpleBinaryOpTest__MinDouble()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx.Min(
Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx.Min(
Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx.Min(
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx).GetMethod(nameof(Avx.Min), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx).GetMethod(nameof(Avx.Min), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx).GetMethod(nameof(Avx.Min), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx.Min(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<Double>* pClsVar1 = &_clsVar1)
fixed (Vector256<Double>* pClsVar2 = &_clsVar2)
{
var result = Avx.Min(
Avx.LoadVector256((Double*)(pClsVar1)),
Avx.LoadVector256((Double*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr);
var result = Avx.Min(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr));
var result = Avx.Min(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr));
var result = Avx.Min(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__MinDouble();
var result = Avx.Min(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__MinDouble();
fixed (Vector256<Double>* pFld1 = &test._fld1)
fixed (Vector256<Double>* pFld2 = &test._fld2)
{
var result = Avx.Min(
Avx.LoadVector256((Double*)(pFld1)),
Avx.LoadVector256((Double*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx.Min(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<Double>* pFld1 = &_fld1)
fixed (Vector256<Double>* pFld2 = &_fld2)
{
var result = Avx.Min(
Avx.LoadVector256((Double*)(pFld1)),
Avx.LoadVector256((Double*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx.Min(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx.Min(
Avx.LoadVector256((Double*)(&test._fld1)),
Avx.LoadVector256((Double*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<Double> op1, Vector256<Double> op2, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.DoubleToInt64Bits(Math.Min(left[0], right[0])) != BitConverter.DoubleToInt64Bits(result[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(Math.Min(left[i], right[i])) != BitConverter.DoubleToInt64Bits(result[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.Min)}<Double>(Vector256<Double>, Vector256<Double>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Messenger class.
// Copyright (C) 2009-2010 Lex Li
//
// 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.
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2009/3/29
* Time: 17:52
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Net;
using Lextm.SharpSnmpLib.Security;
namespace Lextm.SharpSnmpLib.Messaging
{
/// <summary>
/// Messenger class contains all static helper methods you need to send out SNMP messages.
/// Static methods in Manager or Agent class will be removed in the future.
/// </summary>
/// <remarks>
/// SNMP v3 is not supported by this class. Please use <see cref="ISnmpMessage" /> derived classes directly
/// if you want to do v3 operations.
/// </remarks>
public static class Messenger
{
/// <summary>
/// RFC 3416 (3.)
/// </summary>
private static readonly NumberGenerator RequestCounter = new NumberGenerator(int.MinValue, int.MaxValue);
/// <summary>
/// RFC 3412 (6.)
/// </summary>
private static readonly NumberGenerator MessageCounter = new NumberGenerator(0, int.MaxValue);
private static readonly ObjectIdentifier IdUnsupportedSecurityLevel = new ObjectIdentifier(new uint[] { 1, 3, 6, 1, 6, 3, 15, 1, 1, 1, 0 });
private static readonly ObjectIdentifier IdNotInTimeWindow = new ObjectIdentifier(new uint[] { 1, 3, 6, 1, 6, 3, 15, 1, 1, 2, 0 });
private static readonly ObjectIdentifier IdUnknownSecurityName = new ObjectIdentifier(new uint[] { 1, 3, 6, 1, 6, 3, 15, 1, 1, 3, 0 });
private static readonly ObjectIdentifier IdUnknownEngineID = new ObjectIdentifier(new uint[] { 1, 3, 6, 1, 6, 3, 15, 1, 1, 4, 0 });
private static readonly ObjectIdentifier IdAuthenticationFailure = new ObjectIdentifier(new uint[] { 1, 3, 6, 1, 6, 3, 15, 1, 1, 5, 0 });
private static readonly ObjectIdentifier IdDecryptionError = new ObjectIdentifier(new uint[] { 1, 3, 6, 1, 6, 3, 15, 1, 1, 6, 0 });
private static int _maxMessageSize = Header.MaxMessageSize;
/// <summary>
/// Gets a list of variable binds.
/// </summary>
/// <param name="version">Protocol version.</param>
/// <param name="endpoint">Endpoint.</param>
/// <param name="community">Community name.</param>
/// <param name="variables">Variable binds.</param>
/// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
/// <returns></returns>
public static IList<Variable> Get(VersionCode version, IPEndPoint endpoint, OctetString community, IList<Variable> variables, int timeout)
{
if (endpoint == null)
{
throw new ArgumentNullException("endpoint");
}
if (community == null)
{
throw new ArgumentNullException("community");
}
if (variables == null)
{
throw new ArgumentNullException("variables");
}
if (version == VersionCode.V3)
{
throw new NotSupportedException("SNMP v3 is not supported");
}
var message = new GetRequestMessage(RequestCounter.NextId, version, community, variables);
var response = message.GetResponse(timeout, endpoint);
var pdu = response.Pdu();
if (pdu.ErrorStatus.ToInt32() != 0)
{
throw ErrorException.Create(
"error in response",
endpoint.Address,
response);
}
return pdu.Variables;
}
/// <summary>
/// Sets a list of variable binds.
/// </summary>
/// <param name="version">Protocol version.</param>
/// <param name="endpoint">Endpoint.</param>
/// <param name="community">Community name.</param>
/// <param name="variables">Variable binds.</param>
/// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
/// <returns></returns>
public static IList<Variable> Set(VersionCode version, IPEndPoint endpoint, OctetString community, IList<Variable> variables, int timeout)
{
if (endpoint == null)
{
throw new ArgumentNullException("endpoint");
}
if (community == null)
{
throw new ArgumentNullException("community");
}
if (variables == null)
{
throw new ArgumentNullException("variables");
}
if (version == VersionCode.V3)
{
throw new NotSupportedException("SNMP v3 is not supported");
}
var message = new SetRequestMessage(RequestCounter.NextId, version, community, variables);
var response = message.GetResponse(timeout, endpoint);
var pdu = response.Pdu();
if (pdu.ErrorStatus.ToInt32() != 0)
{
throw ErrorException.Create(
"error in response",
endpoint.Address,
response);
}
return pdu.Variables;
}
/// <summary>
/// Walks.
/// </summary>
/// <param name="version">Protocol version.</param>
/// <param name="endpoint">Endpoint.</param>
/// <param name="community">Community name.</param>
/// <param name="table">OID.</param>
/// <param name="list">A list to hold the results.</param>
/// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
/// <param name="mode">Walk mode.</param>
/// <returns>
/// Returns row count if the OID is a table. Otherwise this value is meaningless.
/// </returns>
public static int Walk(VersionCode version, IPEndPoint endpoint, OctetString community, ObjectIdentifier table, IList<Variable> list, int timeout, WalkMode mode)
{
if (list == null)
{
throw new ArgumentNullException("list");
}
var result = 0;
var tableV = new Variable(table);
Variable seed;
var next = tableV;
var rowMask = string.Format(CultureInfo.InvariantCulture, "{0}.1.1.", table);
var subTreeMask = string.Format(CultureInfo.InvariantCulture, "{0}.", table);
do
{
seed = next;
if (seed == tableV)
{
continue;
}
if (mode == WalkMode.WithinSubtree && !seed.Id.ToString().StartsWith(subTreeMask, StringComparison.Ordinal))
{
// not in sub tree
break;
}
list.Add(seed);
if (seed.Id.ToString().StartsWith(rowMask, StringComparison.Ordinal))
{
result++;
}
}
while (HasNext(version, endpoint, community, seed, timeout, out next));
return result;
}
/// <summary>
/// Determines whether the specified seed has next item.
/// </summary>
/// <param name="version">The version.</param>
/// <param name="endpoint">The endpoint.</param>
/// <param name="community">The community.</param>
/// <param name="seed">The seed.</param>
/// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
/// <param name="next">The next.</param>
/// <returns>
/// <c>true</c> if the specified seed has next item; otherwise, <c>false</c>.
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "5#")]
private static bool HasNext(VersionCode version, IPEndPoint endpoint, OctetString community, Variable seed, int timeout, out Variable next)
{
if (seed == null)
{
throw new ArgumentNullException("seed");
}
var variables = new List<Variable> { new Variable(seed.Id) };
var message = new GetNextRequestMessage(
RequestCounter.NextId,
version,
community,
variables);
var response = message.GetResponse(timeout, endpoint);
var pdu = response.Pdu();
var errorFound = pdu.ErrorStatus.ToErrorCode() == ErrorCode.NoSuchName;
next = errorFound ? null : pdu.Variables[0];
return !errorFound;
}
/// <summary>
/// Walks.
/// </summary>
/// <param name="version">Protocol version.</param>
/// <param name="endpoint">Endpoint.</param>
/// <param name="community">Community name.</param>
/// <param name="table">OID.</param>
/// <param name="list">A list to hold the results.</param>
/// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
/// <param name="maxRepetitions">The max repetitions.</param>
/// <param name="mode">Walk mode.</param>
/// <param name="privacy">The privacy provider.</param>
/// <param name="report">The report.</param>
/// <returns></returns>
public static int BulkWalk(VersionCode version, IPEndPoint endpoint, OctetString community, ObjectIdentifier table, IList<Variable> list, int timeout, int maxRepetitions, WalkMode mode, IPrivacyProvider privacy, ISnmpMessage report)
{
if (list == null)
{
throw new ArgumentNullException("list");
}
var tableV = new Variable(table);
var seed = tableV;
IList<Variable> next;
var result = 0;
var message = report;
while (BulkHasNext(version, endpoint, community, seed, timeout, maxRepetitions, out next, privacy, ref message))
{
var subTreeMask = string.Format(CultureInfo.InvariantCulture, "{0}.", table);
var rowMask = string.Format(CultureInfo.InvariantCulture, "{0}.1.1.", table);
foreach (var v in next)
{
var id = v.Id.ToString();
if (v.Data.TypeCode == SnmpType.EndOfMibView)
{
goto end;
}
if (mode == WalkMode.WithinSubtree && !id.StartsWith(subTreeMask, StringComparison.Ordinal))
{
// not in sub tree
goto end;
}
list.Add(v);
if (id.StartsWith(rowMask, StringComparison.Ordinal))
{
result++;
}
}
seed = next[next.Count - 1];
}
end:
return result;
}
/// <summary>
/// Sends a TRAP v1 message.
/// </summary>
/// <param name="receiver">Receiver.</param>
/// <param name="agent">Agent.</param>
/// <param name="community">Community name.</param>
/// <param name="enterprise">Enterprise OID.</param>
/// <param name="generic">Generic code.</param>
/// <param name="specific">Specific code.</param>
/// <param name="timestamp">Timestamp.</param>
/// <param name="variables">Variable bindings.</param>
[CLSCompliant(false)]
public static void SendTrapV1(EndPoint receiver, IPAddress agent, OctetString community, ObjectIdentifier enterprise, GenericCode generic, int specific, uint timestamp, IList<Variable> variables)
{
var message = new TrapV1Message(VersionCode.V1, agent, community, enterprise, generic, specific, timestamp, variables);
message.Send(receiver);
}
/// <summary>
/// Sends TRAP v2 message.
/// </summary>
/// <param name="version">Protocol version.</param>
/// <param name="receiver">Receiver.</param>
/// <param name="community">Community name.</param>
/// <param name="enterprise">Enterprise OID.</param>
/// <param name="timestamp">Timestamp.</param>
/// <param name="variables">Variable bindings.</param>
/// <param name="requestId">Request ID.</param>
[CLSCompliant(false)]
public static void SendTrapV2(int requestId, VersionCode version, EndPoint receiver, OctetString community, ObjectIdentifier enterprise, uint timestamp, IList<Variable> variables)
{
if (version != VersionCode.V2)
{
throw new ArgumentException("Only SNMP v2c is supported", "version");
}
var message = new TrapV2Message(requestId, version, community, enterprise, timestamp, variables);
message.Send(receiver);
}
/// <summary>
/// Sends INFORM message.
/// </summary>
/// <param name="requestId">The request id.</param>
/// <param name="version">Protocol version.</param>
/// <param name="receiver">Receiver.</param>
/// <param name="community">Community name.</param>
/// <param name="enterprise">Enterprise OID.</param>
/// <param name="timestamp">Timestamp.</param>
/// <param name="variables">Variable bindings.</param>
/// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
/// <param name="privacy">The privacy provider.</param>
/// <param name="report">The report.</param>
[CLSCompliant(false)]
public static void SendInform(int requestId, VersionCode version, IPEndPoint receiver, OctetString community, ObjectIdentifier enterprise, uint timestamp, IList<Variable> variables, int timeout, IPrivacyProvider privacy, ISnmpMessage report)
{
if (receiver == null)
{
throw new ArgumentNullException("receiver");
}
if (community == null)
{
throw new ArgumentNullException("community");
}
if (enterprise == null)
{
throw new ArgumentNullException("enterprise");
}
if (variables == null)
{
throw new ArgumentNullException("variables");
}
if (version == VersionCode.V3 && privacy == null)
{
throw new ArgumentNullException("privacy");
}
if (version == VersionCode.V3 && report == null)
{
throw new ArgumentNullException("report");
}
var message = version == VersionCode.V3
? new InformRequestMessage(
version,
MessageCounter.NextId,
requestId,
community,
enterprise,
timestamp,
variables,
privacy,
MaxMessageSize,
report)
: new InformRequestMessage(
requestId,
version,
community,
enterprise,
timestamp,
variables);
var response = message.GetResponse(timeout, receiver);
if (response.Pdu().ErrorStatus.ToInt32() != 0)
{
throw ErrorException.Create(
"error in response",
receiver.Address,
response);
}
}
/// <summary>
/// Gets a table of variables.
/// </summary>
/// <param name="version">Protocol version.</param>
/// <param name="endpoint">Endpoint.</param>
/// <param name="community">Community name.</param>
/// <param name="table">Table OID.</param>
/// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
/// <param name="maxRepetitions">The max repetitions.</param>
/// <param name="registry">The registry.</param>
/// <returns></returns>
/// <remarks><paramref name="registry"/> can be null, which also disables table validation.</remarks>
[SuppressMessage("Microsoft.Performance", "CA1814:PreferJaggedArraysOverMultidimensional", MessageId = "Return", Justification = "ByDesign")]
[SuppressMessage("Microsoft.Performance", "CA1814:PreferJaggedArraysOverMultidimensional", MessageId = "Body", Justification = "ByDesign")]
[CLSCompliant(false)]
[Obsolete("This method only works for a few scenarios. Will provide new methods in the future. If it does not work for you, parse WALK result on your own.")]
public static Variable[,] GetTable(VersionCode version, IPEndPoint endpoint, OctetString community, ObjectIdentifier table, int timeout, int maxRepetitions, IObjectRegistry registry)
{
if (version == VersionCode.V3)
{
throw new NotSupportedException("SNMP v3 is not supported");
}
var canContinue = registry == null || registry.ValidateTable(table);
if (!canContinue)
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "not a table OID: {0}", table));
}
IList<Variable> list = new List<Variable>();
var rows = version == VersionCode.V1 ? Walk(version, endpoint, community, table, list, timeout, WalkMode.WithinSubtree) : BulkWalk(version, endpoint, community, table, list, timeout, maxRepetitions, WalkMode.WithinSubtree, null, null);
if (rows == 0)
{
return new Variable[0, 0];
}
var cols = list.Count / rows;
var k = 0;
var result = new Variable[rows, cols];
for (var j = 0; j < cols; j++)
{
for (var i = 0; i < rows; i++)
{
result[i, j] = list[k];
k++;
}
}
return result;
}
/// <summary>
/// Gets the request counter.
/// </summary>
/// <value>The request counter.</value>
public static int NextRequestId
{
get { return RequestCounter.NextId; }
}
/// <summary>
/// Gets the message counter.
/// </summary>
/// <value>The message counter.</value>
public static int NextMessageId
{
get { return MessageCounter.NextId; }
}
/// <summary>
/// Max message size used in #SNMP.
/// </summary>
/// <remarks>
/// You can use any value for your own application.
/// Also this value may be changed in #SNMP in future releases.
/// </remarks>
public static int MaxMessageSize
{
get { return _maxMessageSize; }
set { _maxMessageSize = value; }
}
/// <summary>
/// Returns a new discovery request.
/// </summary>
/// <returns></returns>
[Obsolete("Please use GetNextDiscovery")]
public static Discovery NextDiscovery
{
get { return new Discovery(NextMessageId, NextRequestId, MaxMessageSize); }
}
/// <summary>
/// If the privacy module returns failure, then the message can
/// not be processed, so the usmStatsDecryptionErrors counter is
/// incremented and an error indication (decryptionError) together
/// with the OID and value of the incremented counter is returned
/// to the calling module.
/// </summary>
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1650:ElementDocumentationMustBeSpelledCorrectly", Justification = "Reviewed. Suppression is OK here.")]
public static ObjectIdentifier DecryptionError
{
get { return IdDecryptionError; }
}
/// <summary>
/// If the authentication module returns failure, then the message
/// cannot be trusted, so the usmStatsWrongDigests counter is
/// incremented and an error indication (authenticationFailure)
/// together with the OID and value of the incremented counter is
/// returned to the calling module.
/// </summary>
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1650:ElementDocumentationMustBeSpelledCorrectly", Justification = "Reviewed. Suppression is OK here.")]
public static ObjectIdentifier AuthenticationFailure
{
get { return IdAuthenticationFailure; }
}
/// <summary>
/// If the value of the msgAuthoritativeEngineID field in the
/// securityParameters is unknown then
/// the usmStatsUnknownEngineIDs counter is incremented, and an
/// error indication (unknownEngineID) together with the OID and
/// value of the incremented counter is returned to the calling
/// module.
/// </summary>
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1650:ElementDocumentationMustBeSpelledCorrectly", Justification = "Reviewed. Suppression is OK here.")]
public static ObjectIdentifier UnknownEngineId
{
get { return IdUnknownEngineID; }
}
/// <summary>
/// Information about the value of the msgUserName and
/// msgAuthoritativeEngineID fields is extracted from the Local
/// Configuration Datastore (LCD, usmUserTable). If no information
/// is available for the user, then the usmStatsUnknownUserNames
/// counter is incremented and an error indication
/// (unknownSecurityName) together with the OID and value of the
/// incremented counter is returned to the calling module.
/// </summary>
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1650:ElementDocumentationMustBeSpelledCorrectly", Justification = "Reviewed. Suppression is OK here.")]
public static ObjectIdentifier UnknownSecurityName
{
get { return IdUnknownSecurityName; }
}
/// <summary>
/// If the message is considered to be outside of the Time Window
/// then the usmStatsNotInTimeWindows counter is incremented and
/// an error indication (notInTimeWindow) together with the OID,
/// the value of the incremented counter, and an indication that
/// the error must be reported with a securityLevel of authNoPriv,
/// is returned to the calling module
/// </summary>
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1650:ElementDocumentationMustBeSpelledCorrectly", Justification = "Reviewed. Suppression is OK here.")]
public static ObjectIdentifier NotInTimeWindow
{
get { return IdNotInTimeWindow; }
}
/// <summary>
/// If the information about the user indicates that it does not
/// support the securityLevel requested by the caller, then the
/// usmStatsUnsupportedSecLevels counter is incremented and an error
/// indication (unsupportedSecurityLevel) together with the OID and
/// value of the incremented counter is returned to the calling
/// module.
/// </summary>
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1650:ElementDocumentationMustBeSpelledCorrectly", Justification = "Reviewed. Suppression is OK here.")]
public static ObjectIdentifier UnsupportedSecurityLevel
{
get { return IdUnsupportedSecurityLevel; }
}
/// <summary>
/// Returns a new discovery request.
/// </summary>
/// <param name="type">Message type.</param>
/// <returns></returns>
public static Discovery GetNextDiscovery(SnmpType type)
{
return new Discovery(NextMessageId, NextRequestId, MaxMessageSize, type);
}
/// <summary>
/// Determines whether the specified seed has next item.
/// </summary>
/// <param name="version">The version.</param>
/// <param name="receiver">The receiver.</param>
/// <param name="community">The community.</param>
/// <param name="seed">The seed.</param>
/// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
/// <param name="maxRepetitions">The max repetitions.</param>
/// <param name="next">The next.</param>
/// <param name="privacy">The privacy provider.</param>
/// <param name="report">The report.</param>
/// <returns>
/// <c>true</c> if the specified seed has next item; otherwise, <c>false</c>.
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "5#")]
private static bool BulkHasNext(VersionCode version, IPEndPoint receiver, OctetString community, Variable seed, int timeout, int maxRepetitions, out IList<Variable> next, IPrivacyProvider privacy, ref ISnmpMessage report)
{
if (version == VersionCode.V1)
{
throw new ArgumentException("v1 is not supported", "version");
}
var variables = new List<Variable> { new Variable(seed.Id) };
var request = version == VersionCode.V3
? new GetBulkRequestMessage(
version,
MessageCounter.NextId,
RequestCounter.NextId,
community,
0,
maxRepetitions,
variables,
privacy,
MaxMessageSize,
report)
: new GetBulkRequestMessage(
RequestCounter.NextId,
version,
community,
0,
maxRepetitions,
variables);
var reply = request.GetResponse(timeout, receiver);
if (reply is ReportMessage)
{
if (reply.Pdu().Variables.Count == 0)
{
// TODO: whether it is good to return?
next = new List<Variable>(0);
return false;
}
var id = reply.Pdu().Variables[0].Id;
if (id != IdNotInTimeWindow)
{
// var error = id.GetErrorMessage();
// TODO: whether it is good to return?
next = new List<Variable>(0);
return false;
}
// according to RFC 3414, send a second request to sync time.
request = new GetBulkRequestMessage(
version,
MessageCounter.NextId,
RequestCounter.NextId,
community,
0,
maxRepetitions,
variables,
privacy,
MaxMessageSize,
reply);
reply = request.GetResponse(timeout, receiver);
}
else if (reply.Pdu().ErrorStatus.ToInt32() != 0)
{
throw ErrorException.Create(
"error in response",
receiver.Address,
reply);
}
next = reply.Pdu().Variables;
report = request;
return next.Count != 0;
}
/// <summary>
/// Returns error message for the specific <see cref="ObjectIdentifier"/>.
/// </summary>
/// <param name="id">The OID.</param>
/// <returns>Error message.</returns>
public static string GetErrorMessage(this ObjectIdentifier id)
{
if (id == IdUnsupportedSecurityLevel)
{
return "unsupported security level";
}
if (id == IdNotInTimeWindow)
{
return "not in time window";
}
if (id == IdUnknownSecurityName)
{
return "unknown security name";
}
if (id == IdUnknownEngineID)
{
return "unknown engine ID";
}
if (id == IdAuthenticationFailure)
{
return "authentication failure";
}
if (id == IdDecryptionError)
{
return "decryption error";
}
return "unknown error";
}
}
}
| |
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
namespace SIL.Windows.Forms
{
/// ------------------------------------------------------------------------------------
/// <summary>
/// Possible painting states for DrawHotBackground
/// </summary>
/// ------------------------------------------------------------------------------------
public enum PaintState
{
Normal,
Hot,
HotDown,
}
/// ----------------------------------------------------------------------------------------
/// <summary>
/// Contains misc. static methods for various customized painting.
/// </summary>
/// ----------------------------------------------------------------------------------------
public class PaintingHelper
{
#region OS-specific stuff
#if !__MonoCS__
[DllImport("User32.dll")]
extern static public IntPtr GetWindowDC(IntPtr hwnd);
#else
static public IntPtr GetWindowDC(IntPtr hwnd)
{
Console.WriteLine("Warning--using unimplemented method GetWindowDC"); // FIXME Linux
return(IntPtr.Zero);
}
#endif
#if !__MonoCS__
[DllImport("User32.dll")]
extern static public int ReleaseDC(IntPtr hwnd, IntPtr hdc);
#else
static public int ReleaseDC(IntPtr hwnd, IntPtr hdc)
{
Console.WriteLine("Warning--using unimplemented method ReleaseDC"); // FIXME Linux
return(-1);
}
#endif
#if !__MonoCS__
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr GetParent(IntPtr hWnd);
#else
public static IntPtr GetParent(IntPtr hWnd)
{
Console.WriteLine("Warning--using unimplemented method GetParent"); // FIXME Linux
return(IntPtr.Zero);
}
#endif
#endregion
public static int WM_NCPAINT = 0x85;
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns a darkened version of the specified image.
/// </summary>
/// ------------------------------------------------------------------------------------
public static Image MakeHotImage(Image img)
{
if (img == null)
return null;
float[][] colorMatrixElements =
{
new[] {0.6f, 0, 0, 0, 0},
new[] {0, 0.6f, 0, 0, 0},
new[] {0, 0, 0.6f, 0, 0},
new[] {0, 0, 0, 1f, 0},
new[] {0.1f, 0.1f, 0.1f, 0, 1}
};
img = img.Clone() as Image;
using (var imgattr = new ImageAttributes())
using (var g = Graphics.FromImage(img))
{
var cm = new ColorMatrix(colorMatrixElements);
var rc = new Rectangle(0, 0, img.Width, img.Height);
imgattr.SetColorMatrix(cm);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(img, rc, 0, 0, img.Width, img.Height, GraphicsUnit.Pixel, imgattr);
return img;
}
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Draws around the specified control, a fixed single border the color of text
/// boxes in a themed environment. If themes are not enabled, the border is black.
/// </summary>
/// ------------------------------------------------------------------------------------
public static void DrawCustomBorder(Control ctrl)
{
DrawCustomBorder(ctrl, CanPaintVisualStyle() ?
VisualStyleInformation.TextControlBorder : Color.Black);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Draws around the specified control, a fixed single border of the specified color.
/// </summary>
/// ------------------------------------------------------------------------------------
public static void DrawCustomBorder(Control ctrl, Color clrBorder)
{
if (Environment.OSVersion.Platform == PlatformID.Unix || Environment.OSVersion.Platform == PlatformID.MacOSX) {
// FIXME Linux - is custom border needed on Linux?
} else { // Windows
IntPtr hdc = GetWindowDC(ctrl.Handle);
if (hdc != IntPtr.Zero) {
using (Graphics g = Graphics.FromHdc(hdc))
{
Rectangle rc = new Rectangle(0, 0, ctrl.Width, ctrl.Height);
ControlPaint.DrawBorder(g, rc, clrBorder, ButtonBorderStyle.Solid);
}
ReleaseDC(ctrl.Handle, hdc);
}
}
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Draws a background in the specified rectangle that looks like a toolbar button
/// when the mouse is over it, with consideration for whether the look should be like
/// the mouse is down or not. Note, when a PaintState of normal is specified, this
/// method does nothing. Normal background painting is up to the caller.
/// </summary>
/// ------------------------------------------------------------------------------------
public static void DrawHotBackground(Graphics g, Rectangle rc, PaintState state)
{
// The caller has to handle painting when the state is normal.
if (state == PaintState.Normal)
return;
var hotDown = (state == PaintState.HotDown);
var clr1 = (hotDown ? ProfessionalColors.ButtonPressedGradientBegin :
ProfessionalColors.ButtonSelectedGradientBegin);
var clr2 = (hotDown ? ProfessionalColors.ButtonPressedGradientEnd :
ProfessionalColors.ButtonSelectedGradientEnd);
using (var br = new LinearGradientBrush(rc, clr1, clr2, 90))
g.FillRectangle(br, rc);
var clrBrdr = (hotDown ? ProfessionalColors.ButtonPressedHighlightBorder :
ProfessionalColors.ButtonSelectedHighlightBorder);
ControlPaint.DrawBorder(g, rc, clrBrdr, ButtonBorderStyle.Solid);
//// Determine the highlight color.
//Color clrHot = (CanPaintVisualStyle() ?
// VisualStyleInformation.ControlHighlightHot : SystemColors.MenuHighlight);
//int alpha = (CanPaintVisualStyle() ? 95 : 120);
//// Determine the angle and one of the colors for the gradient highlight. When state is
//// hot down, the gradiant goes from bottom (lighter) to top (darker). When the state
//// is just hot, the gradient is from top (lighter) to bottom (darker).
//float angle = (state == PaintState.HotDown ? 270 : 90);
//Color clr2 = ColorHelper.CalculateColor(Color.White, clrHot, alpha);
//// Draw the label's background.
//if (state == PaintState.Hot)
//{
// using (LinearGradientBrush br = new LinearGradientBrush(rc, Color.White, clr2, angle))
// g.FillRectangle(br, rc);
//}
//else
//{
// using (LinearGradientBrush br = new LinearGradientBrush(rc, clr2, clrHot, angle))
// g.FillRectangle(br, rc);
//}
//// Draw a black border around the label.
//ControlPaint.DrawBorder(g, rc, Color.Black, ButtonBorderStyle.Solid);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns a value indicating whether or not visual style rendering is supported
/// in the application and if the specified element can be rendered.
/// </summary>
/// ------------------------------------------------------------------------------------
public static bool CanPaintVisualStyle(VisualStyleElement element)
{
return (CanPaintVisualStyle() && VisualStyleRenderer.IsElementDefined(element));
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns a value indicating whether or not visual style rendering is supported
/// in the application.
/// </summary>
/// ------------------------------------------------------------------------------------
public static bool CanPaintVisualStyle()
{
return (Application.VisualStyleState != VisualStyleState.NoneEnabled &&
VisualStyleInformation.IsSupportedByOS &&
VisualStyleInformation.IsEnabledByUser &&
VisualStyleRenderer.IsSupported);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Because the popup containers forces a little padding above and below, we need to get
/// the popup's parent (which is the popup container) and paint its background to match
/// the menu color.
/// </summary>
/// ------------------------------------------------------------------------------------
public static Graphics PaintDropDownContainer(IntPtr hwnd, bool returnGraphics)
{
var hwndParent = GetParent(hwnd);
var g = Graphics.FromHwnd(hwndParent);
var rc = g.VisibleClipBounds;
rc.Inflate(-1, -1);
g.FillRectangle(SystemBrushes.Menu, rc);
if (!returnGraphics)
{
g.Dispose();
g = null;
}
return g;
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Fills the specified rectangle with a gradient background consistent with the
/// current system's color scheme.
/// </summary>
/// ------------------------------------------------------------------------------------
public static void DrawGradientBackground(Graphics g, Rectangle rc)
{
DrawGradientBackground(g, rc, false);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Fills the specified rectangle with a gradient background consistent with the
/// current system's color scheme.
/// </summary>
/// ------------------------------------------------------------------------------------
public static void DrawGradientBackground(Graphics g, Rectangle rc, bool makeDark)
{
Color clrTop;
Color clrBottom;
if (makeDark)
{
clrTop = ColorHelper.CalculateColor(Color.White,
SystemColors.ActiveCaption, 70);
clrBottom = ColorHelper.CalculateColor(SystemColors.ActiveCaption,
SystemColors.ActiveCaption, 0);
}
else
{
clrTop = ColorHelper.CalculateColor(Color.White,
SystemColors.GradientActiveCaption, 190);
clrBottom = ColorHelper.CalculateColor(SystemColors.ActiveCaption,
SystemColors.GradientActiveCaption, 50);
}
DrawGradientBackground(g, rc, clrTop, clrBottom);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Fills the specified rectangle with a gradient background using the specified
/// colors.
/// </summary>
/// ------------------------------------------------------------------------------------
public static void DrawGradientBackground(Graphics g, Rectangle rc, Color clrTop, Color clrBottom)
{
try
{
if (rc.Width > 0 && rc.Height > 0)
{
// Use 89 degrees here instead of 90 because otherwise I noticed sometimes
// the first row of pixels at the top of the rectangle would be painted with
// the gradient's bottom color. This was noticed when painting in a
// DataGridView and I think the problem only manifested itself when the
// height of the rectangle exceeded a certain amount (which I did not
// determine).
using (var br = new LinearGradientBrush(rc, clrTop, clrBottom, 89))
g.FillRectangle(br, rc);
}
}
catch { }
}
/// ------------------------------------------------------------------------------------
public static void DrawGradientBackground(Graphics g, Rectangle rc, Color clrTop,
Color clrBottom, bool useDefaultBlend)
{
if (rc.Width <= 0 || rc.Height <= 0)
return;
if (!useDefaultBlend)
DrawGradientBackground(g, rc, clrTop, clrBottom);
else
{
var blend = new Blend();
blend.Positions = new[] { 0.0f, 0.25f, 1.0f };
blend.Factors = new[] { 0.3f, 0.1f, 1.0f };
DrawGradientBackground(g, rc, clrTop, clrBottom, blend);
}
}
/// ------------------------------------------------------------------------------------
public static void DrawGradientBackground(Graphics g, Rectangle rc, Color clrTop,
Color clrBottom, Blend blend)
{
if (rc.Width <= 0 || rc.Height <= 0)
return;
// Use 89 degrees here instead of 90 because otherwise I noticed sometimes
// the first row of pixels at the top of the rectangle would be painted with
// the gradient's bottom color. This was noticed when painting in a
// DataGridView and I think the problem only manifested itself when the
// height of the rectangle exceeded a certain amount (which I did not
// determine).
using (var br = new LinearGradientBrush(rc, clrTop, clrBottom, 89))
{
br.Blend = blend;
g.FillRectangle(br, rc);
}
}
}
/// ----------------------------------------------------------------------------------------
public class NoToolStripBorderRenderer : ToolStripProfessionalRenderer
{
protected override void OnRenderToolStripBorder(ToolStripRenderEventArgs e)
{
// Eat this event.
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.MirrorSequences
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Models;
/// <summary>
/// A sample API that uses a petstore as an example to demonstrate
/// features in the swagger-2.0 specification
/// </summary>
public partial class SequenceRequestResponseTest : ServiceClient<SequenceRequestResponseTest>, ISequenceRequestResponseTest
{
/// <summary>
/// The base URI of the service.
/// </summary>
public Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Initializes a new instance of the SequenceRequestResponseTest class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public SequenceRequestResponseTest(params DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the SequenceRequestResponseTest class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public SequenceRequestResponseTest(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the SequenceRequestResponseTest class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public SequenceRequestResponseTest(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the SequenceRequestResponseTest class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public SequenceRequestResponseTest(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.BaseUri = new Uri("http://petstore.swagger.wordnik.com/api");
SerializationSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
}
/// <summary>
/// Creates a new pet in the store. Duplicates are allowed
/// </summary>
/// <param name='pets'>
/// Pets to add to the store
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<IList<Pet>>> AddPetWithHttpMessagesAsync(IList<Pet> pets, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (pets == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "pets");
}
if (pets != null)
{
foreach (var element in pets)
{
if (element != null)
{
element.Validate();
}
}
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("pets", pets);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "AddPet", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pets").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
_requestContent = SafeJsonConvert.SerializeObject(pets, this.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorModelException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorModel _errorBody = SafeJsonConvert.DeserializeObject<ErrorModel>(_responseContent, this.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<IList<Pet>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<IList<Pet>>(_responseContent, this.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Adds new pet stylesin the store. Duplicates are allowed
/// </summary>
/// <param name='petStyle'>
/// Pet style to add to the store
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<IList<int?>>> AddPetStylesWithHttpMessagesAsync(IList<int?> petStyle, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (petStyle == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "petStyle");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("petStyle", petStyle);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "AddPetStyles", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "primitives").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
_requestContent = SafeJsonConvert.SerializeObject(petStyle, this.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
IList<ErrorModel> _errorBody = SafeJsonConvert.DeserializeObject<IList<ErrorModel>>(_responseContent, this.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<IList<int?>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<IList<int?>>(_responseContent, this.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Updates new pet stylesin the store. Duplicates are allowed
/// </summary>
/// <param name='petStyle'>
/// Pet style to add to the store
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<IList<int?>>> UpdatePetStylesWithHttpMessagesAsync(IList<int?> petStyle, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (petStyle == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "petStyle");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("petStyle", petStyle);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "UpdatePetStyles", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "primitives").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
_requestContent = SafeJsonConvert.SerializeObject(petStyle, this.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
IList<ErrorModel> _errorBody = SafeJsonConvert.DeserializeObject<IList<ErrorModel>>(_responseContent, this.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<IList<int?>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<IList<int?>>(_responseContent, this.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
/*
* Copyright (C) 2007-2008, Jeff Thompson
*
* 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 copyright holder 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;
using System.Collections.Generic;
namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
{
public interface IUnifiable
{
IEnumerable<bool> unify(object arg);
void addUniqueVariables(List<Variable> variableSet);
object makeCopy(Variable.CopyStore copyStore);
bool termEqual(object term);
bool ground();
}
/// <summary>
/// A Variable is passed to a function so that it can be unified with
/// value or another Variable. See getValue and unify for details.
/// </summary>
public class Variable : IUnifiable
{
// Use _isBound separate from _value so that it can be bound to any value,
// including null.
private bool _isBound = false;
private object _value;
/// <summary>
/// If this Variable is unbound, then just return this Variable.
/// Otherwise, if this has been bound to a value with unify, return the value.
/// If the bound value is another Variable, this follows the "variable chain"
/// to the end and returns the final value, or the final Variable if it is unbound.
/// For more details, see http://yieldprolog.sourceforge.net/tutorial1.html
/// </summary>
/// <returns></returns>
public object getValue()
{
if (!_isBound)
return this;
object result = _value;
while (result is Variable)
{
if (!((Variable)result)._isBound)
return result;
// Keep following the Variable chain.
result = ((Variable)result)._value;
}
return result;
}
/// <summary>
/// If this Variable is bound, then just call YP.unify to unify this with arg.
/// (Note that if arg is an unbound Variable, then YP.unify will bind it to
/// this Variable's value.)
/// Otherwise, bind this Variable to YP.getValue(arg) and yield once. After the
/// yield, return this Variable to the unbound state.
/// For more details, see http://yieldprolog.sourceforge.net/tutorial1.html
/// </summary>
/// <param name="arg"></param>
/// <returns></returns>
public IEnumerable<bool> unify(object arg)
{
if (!_isBound)
{
_value = YP.getValue(arg);
if (_value == this)
// We are unifying this unbound variable with itself, so leave it unbound.
yield return false;
else
{
_isBound = true;
try
{
yield return false;
}
finally
{
// Remove the binding.
_isBound = false;
}
}
}
else
{
// disable warning on l1, don't see how we can
// code this differently
#pragma warning disable 0168, 0219
foreach (bool l1 in YP.unify(this, arg))
yield return false;
#pragma warning restore 0168, 0219
}
}
public override string ToString()
{
object value = getValue();
if (value == this)
return "_Variable";
else
return getValue().ToString();
}
/// <summary>
/// If bound, call YP.addUniqueVariables on the value. Otherwise, if this unbound
/// variable is not already in variableSet, add it.
/// </summary>
/// <param name="variableSet"></param>
public void addUniqueVariables(List<Variable> variableSet)
{
if (_isBound)
YP.addUniqueVariables(getValue(), variableSet);
else
{
if (variableSet.IndexOf(this) < 0)
variableSet.Add(this);
}
}
/// <summary>
/// If bound, return YP.makeCopy for the value, else return copyStore.getCopy(this).
/// However, if copyStore is null, just return this.
/// </summary>
/// <param name="copyStore"></param>
/// <returns></returns>
public object makeCopy(Variable.CopyStore copyStore)
{
if (_isBound)
return YP.makeCopy(getValue(), copyStore);
else
return copyStore == null ? this : copyStore.getCopy(this);
}
public bool termEqual(object term)
{
if (_isBound)
return YP.termEqual(getValue(), term);
else
return this == YP.getValue(term);
}
public bool ground()
{
if (_isBound)
// This is usually called by YP.ground which already did getValue, so this
// should never be reached, but check anyway.
return YP.ground(getValue());
else
return false;
}
/// <summary>
/// A CopyStore is used by makeCopy to track which Variable objects have
/// been copied.
/// </summary>
public class CopyStore
{
private List<Variable> _inVariableSet = new List<Variable>();
private List<Variable> _outVariableSet = new List<Variable>();
/// <summary>
/// If inVariable has already been copied, return its copy. Otherwise,
/// return a fresh Variable associated with inVariable.
/// </summary>
/// <param name="inVariable"></param>
/// <returns></returns>
public Variable getCopy(Variable inVariable)
{
int index = _inVariableSet.IndexOf(inVariable);
if (index >= 0)
return _outVariableSet[index];
else
{
Variable outVariable = new Variable();
_inVariableSet.Add(inVariable);
_outVariableSet.Add(outVariable);
return outVariable;
}
}
/// <summary>
/// Return the number of unique variables that have been copied.
/// </summary>
/// <returns></returns>
public int getNUniqueVariables()
{
return _inVariableSet.Count;
}
}
}
}
| |
// 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.
//
using System;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
namespace System.Text
{
// Encodes text into and out of UTF-32. UTF-32 is a way of writing
// Unicode characters with a single storage unit (32 bits) per character,
//
// The UTF-32 byte order mark is simply the Unicode byte order mark
// (0x00FEFF) written in UTF-32 (0x0000FEFF or 0xFFFE0000). The byte order
// mark is used mostly to distinguish UTF-32 text from other encodings, and doesn't
// switch the byte orderings.
public sealed class UTF32Encoding : Encoding
{
/*
words bits UTF-32 representation
----- ---- -----------------------------------
1 16 00000000 00000000 xxxxxxxx xxxxxxxx
2 21 00000000 000xxxxx hhhhhhll llllllll
----- ---- -----------------------------------
Surrogate:
Real Unicode value = (HighSurrogate - 0xD800) * 0x400 + (LowSurrogate - 0xDC00) + 0x10000
*/
// Used by Encoding.UTF32/BigEndianUTF32 for lazy initialization
// The initialization code will not be run until a static member of the class is referenced
internal static readonly UTF32Encoding s_default = new UTF32Encoding(bigEndian: false, byteOrderMark: true);
internal static readonly UTF32Encoding s_bigEndianDefault = new UTF32Encoding(bigEndian: true, byteOrderMark: true);
private bool _emitUTF32ByteOrderMark = false;
private bool _isThrowException = false;
private bool _bigEndian = false;
public UTF32Encoding() : this(false, true, false)
{
}
public UTF32Encoding(bool bigEndian, bool byteOrderMark) :
this(bigEndian, byteOrderMark, false)
{
}
public UTF32Encoding(bool bigEndian, bool byteOrderMark, bool throwOnInvalidCharacters) :
base(bigEndian ? 12001 : 12000)
{
_bigEndian = bigEndian;
_emitUTF32ByteOrderMark = byteOrderMark;
_isThrowException = throwOnInvalidCharacters;
// Encoding constructor already did this, but it'll be wrong if we're throwing exceptions
if (_isThrowException)
SetDefaultFallbacks();
}
internal override void SetDefaultFallbacks()
{
// For UTF-X encodings, we use a replacement fallback with an empty string
if (_isThrowException)
{
this.encoderFallback = EncoderFallback.ExceptionFallback;
this.decoderFallback = DecoderFallback.ExceptionFallback;
}
else
{
this.encoderFallback = new EncoderReplacementFallback("\xFFFD");
this.decoderFallback = new DecoderReplacementFallback("\xFFFD");
}
}
// The following methods are copied from EncodingNLS.cs.
// Unfortunately EncodingNLS.cs is internal and we're public, so we have to re-implement them here.
// These should be kept in sync for the following classes:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// Returns the number of bytes required to encode a range of characters in
// a character array.
//
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
public override unsafe int GetByteCount(char[] chars, int index, int count)
{
// Validate input parameters
if (chars == null)
throw new ArgumentNullException("chars", SR.ArgumentNull_Array);
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum);
if (chars.Length - index < count)
throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer);
Contract.EndContractBlock();
// If no input, return 0, avoid fixed empty array problem
if (count == 0)
return 0;
// Just call the pointer version
fixed (char* pChars = chars)
return GetByteCount(pChars + index, count, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
public override unsafe int GetByteCount(String s)
{
// Validate input
if (s==null)
throw new ArgumentNullException("s");
Contract.EndContractBlock();
fixed (char* pChars = s)
return GetByteCount(pChars, s.Length, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
[CLSCompliant(false)]
public override unsafe int GetByteCount(char* chars, int count)
{
// Validate Parameters
if (chars == null)
throw new ArgumentNullException("chars", SR.ArgumentNull_Array);
if (count < 0)
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
// Call it with empty encoder
return GetByteCount(chars, count, null);
}
// Parent method is safe.
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
public override unsafe int GetBytes(String s, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
if (s == null || bytes == null)
throw new ArgumentNullException((s == null ? "s" : "bytes"), SR.ArgumentNull_Array);
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
if (s.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException("s", SR.ArgumentOutOfRange_IndexCount);
if (byteIndex < 0 || byteIndex > bytes.Length)
throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index);
Contract.EndContractBlock();
int byteCount = bytes.Length - byteIndex;
// Fix our input array if 0 length because fixed doesn't like 0 length arrays
if (bytes.Length == 0)
bytes = new byte[1];
fixed (char* pChars = s) fixed (byte* pBytes = &bytes[0])
return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null);
}
// 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.
//
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
public override unsafe int GetBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
// Validate parameters
if (chars == null || bytes == null)
throw new ArgumentNullException((chars == null ? "chars" : "bytes"), SR.ArgumentNull_Array);
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
if (chars.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer);
if (byteIndex < 0 || byteIndex > bytes.Length)
throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index);
Contract.EndContractBlock();
// If nothing to encode return 0, avoid fixed problem
if (charCount == 0)
return 0;
// Just call pointer version
int byteCount = bytes.Length - byteIndex;
// Fix our input array if 0 length because fixed doesn't like 0 length arrays
if (bytes.Length == 0)
bytes = new byte[1];
fixed (char* pChars = chars) fixed (byte* pBytes = &bytes[0])
// Remember that byteCount is # to decode, not size of array.
return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
[CLSCompliant(false)]
public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
{
// Validate Parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array);
if (charCount < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
return GetBytes(chars, charCount, bytes, byteCount, null);
}
// Returns the number of characters produced by decoding a range of bytes
// in a byte array.
//
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
public override unsafe int GetCharCount(byte[] bytes, int index, int count)
{
// Validate Parameters
if (bytes == null)
throw new ArgumentNullException("bytes", SR.ArgumentNull_Array);
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum);
if (bytes.Length - index < count)
throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer);
Contract.EndContractBlock();
// If no input just return 0, fixed doesn't like 0 length arrays.
if (count == 0)
return 0;
// Just call pointer version
fixed (byte* pBytes = bytes)
return GetCharCount(pBytes + index, count, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
[CLSCompliant(false)]
public override unsafe int GetCharCount(byte* bytes, int count)
{
// Validate Parameters
if (bytes == null)
throw new ArgumentNullException("bytes", SR.ArgumentNull_Array);
if (count < 0)
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
return GetCharCount(bytes, count, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex)
{
// Validate Parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array);
if (byteIndex < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((byteIndex < 0 ? "byteIndex" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
if ( bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer);
if (charIndex < 0 || charIndex > chars.Length)
throw new ArgumentOutOfRangeException("charIndex", SR.ArgumentOutOfRange_Index);
Contract.EndContractBlock();
// If no input, return 0 & avoid fixed problem
if (byteCount == 0)
return 0;
// Just call pointer version
int charCount = chars.Length - charIndex;
// Fix our input array if 0 length because fixed doesn't like 0 length arrays
if (chars.Length == 0)
chars = new char[1];
fixed (byte* pBytes = bytes) fixed (char* pChars = &chars[0])
// Remember that charCount is # to decode, not size of array
return GetChars(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
[CLSCompliant(false)]
public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount)
{
// Validate Parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array);
if (charCount < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
return GetChars(bytes, byteCount, chars, charCount, null);
}
// Returns a string containing the decoded representation of a range of
// bytes in a byte array.
//
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
public override unsafe String GetString(byte[] bytes, int index, int count)
{
// Validate Parameters
if (bytes == null)
throw new ArgumentNullException("bytes", SR.ArgumentNull_Array);
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum);
if (bytes.Length - index < count)
throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer);
Contract.EndContractBlock();
// Avoid problems with empty input buffer
if (count == 0) return String.Empty;
fixed (byte* pBytes = bytes)
return String.CreateStringFromEncoding(
pBytes + index, count, this);
}
//
// End of standard methods copied from EncodingNLS.cs
//
internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS encoder)
{
Debug.Assert(chars != null, "[UTF32Encoding.GetByteCount]chars!=null");
Debug.Assert(count >= 0, "[UTF32Encoding.GetByteCount]count >=0");
char* end = chars + count;
char* charStart = chars;
int byteCount = 0;
char highSurrogate = '\0';
// For fallback we may need a fallback buffer
EncoderFallbackBuffer fallbackBuffer = null;
char* charsForFallback;
if (encoder != null)
{
highSurrogate = encoder._charLeftOver;
fallbackBuffer = encoder.FallbackBuffer;
// We mustn't have left over fallback data when counting
if (fallbackBuffer.Remaining > 0)
throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, this.EncodingName, encoder.Fallback.GetType()));
}
else
{
fallbackBuffer = this.encoderFallback.CreateFallbackBuffer();
}
// Set our internal fallback interesting things.
fallbackBuffer.InternalInitialize(charStart, end, encoder, false);
char ch;
TryAgain:
while (((ch = fallbackBuffer.InternalGetNextChar()) != 0) || chars < end)
{
// First unwind any fallback
if (ch == 0)
{
// No fallback, just get next char
ch = *chars;
chars++;
}
// Do we need a low surrogate?
if (highSurrogate != '\0')
{
//
// In previous char, we encounter a high surrogate, so we are expecting a low surrogate here.
//
if (Char.IsLowSurrogate(ch))
{
// They're all legal
highSurrogate = '\0';
//
// One surrogate pair will be translated into 4 bytes UTF32.
//
byteCount += 4;
continue;
}
// We are missing our low surrogate, decrement chars and fallback the high surrogate
// The high surrogate may have come from the encoder, but nothing else did.
Debug.Assert(chars > charStart,
"[UTF32Encoding.GetByteCount]Expected chars to have advanced if no low surrogate");
chars--;
// Do the fallback
charsForFallback = chars;
fallbackBuffer.InternalFallback(highSurrogate, ref charsForFallback);
chars = charsForFallback;
// We're going to fallback the old high surrogate.
highSurrogate = '\0';
continue;
}
// Do we have another high surrogate?
if (Char.IsHighSurrogate(ch))
{
//
// We'll have a high surrogate to check next time.
//
highSurrogate = ch;
continue;
}
// Check for illegal characters
if (Char.IsLowSurrogate(ch))
{
// We have a leading low surrogate, do the fallback
charsForFallback = chars;
fallbackBuffer.InternalFallback(ch, ref charsForFallback);
chars = charsForFallback;
// Try again with fallback buffer
continue;
}
// We get to add the character (4 bytes UTF32)
byteCount += 4;
}
// May have to do our last surrogate
if ((encoder == null || encoder.MustFlush) && highSurrogate > 0)
{
// We have to do the fallback for the lonely high surrogate
charsForFallback = chars;
fallbackBuffer.InternalFallback(highSurrogate, ref charsForFallback);
chars = charsForFallback;
highSurrogate = (char)0;
goto TryAgain;
}
// Check for overflows.
if (byteCount < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_GetByteCountOverflow);
// Shouldn't have anything in fallback buffer for GetByteCount
// (don't have to check _throwOnOverflow for count)
Debug.Assert(fallbackBuffer.Remaining == 0,
"[UTF32Encoding.GetByteCount]Expected empty fallback buffer at end");
// Return our count
return byteCount;
}
internal override unsafe int GetBytes(char* chars, int charCount,
byte* bytes, int byteCount, EncoderNLS encoder)
{
Debug.Assert(chars != null, "[UTF32Encoding.GetBytes]chars!=null");
Debug.Assert(bytes != null, "[UTF32Encoding.GetBytes]bytes!=null");
Debug.Assert(byteCount >= 0, "[UTF32Encoding.GetBytes]byteCount >=0");
Debug.Assert(charCount >= 0, "[UTF32Encoding.GetBytes]charCount >=0");
char* charStart = chars;
char* charEnd = chars + charCount;
byte* byteStart = bytes;
byte* byteEnd = bytes + byteCount;
char highSurrogate = '\0';
// For fallback we may need a fallback buffer
EncoderFallbackBuffer fallbackBuffer = null;
char* charsForFallback;
if (encoder != null)
{
highSurrogate = encoder._charLeftOver;
fallbackBuffer = encoder.FallbackBuffer;
// We mustn't have left over fallback data when not converting
if (encoder._throwOnOverflow && fallbackBuffer.Remaining > 0)
throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, this.EncodingName, encoder.Fallback.GetType()));
}
else
{
fallbackBuffer = this.encoderFallback.CreateFallbackBuffer();
}
// Set our internal fallback interesting things.
fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, true);
char ch;
TryAgain:
while (((ch = fallbackBuffer.InternalGetNextChar()) != 0) || chars < charEnd)
{
// First unwind any fallback
if (ch == 0)
{
// No fallback, just get next char
ch = *chars;
chars++;
}
// Do we need a low surrogate?
if (highSurrogate != '\0')
{
//
// In previous char, we encountered a high surrogate, so we are expecting a low surrogate here.
//
if (Char.IsLowSurrogate(ch))
{
// Is it a legal one?
uint iTemp = GetSurrogate(highSurrogate, ch);
highSurrogate = '\0';
//
// One surrogate pair will be translated into 4 bytes UTF32.
//
if (bytes + 3 >= byteEnd)
{
// Don't have 4 bytes
if (fallbackBuffer.bFallingBack)
{
fallbackBuffer.MovePrevious(); // Aren't using these 2 fallback chars
fallbackBuffer.MovePrevious();
}
else
{
// If we don't have enough room, then either we should've advanced a while
// or we should have bytes==byteStart and throw below
Debug.Assert(chars > charStart + 1 || bytes == byteStart,
"[UnicodeEncoding.GetBytes]Expected chars to have when no room to add surrogate pair");
chars -= 2; // Aren't using those 2 chars
}
ThrowBytesOverflow(encoder, bytes == byteStart); // Throw maybe (if no bytes written)
highSurrogate = (char)0; // Nothing left over (we backed up to start of pair if supplimentary)
break;
}
if (_bigEndian)
{
*(bytes++) = (byte)(0x00);
*(bytes++) = (byte)(iTemp >> 16); // Implies & 0xFF, which isn't needed cause high are all 0
*(bytes++) = (byte)(iTemp >> 8); // Implies & 0xFF
*(bytes++) = (byte)(iTemp); // Implies & 0xFF
}
else
{
*(bytes++) = (byte)(iTemp); // Implies & 0xFF
*(bytes++) = (byte)(iTemp >> 8); // Implies & 0xFF
*(bytes++) = (byte)(iTemp >> 16); // Implies & 0xFF, which isn't needed cause high are all 0
*(bytes++) = (byte)(0x00);
}
continue;
}
// We are missing our low surrogate, decrement chars and fallback the high surrogate
// The high surrogate may have come from the encoder, but nothing else did.
Debug.Assert(chars > charStart,
"[UTF32Encoding.GetBytes]Expected chars to have advanced if no low surrogate");
chars--;
// Do the fallback
charsForFallback = chars;
fallbackBuffer.InternalFallback(highSurrogate, ref charsForFallback);
chars = charsForFallback;
// We're going to fallback the old high surrogate.
highSurrogate = '\0';
continue;
}
// Do we have another high surrogate?, if so remember it
if (Char.IsHighSurrogate(ch))
{
//
// We'll have a high surrogate to check next time.
//
highSurrogate = ch;
continue;
}
// Check for illegal characters (low surrogate)
if (Char.IsLowSurrogate(ch))
{
// We have a leading low surrogate, do the fallback
charsForFallback = chars;
fallbackBuffer.InternalFallback(ch, ref charsForFallback);
chars = charsForFallback;
// Try again with fallback buffer
continue;
}
// We get to add the character, yippee.
if (bytes + 3 >= byteEnd)
{
// Don't have 4 bytes
if (fallbackBuffer.bFallingBack)
fallbackBuffer.MovePrevious(); // Aren't using this fallback char
else
{
// Must've advanced already
Debug.Assert(chars > charStart,
"[UTF32Encoding.GetBytes]Expected chars to have advanced if normal character");
chars--; // Aren't using this char
}
ThrowBytesOverflow(encoder, bytes == byteStart); // Throw maybe (if no bytes written)
break; // Didn't throw, stop
}
if (_bigEndian)
{
*(bytes++) = (byte)(0x00);
*(bytes++) = (byte)(0x00);
*(bytes++) = (byte)((uint)ch >> 8); // Implies & 0xFF
*(bytes++) = (byte)(ch); // Implies & 0xFF
}
else
{
*(bytes++) = (byte)(ch); // Implies & 0xFF
*(bytes++) = (byte)((uint)ch >> 8); // Implies & 0xFF
*(bytes++) = (byte)(0x00);
*(bytes++) = (byte)(0x00);
}
}
// May have to do our last surrogate
if ((encoder == null || encoder.MustFlush) && highSurrogate > 0)
{
// We have to do the fallback for the lonely high surrogate
charsForFallback = chars;
fallbackBuffer.InternalFallback(highSurrogate, ref charsForFallback);
chars = charsForFallback;
highSurrogate = (char)0;
goto TryAgain;
}
// Fix our encoder if we have one
Debug.Assert(highSurrogate == 0 || (encoder != null && !encoder.MustFlush),
"[UTF32Encoding.GetBytes]Expected encoder to be flushed.");
if (encoder != null)
{
// Remember our left over surrogate (or 0 if flushing)
encoder._charLeftOver = highSurrogate;
// Need # chars used
encoder._charsUsed = (int)(chars - charStart);
}
// return the new length
return (int)(bytes - byteStart);
}
internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder)
{
Debug.Assert(bytes != null, "[UTF32Encoding.GetCharCount]bytes!=null");
Debug.Assert(count >= 0, "[UTF32Encoding.GetCharCount]count >=0");
UTF32Decoder decoder = (UTF32Decoder)baseDecoder;
// None so far!
int charCount = 0;
byte* end = bytes + count;
byte* byteStart = bytes;
// Set up decoder
int readCount = 0;
uint iChar = 0;
// For fallback we may need a fallback buffer
DecoderFallbackBuffer fallbackBuffer = null;
// See if there's anything in our decoder
if (decoder != null)
{
readCount = decoder.readByteCount;
iChar = (uint)decoder.iChar;
fallbackBuffer = decoder.FallbackBuffer;
// Shouldn't have anything in fallback buffer for GetCharCount
// (don't have to check _throwOnOverflow for chars or count)
Debug.Assert(fallbackBuffer.Remaining == 0,
"[UTF32Encoding.GetCharCount]Expected empty fallback buffer at start");
}
else
{
fallbackBuffer = this.decoderFallback.CreateFallbackBuffer();
}
// Set our internal fallback interesting things.
fallbackBuffer.InternalInitialize(byteStart, null);
// Loop through our input, 4 characters at a time!
while (bytes < end && charCount >= 0)
{
// Get our next character
if (_bigEndian)
{
// Scoot left and add it to the bottom
iChar <<= 8;
iChar += *(bytes++);
}
else
{
// Scoot right and add it to the top
iChar >>= 8;
iChar += (uint)(*(bytes++)) << 24;
}
readCount++;
// See if we have all the bytes yet
if (readCount < 4)
continue;
// Have the bytes
readCount = 0;
// See if its valid to encode
if (iChar > 0x10FFFF || (iChar >= 0xD800 && iChar <= 0xDFFF))
{
// Need to fall back these 4 bytes
byte[] fallbackBytes;
if (_bigEndian)
{
fallbackBytes = new byte[] {
unchecked((byte)(iChar>>24)), unchecked((byte)(iChar>>16)),
unchecked((byte)(iChar>>8)), unchecked((byte)(iChar)) };
}
else
{
fallbackBytes = new byte[] {
unchecked((byte)(iChar)), unchecked((byte)(iChar>>8)),
unchecked((byte)(iChar>>16)), unchecked((byte)(iChar>>24)) };
}
charCount += fallbackBuffer.InternalFallback(fallbackBytes, bytes);
// Ignore the illegal character
iChar = 0;
continue;
}
// Ok, we have something we can add to our output
if (iChar >= 0x10000)
{
// Surrogates take 2
charCount++;
}
// Add the rest of the surrogate or our normal character
charCount++;
// iChar is back to 0
iChar = 0;
}
// See if we have something left over that has to be decoded
if (readCount > 0 && (decoder == null || decoder.MustFlush))
{
// Oops, there's something left over with no place to go.
byte[] fallbackBytes = new byte[readCount];
if (_bigEndian)
{
while (readCount > 0)
{
fallbackBytes[--readCount] = unchecked((byte)iChar);
iChar >>= 8;
}
}
else
{
while (readCount > 0)
{
fallbackBytes[--readCount] = unchecked((byte)(iChar >> 24));
iChar <<= 8;
}
}
charCount += fallbackBuffer.InternalFallback(fallbackBytes, bytes);
}
// Check for overflows.
if (charCount < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_GetByteCountOverflow);
// Shouldn't have anything in fallback buffer for GetCharCount
// (don't have to check _throwOnOverflow for chars or count)
Debug.Assert(fallbackBuffer.Remaining == 0,
"[UTF32Encoding.GetCharCount]Expected empty fallback buffer at end");
// Return our count
return charCount;
}
internal override unsafe int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, DecoderNLS baseDecoder)
{
Debug.Assert(chars != null, "[UTF32Encoding.GetChars]chars!=null");
Debug.Assert(bytes != null, "[UTF32Encoding.GetChars]bytes!=null");
Debug.Assert(byteCount >= 0, "[UTF32Encoding.GetChars]byteCount >=0");
Debug.Assert(charCount >= 0, "[UTF32Encoding.GetChars]charCount >=0");
UTF32Decoder decoder = (UTF32Decoder)baseDecoder;
// None so far!
char* charStart = chars;
char* charEnd = chars + charCount;
byte* byteStart = bytes;
byte* byteEnd = bytes + byteCount;
// See if there's anything in our decoder (but don't clear it yet)
int readCount = 0;
uint iChar = 0;
// For fallback we may need a fallback buffer
DecoderFallbackBuffer fallbackBuffer = null;
char* charsForFallback;
// See if there's anything in our decoder
if (decoder != null)
{
readCount = decoder.readByteCount;
iChar = (uint)decoder.iChar;
fallbackBuffer = baseDecoder.FallbackBuffer;
// Shouldn't have anything in fallback buffer for GetChars
// (don't have to check _throwOnOverflow for chars)
Debug.Assert(fallbackBuffer.Remaining == 0,
"[UTF32Encoding.GetChars]Expected empty fallback buffer at start");
}
else
{
fallbackBuffer = this.decoderFallback.CreateFallbackBuffer();
}
// Set our internal fallback interesting things.
fallbackBuffer.InternalInitialize(bytes, chars + charCount);
// Loop through our input, 4 characters at a time!
while (bytes < byteEnd)
{
// Get our next character
if (_bigEndian)
{
// Scoot left and add it to the bottom
iChar <<= 8;
iChar += *(bytes++);
}
else
{
// Scoot right and add it to the top
iChar >>= 8;
iChar += (uint)(*(bytes++)) << 24;
}
readCount++;
// See if we have all the bytes yet
if (readCount < 4)
continue;
// Have the bytes
readCount = 0;
// See if its valid to encode
if (iChar > 0x10FFFF || (iChar >= 0xD800 && iChar <= 0xDFFF))
{
// Need to fall back these 4 bytes
byte[] fallbackBytes;
if (_bigEndian)
{
fallbackBytes = new byte[] {
unchecked((byte)(iChar>>24)), unchecked((byte)(iChar>>16)),
unchecked((byte)(iChar>>8)), unchecked((byte)(iChar)) };
}
else
{
fallbackBytes = new byte[] {
unchecked((byte)(iChar)), unchecked((byte)(iChar>>8)),
unchecked((byte)(iChar>>16)), unchecked((byte)(iChar>>24)) };
}
// Chars won't be updated unless this works.
charsForFallback = chars;
bool fallbackResult = fallbackBuffer.InternalFallback(fallbackBytes, bytes, ref charsForFallback);
chars = charsForFallback;
if (!fallbackResult)
{
// Couldn't fallback, throw or wait til next time
// We either read enough bytes for bytes-=4 to work, or we're
// going to throw in ThrowCharsOverflow because chars == charStart
Debug.Assert(bytes >= byteStart + 4 || chars == charStart,
"[UTF32Encoding.GetChars]Expected to have consumed bytes or throw (bad surrogate)");
bytes -= 4; // get back to where we were
iChar = 0; // Remembering nothing
fallbackBuffer.InternalReset();
ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output
break; // Stop here, didn't throw
}
// Ignore the illegal character
iChar = 0;
continue;
}
// Ok, we have something we can add to our output
if (iChar >= 0x10000)
{
// Surrogates take 2
if (chars >= charEnd - 1)
{
// Throwing or stopping
// We either read enough bytes for bytes-=4 to work, or we're
// going to throw in ThrowCharsOverflow because chars == charStart
Debug.Assert(bytes >= byteStart + 4 || chars == charStart,
"[UTF32Encoding.GetChars]Expected to have consumed bytes or throw (surrogate)");
bytes -= 4; // get back to where we were
iChar = 0; // Remembering nothing
ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output
break; // Stop here, didn't throw
}
*(chars++) = GetHighSurrogate(iChar);
iChar = GetLowSurrogate(iChar);
}
// Bounds check for normal character
else if (chars >= charEnd)
{
// Throwing or stopping
// We either read enough bytes for bytes-=4 to work, or we're
// going to throw in ThrowCharsOverflow because chars == charStart
Debug.Assert(bytes >= byteStart + 4 || chars == charStart,
"[UTF32Encoding.GetChars]Expected to have consumed bytes or throw (normal char)");
bytes -= 4; // get back to where we were
iChar = 0; // Remembering nothing
ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output
break; // Stop here, didn't throw
}
// Add the rest of the surrogate or our normal character
*(chars++) = (char)iChar;
// iChar is back to 0
iChar = 0;
}
// See if we have something left over that has to be decoded
if (readCount > 0 && (decoder == null || decoder.MustFlush))
{
// Oops, there's something left over with no place to go.
byte[] fallbackBytes = new byte[readCount];
int tempCount = readCount;
if (_bigEndian)
{
while (tempCount > 0)
{
fallbackBytes[--tempCount] = unchecked((byte)iChar);
iChar >>= 8;
}
}
else
{
while (tempCount > 0)
{
fallbackBytes[--tempCount] = unchecked((byte)(iChar >> 24));
iChar <<= 8;
}
}
charsForFallback = chars;
bool fallbackResult = fallbackBuffer.InternalFallback(fallbackBytes, bytes, ref charsForFallback);
chars = charsForFallback;
if (!fallbackResult)
{
// Couldn't fallback.
fallbackBuffer.InternalReset();
ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output
// Stop here, didn't throw, backed up, so still nothing in buffer
}
else
{
// Don't clear our decoder unless we could fall it back.
// If we caught the if above, then we're a convert() and will catch this next time.
readCount = 0;
iChar = 0;
}
}
// Remember any left over stuff, clearing buffer as well for MustFlush
if (decoder != null)
{
decoder.iChar = (int)iChar;
decoder.readByteCount = readCount;
decoder._bytesUsed = (int)(bytes - byteStart);
}
// Shouldn't have anything in fallback buffer for GetChars
// (don't have to check _throwOnOverflow for chars)
Debug.Assert(fallbackBuffer.Remaining == 0,
"[UTF32Encoding.GetChars]Expected empty fallback buffer at end");
// Return our count
return (int)(chars - charStart);
}
private uint GetSurrogate(char cHigh, char cLow)
{
return (((uint)cHigh - 0xD800) * 0x400) + ((uint)cLow - 0xDC00) + 0x10000;
}
private char GetHighSurrogate(uint iChar)
{
return (char)((iChar - 0x10000) / 0x400 + 0xD800);
}
private char GetLowSurrogate(uint iChar)
{
return (char)((iChar - 0x10000) % 0x400 + 0xDC00);
}
public override Decoder GetDecoder()
{
return new UTF32Decoder(this);
}
public override Encoder GetEncoder()
{
return new EncoderNLS(this);
}
public override int GetMaxByteCount(int charCount)
{
if (charCount < 0)
throw new ArgumentOutOfRangeException(nameof(charCount),
SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
// Characters would be # of characters + 1 in case left over high surrogate is ? * max fallback
long byteCount = (long)charCount + 1;
if (EncoderFallback.MaxCharCount > 1)
byteCount *= EncoderFallback.MaxCharCount;
// 4 bytes per char
byteCount *= 4;
if (byteCount > 0x7fffffff)
throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_GetByteCountOverflow);
return (int)byteCount;
}
public override int GetMaxCharCount(int byteCount)
{
if (byteCount < 0)
throw new ArgumentOutOfRangeException(nameof(byteCount),
SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
// A supplementary character becomes 2 surrogate characters, so 4 input bytes becomes 2 chars,
// plus we may have 1 surrogate char left over if the decoder has 3 bytes in it already for a non-bmp char.
// Have to add another one because 1/2 == 0, but 3 bytes left over could be 2 char surrogate pair
int charCount = (byteCount / 2) + 2;
// Also consider fallback because our input bytes could be out of range of unicode.
// Since fallback would fallback 4 bytes at a time, we'll only fall back 1/2 of MaxCharCount.
if (DecoderFallback.MaxCharCount > 2)
{
// Multiply time fallback size
charCount *= DecoderFallback.MaxCharCount;
// We were already figuring 2 chars per 4 bytes, but fallback will be different #
charCount /= 2;
}
if (charCount > 0x7fffffff)
throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_GetCharCountOverflow);
return (int)charCount;
}
public override byte[] GetPreamble()
{
if (_emitUTF32ByteOrderMark)
{
// Allocate new array to prevent users from modifying it.
if (_bigEndian)
{
return new byte[4] { 0x00, 0x00, 0xFE, 0xFF };
}
else
{
return new byte[4] { 0xFF, 0xFE, 0x00, 0x00 }; // 00 00 FE FF
}
}
else
return Array.Empty<byte>();
}
public override bool Equals(Object value)
{
UTF32Encoding that = value as UTF32Encoding;
if (that != null)
{
return (_emitUTF32ByteOrderMark == that._emitUTF32ByteOrderMark) &&
(_bigEndian == that._bigEndian) &&
(EncoderFallback.Equals(that.EncoderFallback)) &&
(DecoderFallback.Equals(that.DecoderFallback));
}
return (false);
}
public override int GetHashCode()
{
//Not great distribution, but this is relatively unlikely to be used as the key in a hashtable.
return this.EncoderFallback.GetHashCode() + this.DecoderFallback.GetHashCode() +
CodePage + (_emitUTF32ByteOrderMark ? 4 : 0) + (_bigEndian ? 8 : 0);
}
private sealed class UTF32Decoder : DecoderNLS
{
// Need a place to store any extra bytes we may have picked up
internal int iChar = 0;
internal int readByteCount = 0;
public UTF32Decoder(UTF32Encoding encoding) : base(encoding)
{
// base calls reset
}
public override void Reset()
{
this.iChar = 0;
this.readByteCount = 0;
if (_fallbackBuffer != null)
_fallbackBuffer.Reset();
}
// Anything left in our decoder?
internal override bool HasState
{
get
{
// ReadByteCount is our flag. (iChar==0 doesn't mean much).
return (this.readByteCount != 0);
}
}
}
}
}
| |
// 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.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Internal.Runtime.CompilerServices;
namespace System
{
// Represents a Globally Unique Identifier.
[StructLayout(LayoutKind.Sequential)]
[Serializable]
[Runtime.Versioning.NonVersionable] // This only applies to field layout
[TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public partial struct Guid : IFormattable, IComparable, IComparable<Guid>, IEquatable<Guid>, ISpanFormattable
{
public static readonly Guid Empty = new Guid();
////////////////////////////////////////////////////////////////////////////////
// Member variables
////////////////////////////////////////////////////////////////////////////////
private int _a; // Do not rename (binary serialization)
private short _b; // Do not rename (binary serialization)
private short _c; // Do not rename (binary serialization)
private byte _d; // Do not rename (binary serialization)
private byte _e; // Do not rename (binary serialization)
private byte _f; // Do not rename (binary serialization)
private byte _g; // Do not rename (binary serialization)
private byte _h; // Do not rename (binary serialization)
private byte _i; // Do not rename (binary serialization)
private byte _j; // Do not rename (binary serialization)
private byte _k; // Do not rename (binary serialization)
////////////////////////////////////////////////////////////////////////////////
// Constructors
////////////////////////////////////////////////////////////////////////////////
// Creates a new guid from an array of bytes.
public Guid(byte[] b) :
this(new ReadOnlySpan<byte>(b ?? throw new ArgumentNullException(nameof(b))))
{
}
// Creates a new guid from a read-only span.
public Guid(ReadOnlySpan<byte> b)
{
if ((uint)b.Length != 16)
throw new ArgumentException(SR.Format(SR.Arg_GuidArrayCtor, "16"), nameof(b));
_a = b[3] << 24 | b[2] << 16 | b[1] << 8 | b[0];
_b = (short)(b[5] << 8 | b[4]);
_c = (short)(b[7] << 8 | b[6]);
_d = b[8];
_e = b[9];
_f = b[10];
_g = b[11];
_h = b[12];
_i = b[13];
_j = b[14];
_k = b[15];
}
[CLSCompliant(false)]
public Guid(uint a, ushort b, ushort c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k)
{
_a = (int)a;
_b = (short)b;
_c = (short)c;
_d = d;
_e = e;
_f = f;
_g = g;
_h = h;
_i = i;
_j = j;
_k = k;
}
// Creates a new GUID initialized to the value represented by the arguments.
//
public Guid(int a, short b, short c, byte[] d)
{
if (d == null)
throw new ArgumentNullException(nameof(d));
// Check that array is not too big
if (d.Length != 8)
throw new ArgumentException(SR.Format(SR.Arg_GuidArrayCtor, "8"), nameof(d));
_a = a;
_b = b;
_c = c;
_d = d[0];
_e = d[1];
_f = d[2];
_g = d[3];
_h = d[4];
_i = d[5];
_j = d[6];
_k = d[7];
}
// Creates a new GUID initialized to the value represented by the
// arguments. The bytes are specified like this to avoid endianness issues.
public Guid(int a, short b, short c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k)
{
_a = a;
_b = b;
_c = c;
_d = d;
_e = e;
_f = f;
_g = g;
_h = h;
_i = i;
_j = j;
_k = k;
}
private enum GuidParseThrowStyle : byte
{
None = 0,
All = 1,
AllButOverflow = 2
}
// This will store the result of the parsing. And it will eventually be used to construct a Guid instance.
private struct GuidResult
{
internal readonly GuidParseThrowStyle _throwStyle;
internal Guid _parsedGuid;
private bool _overflow;
private string _failureMessageID;
private object _failureMessageFormatArgument;
internal GuidResult(GuidParseThrowStyle canThrow) : this()
{
_throwStyle = canThrow;
}
internal void SetFailure(bool overflow, string failureMessageID)
{
_overflow = overflow;
_failureMessageID = failureMessageID;
if (_throwStyle != GuidParseThrowStyle.None)
{
throw CreateGuidParseException();
}
}
internal void SetFailure(bool overflow, string failureMessageID, object failureMessageFormatArgument)
{
_failureMessageFormatArgument = failureMessageFormatArgument;
SetFailure(overflow, failureMessageID);
}
internal Exception CreateGuidParseException()
{
if (_overflow)
{
return _throwStyle == GuidParseThrowStyle.All ?
(Exception)new OverflowException(SR.GetResourceString(_failureMessageID)) :
new FormatException(SR.Format_GuidUnrecognized);
}
else
{
return new FormatException(SR.GetResourceString(_failureMessageID));
}
}
}
// Creates a new guid based on the value in the string. The value is made up
// of hex digits speared by the dash ("-"). The string may begin and end with
// brackets ("{", "}").
//
// The string must be of the form dddddddd-dddd-dddd-dddd-dddddddddddd. where
// d is a hex digit. (That is 8 hex digits, followed by 4, then 4, then 4,
// then 12) such as: "CA761232-ED42-11CE-BACD-00AA0057B223"
//
public Guid(string g)
{
if (g == null)
{
throw new ArgumentNullException(nameof(g));
}
var result = new GuidResult(GuidParseThrowStyle.All);
if (!TryParseGuid(g, ref result))
{
throw result.CreateGuidParseException();
}
this = result._parsedGuid;
}
public static Guid Parse(string input) =>
Parse(input != null ? (ReadOnlySpan<char>)input : throw new ArgumentNullException(nameof(input)));
public static Guid Parse(ReadOnlySpan<char> input)
{
var result = new GuidResult(GuidParseThrowStyle.AllButOverflow);
if (!TryParseGuid(input, ref result))
{
throw result.CreateGuidParseException();
}
return result._parsedGuid;
}
public static bool TryParse(string input, out Guid result)
{
if (input == null)
{
result = default;
return false;
}
return TryParse((ReadOnlySpan<char>)input, out result);
}
public static bool TryParse(ReadOnlySpan<char> input, out Guid result)
{
var parseResult = new GuidResult(GuidParseThrowStyle.None);
if (TryParseGuid(input, ref parseResult))
{
result = parseResult._parsedGuid;
return true;
}
else
{
result = default;
return false;
}
}
public static Guid ParseExact(string input, string format) =>
ParseExact(
input != null ? (ReadOnlySpan<char>)input : throw new ArgumentNullException(nameof(input)),
format != null ? (ReadOnlySpan<char>)format : throw new ArgumentNullException(nameof(format)));
public static Guid ParseExact(ReadOnlySpan<char> input, ReadOnlySpan<char> format)
{
if (format.Length != 1)
{
// all acceptable format strings are of length 1
throw new FormatException(SR.Format_InvalidGuidFormatSpecification);
}
input = input.Trim();
var result = new GuidResult(GuidParseThrowStyle.AllButOverflow);
bool success;
switch ((char)(format[0] | 0x20))
{
case 'd':
success = TryParseExactD(input, ref result);
break;
case 'n':
success = TryParseExactN(input, ref result);
break;
case 'b':
success = TryParseExactB(input, ref result);
break;
case 'p':
success = TryParseExactP(input, ref result);
break;
case 'x':
success = TryParseExactX(input, ref result);
break;
default:
throw new FormatException(SR.Format_InvalidGuidFormatSpecification);
}
if (!success)
{
throw result.CreateGuidParseException();
}
return result._parsedGuid;
}
public static bool TryParseExact(string input, string format, out Guid result)
{
if (input == null)
{
result = default;
return false;
}
return TryParseExact((ReadOnlySpan<char>)input, format, out result);
}
public static bool TryParseExact(ReadOnlySpan<char> input, ReadOnlySpan<char> format, out Guid result)
{
if (format.Length != 1)
{
result = default;
return false;
}
input = input.Trim();
var parseResult = new GuidResult(GuidParseThrowStyle.None);
bool success = false;
switch ((char)(format[0] | 0x20))
{
case 'd':
success = TryParseExactD(input, ref parseResult);
break;
case 'n':
success = TryParseExactN(input, ref parseResult);
break;
case 'b':
success = TryParseExactB(input, ref parseResult);
break;
case 'p':
success = TryParseExactP(input, ref parseResult);
break;
case 'x':
success = TryParseExactX(input, ref parseResult);
break;
}
if (success)
{
result = parseResult._parsedGuid;
return true;
}
else
{
result = default;
return false;
}
}
private static bool TryParseGuid(ReadOnlySpan<char> guidString, ref GuidResult result)
{
guidString = guidString.Trim(); // Remove whitespace from beginning and end
if (guidString.Length == 0)
{
result.SetFailure(overflow: false, nameof(SR.Format_GuidUnrecognized));
return false;
}
switch (guidString[0])
{
case '(':
return TryParseExactP(guidString, ref result);
case '{':
return guidString.Contains('-') ?
TryParseExactB(guidString, ref result) :
TryParseExactX(guidString, ref result);
default:
return guidString.Contains('-') ?
TryParseExactD(guidString, ref result) :
TryParseExactN(guidString, ref result);
}
}
// Two helpers used for parsing components:
// - uint.TryParse(..., NumberStyles.AllowHexSpecifier, ...)
// Used when we expect the entire provided span to be filled with and only with hex digits and no overflow is possible
// - TryParseHex
// Used when the component may have an optional '+' and "0x" prefix, when it may overflow, etc.
private static bool TryParseExactB(ReadOnlySpan<char> guidString, ref GuidResult result)
{
// e.g. "{d85b1407-351d-4694-9392-03acc5870eb1}"
if ((uint)guidString.Length != 38 || guidString[0] != '{' || guidString[37] != '}')
{
result.SetFailure(overflow: false, nameof(SR.Format_GuidInvLen));
return false;
}
return TryParseExactD(guidString.Slice(1, 36), ref result);
}
private static bool TryParseExactD(ReadOnlySpan<char> guidString, ref GuidResult result)
{
// e.g. "d85b1407-351d-4694-9392-03acc5870eb1"
// Compat notes due to the previous implementation's implementation details.
// - Components may begin with "0x" or "0x+", but the expected length of each component
// needs to include those prefixes, e.g. a four digit component could be "1234" or
// "0x34" or "+0x4" or "+234", but not "0x1234" nor "+1234" nor "+0x1234".
// - "0X" is valid instead of "0x"
if ((uint)guidString.Length != 36)
{
result.SetFailure(overflow: false, nameof(SR.Format_GuidInvLen));
return false;
}
if (guidString[8] != '-' || guidString[13] != '-' || guidString[18] != '-' || guidString[23] != '-')
{
result.SetFailure(overflow: false, nameof(SR.Format_GuidDashes));
return false;
}
ref Guid g = ref result._parsedGuid;
uint uintTmp;
if (TryParseHex(guidString.Slice(0, 8), out Unsafe.As<int, uint>(ref g._a)) && // _a
TryParseHex(guidString.Slice(9, 4), out uintTmp)) // _b
{
g._b = (short)uintTmp;
if (TryParseHex(guidString.Slice(14, 4), out uintTmp)) // _c
{
g._c = (short)uintTmp;
if (TryParseHex(guidString.Slice(19, 4), out uintTmp)) // _d, _e
{
g._d = (byte)(uintTmp >> 8);
g._e = (byte)uintTmp;
if (TryParseHex(guidString.Slice(24, 4), out uintTmp)) // _f, _g
{
g._f = (byte)(uintTmp >> 8);
g._g = (byte)uintTmp;
if (uint.TryParse(guidString.Slice(28, 8), NumberStyles.AllowHexSpecifier, null, out uintTmp)) // _h, _i, _j, _k
{
g._h = (byte)(uintTmp >> 24);
g._i = (byte)(uintTmp >> 16);
g._j = (byte)(uintTmp >> 8);
g._k = (byte)uintTmp;
return true;
}
}
}
}
}
result.SetFailure(overflow: false, nameof(SR.Format_GuidInvalidChar));
return false;
}
private static bool TryParseExactN(ReadOnlySpan<char> guidString, ref GuidResult result)
{
// e.g. "d85b1407351d4694939203acc5870eb1"
if ((uint)guidString.Length != 32)
{
result.SetFailure(overflow: false, nameof(SR.Format_GuidInvLen));
return false;
}
ref Guid g = ref result._parsedGuid;
uint uintTmp;
if (uint.TryParse(guidString.Slice(0, 8), NumberStyles.AllowHexSpecifier, null, out Unsafe.As<int, uint>(ref g._a)) && // _a
uint.TryParse(guidString.Slice(8, 8), NumberStyles.AllowHexSpecifier, null, out uintTmp)) // _b, _c
{
g._b = (short)(uintTmp >> 16);
g._c = (short)uintTmp;
if (uint.TryParse(guidString.Slice(16, 8), NumberStyles.AllowHexSpecifier, null, out uintTmp)) // _d, _e, _f, _g
{
g._d = (byte)(uintTmp >> 24);
g._e = (byte)(uintTmp >> 16);
g._f = (byte)(uintTmp >> 8);
g._g = (byte)uintTmp;
if (uint.TryParse(guidString.Slice(24, 8), NumberStyles.AllowHexSpecifier, null, out uintTmp)) // _h, _i, _j, _k
{
g._h = (byte)(uintTmp >> 24);
g._i = (byte)(uintTmp >> 16);
g._j = (byte)(uintTmp >> 8);
g._k = (byte)uintTmp;
return true;
}
}
}
result.SetFailure(overflow: false, nameof(SR.Format_GuidInvalidChar));
return false;
}
private static bool TryParseExactP(ReadOnlySpan<char> guidString, ref GuidResult result)
{
// e.g. "(d85b1407-351d-4694-9392-03acc5870eb1)"
if ((uint)guidString.Length != 38 || guidString[0] != '(' || guidString[37] != ')')
{
result.SetFailure(overflow: false, nameof(SR.Format_GuidInvLen));
return false;
}
return TryParseExactD(guidString.Slice(1, 36), ref result);
}
private static bool TryParseExactX(ReadOnlySpan<char> guidString, ref GuidResult result)
{
// e.g. "{0xd85b1407,0x351d,0x4694,{0x93,0x92,0x03,0xac,0xc5,0x87,0x0e,0xb1}}"
// Compat notes due to the previous implementation's implementation details.
// - Each component need not be the full expected number of digits.
// - Each component may contain any number of leading 0s
// - The "short" components are parsed as 32-bits and only considered to overflow if they'd overflow 32 bits.
// - The "byte" components are parsed as 32-bits and are considered to overflow if they'd overflow 8 bits,
// but for the Guid ctor, whether they overflow 8 bits or 32 bits results in differing exceptions.
// - Components may begin with "0x", "0x+", even "0x+0x".
// - "0X" is valid instead of "0x"
// Eat all of the whitespace. Unlike the other forms, X allows for any amount of whitespace
// anywhere, not just at the beginning and end.
guidString = EatAllWhitespace(guidString);
// Check for leading '{'
if ((uint)guidString.Length == 0 || guidString[0] != '{')
{
result.SetFailure(overflow: false, nameof(SR.Format_GuidBrace));
return false;
}
// Check for '0x'
if (!IsHexPrefix(guidString, 1))
{
result.SetFailure(overflow: false, nameof(SR.Format_GuidHexPrefix), "{0xdddddddd, etc}");
return false;
}
// Find the end of this hex number (since it is not fixed length)
int numStart = 3;
int numLen = guidString.Slice(numStart).IndexOf(',');
if (numLen <= 0)
{
result.SetFailure(overflow: false, nameof(SR.Format_GuidComma));
return false;
}
bool overflow = false;
if (!TryParseHex(guidString.Slice(numStart, numLen), out Unsafe.As<int, uint>(ref result._parsedGuid._a), ref overflow) || overflow)
{
result.SetFailure(overflow, overflow ? nameof(SR.Overflow_UInt32) : nameof(SR.Format_GuidInvalidChar));
return false;
}
// Check for '0x'
if (!IsHexPrefix(guidString, numStart + numLen + 1))
{
result.SetFailure(overflow: false, nameof(SR.Format_GuidHexPrefix), "{0xdddddddd, 0xdddd, etc}");
return false;
}
// +3 to get by ',0x'
numStart = numStart + numLen + 3;
numLen = guidString.Slice(numStart).IndexOf(',');
if (numLen <= 0)
{
result.SetFailure(overflow: false, nameof(SR.Format_GuidComma));
return false;
}
// Read in the number
if (!TryParseHex(guidString.Slice(numStart, numLen), out result._parsedGuid._b, ref overflow) || overflow)
{
result.SetFailure(overflow, overflow ? nameof(SR.Overflow_UInt32) : nameof(SR.Format_GuidInvalidChar));
return false;
}
// Check for '0x'
if (!IsHexPrefix(guidString, numStart + numLen + 1))
{
result.SetFailure(overflow: false, nameof(SR.Format_GuidHexPrefix), "{0xdddddddd, 0xdddd, 0xdddd, etc}");
return false;
}
// +3 to get by ',0x'
numStart = numStart + numLen + 3;
numLen = guidString.Slice(numStart).IndexOf(',');
if (numLen <= 0)
{
result.SetFailure(overflow: false, nameof(SR.Format_GuidComma));
return false;
}
// Read in the number
if (!TryParseHex(guidString.Slice(numStart, numLen), out result._parsedGuid._c, ref overflow) || overflow)
{
result.SetFailure(overflow, overflow ? nameof(SR.Overflow_UInt32) : nameof(SR.Format_GuidInvalidChar));
return false;
}
// Check for '{'
if ((uint)guidString.Length <= numStart + numLen + 1 || guidString[numStart + numLen + 1] != '{')
{
result.SetFailure(overflow: false, nameof(SR.Format_GuidBrace));
return false;
}
// Prepare for loop
numLen++;
for (int i = 0; i < 8; i++)
{
// Check for '0x'
if (!IsHexPrefix(guidString, numStart + numLen + 1))
{
result.SetFailure(overflow: false, nameof(SR.Format_GuidHexPrefix), "{... { ... 0xdd, ...}}");
return false;
}
// +3 to get by ',0x' or '{0x' for first case
numStart = numStart + numLen + 3;
// Calculate number length
if (i < 7) // first 7 cases
{
numLen = guidString.Slice(numStart).IndexOf(',');
if (numLen <= 0)
{
result.SetFailure(overflow: false, nameof(SR.Format_GuidComma));
return false;
}
}
else // last case ends with '}', not ','
{
numLen = guidString.Slice(numStart).IndexOf('}');
if (numLen <= 0)
{
result.SetFailure(overflow: false, nameof(SR.Format_GuidBraceAfterLastNumber));
return false;
}
}
// Read in the number
uint byteVal;
if (!TryParseHex(guidString.Slice(numStart, numLen), out byteVal, ref overflow) || overflow || byteVal > byte.MaxValue)
{
// The previous implementation had some odd inconsistencies, which are carried forward here.
// The byte values in the X format are treated as integers with regards to overflow, so
// a "byte" value like 0xddd in Guid's ctor results in a FormatException but 0xddddddddd results
// in OverflowException.
result.SetFailure(overflow,
overflow ? nameof(SR.Overflow_UInt32) :
byteVal > byte.MaxValue ? nameof(SR.Overflow_Byte) :
nameof(SR.Format_GuidInvalidChar));
return false;
}
Unsafe.Add(ref result._parsedGuid._d, i) = (byte)byteVal;
}
// Check for last '}'
if (numStart + numLen + 1 >= guidString.Length || guidString[numStart + numLen + 1] != '}')
{
result.SetFailure(overflow: false, nameof(SR.Format_GuidEndBrace));
return false;
}
// Check if we have extra characters at the end
if (numStart + numLen + 1 != guidString.Length - 1)
{
result.SetFailure(overflow: false, nameof(SR.Format_ExtraJunkAtEnd));
return false;
}
return true;
}
private static bool TryParseHex(ReadOnlySpan<char> guidString, out short result, ref bool overflow)
{
uint tmp;
bool success = TryParseHex(guidString, out tmp, ref overflow);
result = (short)tmp;
return success;
}
private static bool TryParseHex(ReadOnlySpan<char> guidString, out uint result)
{
bool overflowIgnored = false;
return TryParseHex(guidString, out result, ref overflowIgnored);
}
private static bool TryParseHex(ReadOnlySpan<char> guidString, out uint result, ref bool overflow)
{
if ((uint)guidString.Length > 0)
{
if (guidString[0] == '+')
{
guidString = guidString.Slice(1);
}
if ((uint)guidString.Length > 1 && guidString[0] == '0' && (guidString[1] | 0x20) == 'x')
{
guidString = guidString.Slice(2);
}
}
// Skip past leading 0s.
int i = 0;
for (; i < guidString.Length && guidString[i] == '0'; i++);
int processedDigits = 0;
int[] charToHexLookup = Number.s_charToHexLookup;
uint tmp = 0;
for (; i < guidString.Length; i++)
{
int numValue;
char c = guidString[i];
if (c >= charToHexLookup.Length || (numValue = charToHexLookup[c]) == 0xFF)
{
if (processedDigits > 8) overflow = true;
result = 0;
return false;
}
tmp = (tmp * 16) + (uint)numValue;
processedDigits++;
}
if (processedDigits > 8) overflow = true;
result = tmp;
return true;
}
private static ReadOnlySpan<char> EatAllWhitespace(ReadOnlySpan<char> str)
{
// Find the first whitespace character. If there is none, just return the input.
int i;
for (i = 0; i < str.Length && !char.IsWhiteSpace(str[i]); i++) ;
if (i == str.Length)
{
return str;
}
// There was at least one whitespace. Copy over everything prior to it to a new array.
var chArr = new char[str.Length];
int newLength = 0;
if (i > 0)
{
newLength = i;
str.Slice(0, i).CopyTo(chArr);
}
// Loop through the remaining chars, copying over non-whitespace.
for (; i < str.Length; i++)
{
char c = str[i];
if (!char.IsWhiteSpace(c))
{
chArr[newLength++] = c;
}
}
// Return the string with the whitespace removed.
return new ReadOnlySpan<char>(chArr, 0, newLength);
}
private static bool IsHexPrefix(ReadOnlySpan<char> str, int i) =>
i + 1 < str.Length &&
str[i] == '0' &&
(str[i + 1] | 0x20) == 'x';
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void WriteByteHelper(Span<byte> destination)
{
destination[0] = (byte)(_a);
destination[1] = (byte)(_a >> 8);
destination[2] = (byte)(_a >> 16);
destination[3] = (byte)(_a >> 24);
destination[4] = (byte)(_b);
destination[5] = (byte)(_b >> 8);
destination[6] = (byte)(_c);
destination[7] = (byte)(_c >> 8);
destination[8] = _d;
destination[9] = _e;
destination[10] = _f;
destination[11] = _g;
destination[12] = _h;
destination[13] = _i;
destination[14] = _j;
destination[15] = _k;
}
// Returns an unsigned byte array containing the GUID.
public byte[] ToByteArray()
{
var g = new byte[16];
WriteByteHelper(g);
return g;
}
// Returns whether bytes are sucessfully written to given span.
public bool TryWriteBytes(Span<byte> destination)
{
if (destination.Length < 16)
return false;
WriteByteHelper(destination);
return true;
}
// Returns the guid in "registry" format.
public override string ToString()
{
return ToString("D", null);
}
public override int GetHashCode()
{
// Simply XOR all the bits of the GUID 32 bits at a time.
return _a ^ Unsafe.Add(ref _a, 1) ^ Unsafe.Add(ref _a, 2) ^ Unsafe.Add(ref _a, 3);
}
// Returns true if and only if the guid represented
// by o is the same as this instance.
public override bool Equals(object o)
{
Guid g;
// Check that o is a Guid first
if (o == null || !(o is Guid))
return false;
else g = (Guid)o;
// Now compare each of the elements
return g._a == _a &&
Unsafe.Add(ref g._a, 1) == Unsafe.Add(ref _a, 1) &&
Unsafe.Add(ref g._a, 2) == Unsafe.Add(ref _a, 2) &&
Unsafe.Add(ref g._a, 3) == Unsafe.Add(ref _a, 3);
}
public bool Equals(Guid g)
{
// Now compare each of the elements
return g._a == _a &&
Unsafe.Add(ref g._a, 1) == Unsafe.Add(ref _a, 1) &&
Unsafe.Add(ref g._a, 2) == Unsafe.Add(ref _a, 2) &&
Unsafe.Add(ref g._a, 3) == Unsafe.Add(ref _a, 3);
}
private int GetResult(uint me, uint them)
{
if (me < them)
{
return -1;
}
return 1;
}
public int CompareTo(object value)
{
if (value == null)
{
return 1;
}
if (!(value is Guid))
{
throw new ArgumentException(SR.Arg_MustBeGuid, nameof(value));
}
Guid g = (Guid)value;
if (g._a != _a)
{
return GetResult((uint)_a, (uint)g._a);
}
if (g._b != _b)
{
return GetResult((uint)_b, (uint)g._b);
}
if (g._c != _c)
{
return GetResult((uint)_c, (uint)g._c);
}
if (g._d != _d)
{
return GetResult(_d, g._d);
}
if (g._e != _e)
{
return GetResult(_e, g._e);
}
if (g._f != _f)
{
return GetResult(_f, g._f);
}
if (g._g != _g)
{
return GetResult(_g, g._g);
}
if (g._h != _h)
{
return GetResult(_h, g._h);
}
if (g._i != _i)
{
return GetResult(_i, g._i);
}
if (g._j != _j)
{
return GetResult(_j, g._j);
}
if (g._k != _k)
{
return GetResult(_k, g._k);
}
return 0;
}
public int CompareTo(Guid value)
{
if (value._a != _a)
{
return GetResult((uint)_a, (uint)value._a);
}
if (value._b != _b)
{
return GetResult((uint)_b, (uint)value._b);
}
if (value._c != _c)
{
return GetResult((uint)_c, (uint)value._c);
}
if (value._d != _d)
{
return GetResult(_d, value._d);
}
if (value._e != _e)
{
return GetResult(_e, value._e);
}
if (value._f != _f)
{
return GetResult(_f, value._f);
}
if (value._g != _g)
{
return GetResult(_g, value._g);
}
if (value._h != _h)
{
return GetResult(_h, value._h);
}
if (value._i != _i)
{
return GetResult(_i, value._i);
}
if (value._j != _j)
{
return GetResult(_j, value._j);
}
if (value._k != _k)
{
return GetResult(_k, value._k);
}
return 0;
}
public static bool operator ==(Guid a, Guid b)
{
// Now compare each of the elements
return a._a == b._a &&
Unsafe.Add(ref a._a, 1) == Unsafe.Add(ref b._a, 1) &&
Unsafe.Add(ref a._a, 2) == Unsafe.Add(ref b._a, 2) &&
Unsafe.Add(ref a._a, 3) == Unsafe.Add(ref b._a, 3);
}
public static bool operator !=(Guid a, Guid b)
{
// Now compare each of the elements
return a._a != b._a ||
Unsafe.Add(ref a._a, 1) != Unsafe.Add(ref b._a, 1) ||
Unsafe.Add(ref a._a, 2) != Unsafe.Add(ref b._a, 2) ||
Unsafe.Add(ref a._a, 3) != Unsafe.Add(ref b._a, 3);
}
public string ToString(string format)
{
return ToString(format, null);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static char HexToChar(int a)
{
a = a & 0xf;
return (char)((a > 9) ? a - 10 + 0x61 : a + 0x30);
}
private static unsafe int HexsToChars(char* guidChars, int a, int b)
{
guidChars[0] = HexToChar(a >> 4);
guidChars[1] = HexToChar(a);
guidChars[2] = HexToChar(b >> 4);
guidChars[3] = HexToChar(b);
return 4;
}
private static unsafe int HexsToCharsHexOutput(char* guidChars, int a, int b)
{
guidChars[0] = '0';
guidChars[1] = 'x';
guidChars[2] = HexToChar(a >> 4);
guidChars[3] = HexToChar(a);
guidChars[4] = ',';
guidChars[5] = '0';
guidChars[6] = 'x';
guidChars[7] = HexToChar(b >> 4);
guidChars[8] = HexToChar(b);
return 9;
}
// IFormattable interface
// We currently ignore provider
public string ToString(string format, IFormatProvider provider)
{
if (format == null || format.Length == 0)
format = "D";
// all acceptable format strings are of length 1
if (format.Length != 1)
throw new FormatException(SR.Format_InvalidGuidFormatSpecification);
int guidSize;
switch (format[0])
{
case 'D':
case 'd':
guidSize = 36;
break;
case 'N':
case 'n':
guidSize = 32;
break;
case 'B':
case 'b':
case 'P':
case 'p':
guidSize = 38;
break;
case 'X':
case 'x':
guidSize = 68;
break;
default:
throw new FormatException(SR.Format_InvalidGuidFormatSpecification);
}
string guidString = string.FastAllocateString(guidSize);
int bytesWritten;
bool result = TryFormat(new Span<char>(ref guidString.GetRawStringData(), guidString.Length), out bytesWritten, format);
Debug.Assert(result && bytesWritten == guidString.Length, "Formatting guid should have succeeded.");
return guidString;
}
// Returns whether the guid is successfully formatted as a span.
public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default)
{
if (format.Length == 0)
format = "D";
// all acceptable format strings are of length 1
if (format.Length != 1)
throw new FormatException(SR.Format_InvalidGuidFormatSpecification);
bool dash = true;
bool hex = false;
int braces = 0;
int guidSize;
switch (format[0])
{
case 'D':
case 'd':
guidSize = 36;
break;
case 'N':
case 'n':
dash = false;
guidSize = 32;
break;
case 'B':
case 'b':
braces = '{' + ('}' << 16);
guidSize = 38;
break;
case 'P':
case 'p':
braces = '(' + (')' << 16);
guidSize = 38;
break;
case 'X':
case 'x':
braces = '{' + ('}' << 16);
dash = false;
hex = true;
guidSize = 68;
break;
default:
throw new FormatException(SR.Format_InvalidGuidFormatSpecification);
}
if (destination.Length < guidSize)
{
charsWritten = 0;
return false;
}
unsafe
{
fixed (char* guidChars = &MemoryMarshal.GetReference(destination))
{
char * p = guidChars;
if (braces != 0)
*p++ = (char)braces;
if (hex)
{
// {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}
*p++ = '0';
*p++ = 'x';
p += HexsToChars(p, _a >> 24, _a >> 16);
p += HexsToChars(p, _a >> 8, _a);
*p++ = ',';
*p++ = '0';
*p++ = 'x';
p += HexsToChars(p, _b >> 8, _b);
*p++ = ',';
*p++ = '0';
*p++ = 'x';
p += HexsToChars(p, _c >> 8, _c);
*p++ = ',';
*p++ = '{';
p += HexsToCharsHexOutput(p, _d, _e);
*p++ = ',';
p += HexsToCharsHexOutput(p, _f, _g);
*p++ = ',';
p += HexsToCharsHexOutput(p, _h, _i);
*p++ = ',';
p += HexsToCharsHexOutput(p, _j, _k);
*p++ = '}';
}
else
{
// [{|(]dddddddd[-]dddd[-]dddd[-]dddd[-]dddddddddddd[}|)]
p += HexsToChars(p, _a >> 24, _a >> 16);
p += HexsToChars(p, _a >> 8, _a);
if (dash)
*p++ = '-';
p += HexsToChars(p, _b >> 8, _b);
if (dash)
*p++ = '-';
p += HexsToChars(p, _c >> 8, _c);
if (dash)
*p++ = '-';
p += HexsToChars(p, _d, _e);
if (dash)
*p++ = '-';
p += HexsToChars(p, _f, _g);
p += HexsToChars(p, _h, _i);
p += HexsToChars(p, _j, _k);
}
if (braces != 0)
*p++ = (char)(braces >> 16);
Debug.Assert(p - guidChars == guidSize);
}
}
charsWritten = guidSize;
return true;
}
bool ISpanFormattable.TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format, IFormatProvider provider)
{
// Like with the IFormattable implementation, provider is ignored.
return TryFormat(destination, out charsWritten, format);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using DemoGame.DbObjs;
using DemoGame.Server.Queries;
using log4net;
using NetGore;
using NetGore.Db;
using NetGore.Features.ActionDisplays;
using NetGore.Stats;
using NetGore.World;
using SFML.Graphics;
namespace DemoGame.Server
{
/// <summary>
/// A single item instance on the server. Can be either a single item, or a stack of the exact same kind
/// of item combined into one (<see cref="ItemEntity.Amount"/> greater than 1).
/// </summary>
public class ItemEntity : ItemEntityBase, IItemTable
{
static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// The <see cref="ItemID"/> used to represent when an <see cref="ItemEntity"/> has either an invalid or unassigned
/// <see cref="ItemID"/>.
/// </summary>
static readonly ItemID _invalidIDValue = new ItemID(0);
/// <summary>
/// The <see cref="DeleteItemQuery"/> instance to use.
/// </summary>
static readonly DeleteItemQuery _queryDeleteItem;
/// <summary>
/// The <see cref="InsertItemQuery"/> instance to use.
/// </summary>
static readonly InsertItemQuery _queryInsertItem;
/// <summary>
/// The <see cref="SelectItemQuery"/> instance to use.
/// </summary>
static readonly SelectItemQuery _querySelectItem;
/// <summary>
/// The <see cref="UpdateItemFieldQuery"/> instance to use.
/// </summary>
static readonly UpdateItemFieldQuery _queryUpdateItemField;
readonly StatCollection<StatType> _baseStats;
readonly StatCollection<StatType> _reqStats;
ActionDisplayID? _actionDisplayID;
byte _amount = 1;
string _description;
string _equippedBody;
GrhIndex _graphicIndex;
SPValueType _hp;
ItemID _id = _invalidIDValue;
bool _isPersistent;
SPValueType _mp;
string _name;
ushort _range;
ItemTemplateID? _templateID;
ItemType _type;
int _value;
WeaponType _weaponType;
SkillType? _skillID;
/// <summary>
/// Initializes the <see cref="ItemEntity"/> class.
/// </summary>
static ItemEntity()
{
var dbController = DbControllerBase.GetInstance();
_queryUpdateItemField = dbController.GetQuery<UpdateItemFieldQuery>();
_queryInsertItem = dbController.GetQuery<InsertItemQuery>();
_queryDeleteItem = dbController.GetQuery<DeleteItemQuery>();
_querySelectItem = dbController.GetQuery<SelectItemQuery>();
}
/// <summary>
/// Initializes a new instance of the <see cref="ItemEntity"/> class.
/// </summary>
/// <param name="t">The item template to copy the initial values from.</param>
/// <param name="amount">The amount of the item.</param>
public ItemEntity(IItemTemplateTable t, byte amount) : this(t, Vector2.Zero, amount)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ItemEntity"/> class.
/// </summary>
/// <param name="t">The item template to copy the initial values from.</param>
/// <param name="pos">The world position of the item.</param>
/// <param name="amount">The amount of the item.</param>
/// <param name="map">The map the item is to spawn on.</param>
public ItemEntity(IItemTemplateTable t, Vector2 pos, byte amount, MapBase map) : this(t, pos, amount)
{
// Since the item is spawning on a map, ensure that the position is valid for the map
var validPos = ValidatePosition(map, pos);
if (!IsDisposed)
{
Teleport(validPos);
map.AddEntity(this);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="ItemEntity"/> class.
/// </summary>
/// <param name="t">The item template to copy the initial values from.</param>
/// <param name="pos">The world position of the item.</param>
/// <param name="amount">The amount of the item.</param>
public ItemEntity(IItemTemplateTable t, Vector2 pos, byte amount)
: this(
pos, new Vector2(t.Width, t.Height), t.ID, t.Name, t.Description, t.Type, t.WeaponType, t.Range, t.Graphic,
t.Value, amount, t.HP, t.MP, t.EquippedBody, t.ActionDisplayID, t.SkillID, t.Stats.Select(x => (Stat<StatType>)x),
t.ReqStats.Select(x => (Stat<StatType>)x))
{
if (ItemTemplateID.HasValue)
{
WorldStatsTracker.Instance.AddCountCreateItem((int)ItemTemplateID, amount);
EventCounterManager.ItemTemplate.Increment(ItemTemplateID.Value, ItemTemplateEventCounterType.Create, amount);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="ItemEntity"/> class.
/// </summary>
public ItemEntity() : base(Vector2.Zero, Vector2.Zero)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ItemEntity"/> class.
/// </summary>
/// <param name="iv">The item values.</param>
public ItemEntity(IItemTable iv) : this(
Vector2.Zero, new Vector2(iv.Width, iv.Height),
iv.ItemTemplateID, iv.Name, iv.Description, iv.Type, iv.WeaponType, iv.Range,
iv.Graphic, iv.Value, iv.Amount, iv.HP, iv.MP, iv.EquippedBody, iv.ActionDisplayID,
iv.SkillID, iv.Stats.Select(x => (Stat<StatType>)x),
iv.ReqStats.Select(x => (Stat<StatType>)x))
{
_id = iv.ID;
}
/// <summary>
/// Initializes a new instance of the <see cref="ItemEntity"/> class.
/// </summary>
/// <param name="pos">The pos.</param>
/// <param name="size">The size.</param>
/// <param name="templateID">The template ID.</param>
/// <param name="name">The name.</param>
/// <param name="desc">The desc.</param>
/// <param name="type">The type.</param>
/// <param name="weaponType">Type of the weapon.</param>
/// <param name="range">The range.</param>
/// <param name="graphic">The graphic.</param>
/// <param name="value">The value.</param>
/// <param name="amount">The amount.</param>
/// <param name="hp">The hp.</param>
/// <param name="mp">The mp.</param>
/// <param name="equippedBody">The equipped body.</param>
/// <param name="actionDisplayID">The action display ID.</param>
/// <param name="baseStats">The base stats.</param>
/// <param name="reqStats">The req stats.</param>
ItemEntity(Vector2 pos, Vector2 size, ItemTemplateID? templateID, string name, string desc, ItemType type,
WeaponType weaponType, ushort range, GrhIndex graphic, int value, byte amount, SPValueType hp, SPValueType mp,
string equippedBody, ActionDisplayID? actionDisplayID, SkillType? skillID, IEnumerable<Stat<StatType>> baseStats,
IEnumerable<Stat<StatType>> reqStats) : base(pos, size)
{
_templateID = templateID;
_name = name;
_description = desc;
_graphicIndex = graphic;
_value = value;
_amount = amount;
_type = type;
_weaponType = weaponType;
_range = range;
_hp = hp;
_mp = mp;
_equippedBody = equippedBody;
_actionDisplayID = actionDisplayID;
_skillID = skillID;
_baseStats = NewItemStats(baseStats, StatCollectionType.Base);
_reqStats = NewItemStats(reqStats, StatCollectionType.Requirement);
Resized -= ItemEntity_Resized;
Resized += ItemEntity_Resized;
}
/// <summary>
/// Initializes a new instance of the <see cref="ItemEntity"/> class.
/// </summary>
/// <param name="s">The <see cref="ItemEntity"/> to copy the values from.</param>
ItemEntity(ItemEntity s)
: this(
s.Position, s.Size, s.ItemTemplateID, s.Name, s.Description, s.Type, s.WeaponType, s.Range, s.GraphicIndex,
s.Value, s.Amount, s.HP, s.MP, s.EquippedBody, s.ActionDisplayID, s.SkillID, s.BaseStats, s.ReqStats)
{
}
/// <summary>
/// Notifies listeners that the ItemEntity's Amount or GraphicIndex have changed.
/// </summary>
public event TypedEventHandler<ItemEntity> GraphicOrAmountChanged;
/// <summary>
/// Notifies listeners that this <see cref="Entity"/> was picked up.
/// </summary>
public override event TypedEventHandler<Entity, EventArgs<CharacterEntity>> PickedUp;
/// <summary>
/// Gets the <see cref="ItemEntity"/>'s base stats.
/// </summary>
public StatCollection<StatType> BaseStats
{
get { return _baseStats; }
}
/// <summary>
/// Gets or sets the index of the graphic that is used for this ItemEntity.
/// </summary>
public override GrhIndex GraphicIndex
{
get { return _graphicIndex; }
set
{
if (_graphicIndex == value)
return;
_graphicIndex = value;
if (GraphicOrAmountChanged != null)
GraphicOrAmountChanged.Raise(this, EventArgs.Empty);
SynchronizeField("graphic", _graphicIndex);
}
}
/// <summary>
/// Gets or sets if the <see cref="ItemEntity"/> is persistent. Whether or not an <see cref="ItemEntity"/> is persistent
/// depends completely on where it is currently contained. Whenever the <see cref="ItemEntity"/> is added to a container
/// for a persistent object, this must be set to true to ensure that it persists. When added to a non-persistent container,
/// this should be set to false. It is vital that this property is set to true at the appropriate times, but not vital
/// it is set to false. As such, this property should only be set by a container when it is added to the container, and not
/// set to false by a container when removed.
/// </summary>
/// <example>
/// Good practices:
/// * Set to true when adding to the Inventory or Equipped of a persistent character
/// * Set to false when adding to a map or non-persistent character
/// Bad practices (DO NOT DO!):
/// * Set to false when removing from the Inventory or Equipped of a persistent character
/// </example>
public bool IsPersistent
{
get { return _isPersistent; }
set
{
if (_isPersistent == value)
return;
_isPersistent = value;
// Handle the changed persistence
if (IsPersistent)
{
// Item changed to persistent
// Changed to persistent for the first time?
if (ID == _invalidIDValue)
{
// Perform an insert, and let the database assign us a free ID
long insertID;
_queryInsertItem.ExecuteWithResult(this, out insertID);
Debug.Assert(insertID <= ItemID.MaxValue);
Debug.Assert(insertID >= ItemID.MinValue);
Debug.Assert(insertID <= int.MaxValue);
Debug.Assert(insertID >= int.MinValue);
_id = new ItemID((int)insertID);
}
else
{
// Just perform a non-blocking insert since we don't need to get the ID
_queryInsertItem.Execute(this);
}
}
else
{
// Item changed to not persistent - delete from database
_queryDeleteItem.Execute(ID);
}
}
}
/// <summary>
/// Gets the <see cref="ItemEntity"/>'s required stats.
/// </summary>
public StatCollection<StatType> ReqStats
{
get { return _reqStats; }
}
/// <summary>
/// Performs assertions on the <see cref="ItemEntity"/> during the <see cref="HandleDispose"/> method.
/// </summary>
/// <param name="disposeManaged">The disposedManaged value.</param>
[Conditional("DEBUG")]
void AssertHandleDisposeState(bool disposeManaged)
{
if (Amount == 0)
{
if (!disposeManaged)
{
const string errmsg =
"ItemEntity `{0}` had Amount = 0, but it was garbage collected. This is often indication " +
" that you are alter item amounts somewhere, but are not calling Destroy() when the amount get set to 0." +
" This is not an issue since the GC cleans it up for you, but its best to avoid this if you can.";
if (log.IsWarnEnabled)
log.WarnFormat(errmsg, this);
}
}
}
/// <summary>
/// Checks if this <see cref="Entity"/> can be picked up by the specified <paramref name="charEntity"/>, but does
/// not actually pick up this <see cref="Entity"/>.
/// </summary>
/// <param name="charEntity"><see cref="CharacterEntity"/> that is trying to use this <see cref="Entity"/>.</param>
/// <returns>True if this <see cref="Entity"/> can be picked up, else false.</returns>
public override bool CanPickup(CharacterEntity charEntity)
{
// Every character can pick up an ItemEntity
return true;
}
/// <summary>
/// Checks if this item can be stacked with another item. To stack, both items must contain the same
/// stat modifiers, name, description, value, and graphic index.
/// </summary>
/// <param name="source">Item to check if can stack on this item</param>
/// <returns>
/// True if the two items can stack on each other, else false
/// </returns>
public override bool CanStack(ItemEntityBase source)
{
var s = source as ItemEntity;
if (s == null)
return false;
return CanStack(s);
}
/// <summary>
/// Checks if this ItemEntity can be stacked with another ItemEntity. To stack, both items must contain the same
/// stat modifiers, name, description, value, and graphic index.
/// </summary>
/// <param name="source">Item to check if can stack on this ItemEntity.</param>
/// <returns>True if the two items can stack on each other, else false.</returns>
public bool CanStack(ItemEntity source)
{
// Check for equal reference
if (ReferenceEquals(this, source))
{
// Although it makes sense for an ItemEntity to be able to stack onto itself,
// there is no reason this should ever happen intentionally
const string errmsg =
"Trying to stack an ItemEntity `{0}` onto itself. Although this is not an error, " +
"it makes no sense why it would be attempted.";
if (log.IsWarnEnabled)
log.WarnFormat(errmsg, this);
Debug.Fail(string.Format(errmsg, this));
return true;
}
// Check for non-equal values
if (Value != source.Value || GraphicIndex != source.GraphicIndex || Type != source.Type || Name != source.Name ||
Description != source.Description || Range != source.Range || WeaponType != source.WeaponType)
return false;
// Check for non-equal stats
if (!BaseStats.HasSameValues(source.BaseStats) || !ReqStats.HasSameValues(source.ReqStats))
return false;
// Everything important is equal, so they can be stacked
return true;
}
/// <summary>
/// Creates a deep copy of the inheritor, which is a new class with the same values, and returns
/// the copy as an ItemEntityBase.
/// </summary>
/// <returns>A deep copy of the object</returns>
public override ItemEntityBase DeepCopy()
{
return new ItemEntity(this) { IsPersistent = this.IsPersistent };
}
/// <summary>
/// Gets a deep copy of the ItemEntity's values, providing a "snapshot" of the values of the ItemEntity.
/// </summary>
/// <returns>A deep copy of the ItemEntity's values.</returns>
public IItemTable DeepCopyValues()
{
return ((IItemTable)this).DeepCopy();
}
/// <summary>
/// When overridden in the derived class, handles destroying the <see cref="ItemEntityBase"/>.
/// </summary>
protected override void HandleDestroy()
{
Amount = 0;
Dispose();
}
/// <summary>
/// Disposes of the ItemEntity, freeing its ID and existance in the database. Once disposed, an ItemEntity
/// should never be used again.
/// </summary>
/// <param name="disposeManaged">When true, <see cref="IDisposable.Dispose"/> was explicitly called and managed resources need to be
/// disposed. When false, managed resources do not need to be disposed since this object was garbage-collected.</param>
protected override void HandleDispose(bool disposeManaged)
{
AssertHandleDisposeState(disposeManaged);
if (Amount == 0)
{
if (IsPersistent)
{
// Delete the ItemEntity from the database
_queryDeleteItem.Execute(ID);
}
}
base.HandleDispose(disposeManaged);
}
/// <summary>
/// Handles when an ItemEntity is resized.
/// </summary>
/// <param name="sender">The <see cref="ItemEntity"/> that was resized.</param>
/// <param name="e">The <see cref="NetGore.EventArgs{Vector2}"/> instance containing the event data.</param>
void ItemEntity_Resized(ISpatial sender, EventArgs<Vector2> e)
{
Debug.Assert(sender == this, "Why did we receive an ItemEntity_OnResize for another Entity?");
// Get the sizes as a byte
var oldWidth = (byte)e.Item1.X;
var oldHeight = (byte)e.Item1.Y;
var width = (byte)sender.Size.X;
var height = (byte)sender.Size.Y;
// Update the changed sizes
if (oldWidth != width)
SynchronizeField("width", width);
if (oldHeight != height)
SynchronizeField("height", height);
}
/// <summary>
/// Loads an <see cref="ItemEntity"/> instance from the databas.e
/// </summary>
/// <param name="id">The <see cref="ItemID"/> of the item to load.</param>
/// <returns>The loaded <see cref="ItemEntity"/>, or null if the <paramref name="id"/> was invalid or no item with that
/// id exists.</returns>
public static ItemEntity LoadFromDatabase(ItemID id)
{
// Get the item information from the database
var itemInfo = _querySelectItem.Execute(id);
if (itemInfo == null)
return null;
return new ItemEntity(itemInfo);
}
/// <summary>
/// Creates a <see cref="StatCollection{StatType}"/> from the given collection of stats.
/// </summary>
/// <exception cref="ArgumentException">ItemEntity does not use StatCollectionType.Modified.</exception>
/// <exception cref="ArgumentOutOfRangeException"><c>statCollectionType</c> is not a defined enum value.</exception>
StatCollection<StatType> NewItemStats(IEnumerable<Stat<StatType>> statValues, StatCollectionType statCollectionType)
{
var ret = new StatCollection<StatType>(statCollectionType, statValues);
switch (statCollectionType)
{
case StatCollectionType.Base:
case StatCollectionType.Requirement:
ret.StatChanged -= StatCollection_StatChanged;
ret.StatChanged += StatCollection_StatChanged;
break;
case StatCollectionType.Modified:
throw new ArgumentException("ItemEntity does not use StatCollectionType.Modified.", "statCollectionType");
default:
throw new ArgumentOutOfRangeException("statCollectionType");
}
return ret;
}
/// <summary>
/// Picks up this <see cref="Entity"/>.
/// </summary>
/// <param name="charEntity"><see cref="CharacterEntity"/> that is trying to pick up this <see cref="Entity"/>.</param>
/// <returns>True if this <see cref="Entity"/> was successfully picked up, else false.</returns>
public override bool Pickup(CharacterEntity charEntity)
{
// Check for invalid character
if (charEntity == null)
{
const string errmsg = "Null charEntity specified.";
if (log.IsWarnEnabled)
log.Warn(errmsg);
Debug.Fail(errmsg);
return false;
}
// Check if the ItemEntity can be picked up
if (!CanPickup(charEntity))
return false;
// Convert to a character
var character = charEntity as Character;
if (character == null)
{
const string errmsg =
"Unable to convert CharacterEntity `{0}` to Character for some reason. " +
"Is there another type, besides Character, inheriting CharacterEntity?";
if (log.IsErrorEnabled)
log.ErrorFormat(errmsg, charEntity);
Debug.Fail(string.Format(errmsg, charEntity));
return false;
}
// Create a deep copy of the item to give to the character instead of giving them this item (its easier this way)
var itemCopy = (ItemEntity)DeepCopy();
var amountGiven = character.GiveItem(itemCopy);
// If nothing was given, then nothing happens... move on
if (amountGiven <= 0)
{
Debug.Assert(amountGiven == 0);
return false;
}
// Find the new item amount
var newAmount = (byte)Math.Max(Math.Min(Amount - amountGiven, byte.MaxValue), byte.MinValue);
Debug.Assert(amountGiven > 0 && amountGiven <= Amount);
// Update the amount property
Amount = newAmount;
// If all of the item was picked up, then destroy this item
if (newAmount == 0)
Destroy();
// Notify listeners using the item copy since that was the one actually given to them
if (PickedUp != null)
PickedUp.Raise(itemCopy, EventArgsHelper.Create(charEntity));
return true;
}
/// <summary>
/// Splits the ItemEntity into two parts. This ItemEntity's amount will be decreased, and a new
/// ItemEntity will be constructed as the product of the method. The original ItemEntity must still have
/// an amount of at least one for the split to succeed.
/// </summary>
/// <param name="amount">Amount of the ItemEntity for the new part to contain. This must be less than
/// the Amount of the existing ItemEntity, since both resulting ItemEntities must have an amount of
/// at least 1.</param>
/// <returns>New ItemEntity of the specified <paramref name="amount"/>, or null if the specified
/// amount of the ItemEntity could not be acquired.</returns>
public ItemEntity Split(byte amount)
{
// Check for a valid amount
if (Amount <= 0)
{
Debug.Fail("Tried to Split() an ItemEntity with an Amount <= 0.");
return null;
}
// Check if we can't perform a full split
if (amount >= Amount)
return null;
// Create the new ItemEntity
var child = new ItemEntity(this) { Amount = amount, IsPersistent = true };
// Lower the amount of this ItemEntity
Amount -= amount;
return child;
}
/// <summary>
/// Handles the <see cref="IStatCollection{T}.StatChanged"/> event for the stat collections in this class.
/// </summary>
void StatCollection_StatChanged(IStatCollection<StatType> sender, StatCollectionStatChangedEventArgs<StatType> e)
{
Debug.Assert(sender.StatCollectionType != StatCollectionType.Modified,
"ItemEntity does not use StatCollectionType.Modified.");
var field = e.StatType.GetDatabaseField(sender.StatCollectionType);
SynchronizeField(field, e.NewValue);
}
/// <summary>
/// Updates a single field for the ItemEntity in the database.
/// </summary>
/// <param name="field">Name of the field to update.</param>
/// <param name="value">New value for the field.</param>
void SynchronizeField(string field, object value)
{
if (!IsPersistent)
return;
_queryUpdateItemField.Execute(_id, field, value);
}
/// <summary>
/// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </returns>
public override string ToString()
{
return string.Format("{0} [ID: {1}]", Name, ID);
}
/// <summary>
/// Validates the given <paramref name="position"/> by attempting to make it a legal position if it is not
/// one already.
/// </summary>
/// <param name="map">The map that the <see cref="ItemEntity"/> is on or will be on.</param>
/// <param name="position">The position to validate.</param>
/// <returns>If the <paramref name="position"/> was already valid, or no valid position was found, contains
/// the same value as the <paramref name="position"/>; otherwise, contains the corrected valid position.</returns>
Vector2 ValidatePosition(MapBase map, Vector2 position)
{
if (map == null)
return position;
var tempRect = new Rectangle(position.X, position.Y, Size.X, Size.Y);
Vector2 closestLegalPosition;
bool isClosestPositionValid;
if (!map.IsValidPlacementPosition(tempRect, out closestLegalPosition, out isClosestPositionValid))
{
if (isClosestPositionValid)
{
// Legal position found
return closestLegalPosition;
}
else
{
// No legal position found, so just destroy the item...
const string errmsg =
"No legal position could be found for item `{0}` (Map: `{1}`; Position: `{2}`). Destroying item...";
if (log.IsWarnEnabled)
log.WarnFormat(errmsg, this, map, position);
Debug.Fail(string.Format(errmsg, this, map, position));
Destroy();
}
}
return position;
}
#region IItemTable Members
/// <summary>
/// Gets or sets the <see cref="ActionDisplayID"/> to use when using this item.
/// </summary>
public ActionDisplayID? ActionDisplayID
{
get { return _actionDisplayID; }
set
{
if (_actionDisplayID == value)
return;
_actionDisplayID = value;
SynchronizeField("action_display_id", _actionDisplayID);
}
}
/// <summary>
/// Gets the <see cref="SkillID"/> to use when using this item.
/// </summary>
public SkillType? SkillID
{
get { return _skillID; }
}
/// <summary>
/// Gets or sets the size of this ItemEntity cluster (1 for a single ItemEntity).
/// </summary>
public override byte Amount
{
get { return _amount; }
set
{
if (_amount == value)
return;
_amount = value;
if (GraphicOrAmountChanged != null)
GraphicOrAmountChanged.Raise(this, EventArgs.Empty);
SynchronizeField("amount", _amount);
}
}
/// <summary>
/// Gets or sets the description of the ItemEntity.
/// </summary>
public string Description
{
get { return _description; }
set
{
if (_description == value)
return;
_description = value;
SynchronizeField("description", _description);
}
}
/// <summary>
/// Gets the value of the database column `equipped_body`.
/// </summary>
public string EquippedBody
{
get { return _equippedBody; }
set
{
if (_equippedBody == value)
return;
_equippedBody = value;
SynchronizeField("equipped_body", _equippedBody);
}
}
/// <summary>
/// Gets the value of the database column `graphic`.
/// </summary>
GrhIndex IItemTable.Graphic
{
get { return GraphicIndex; }
}
/// <summary>
/// Gets the value of the database column `hp`.
/// </summary>
public SPValueType HP
{
get { return _hp; }
set
{
if (_hp == value)
return;
_hp = value;
SynchronizeField("hp", _hp);
}
}
/// <summary>
/// Gets the value of the database column `height`.
/// </summary>
byte IItemTable.Height
{
get { return (byte)Size.Y; }
}
/// <summary>
/// Gets the unique ID for this ItemEntity.
/// </summary>
public ItemID ID
{
get { return _id; }
}
/// <summary>
/// Gets the value of the database column `item_template_id`.
/// </summary>
public ItemTemplateID? ItemTemplateID
{
get { return _templateID; }
private set
{
if (_templateID == value)
return;
_templateID = value;
SynchronizeField("item_template_id", _mp);
}
}
/// <summary>
/// Gets the value of the database column `mp`.
/// </summary>
public SPValueType MP
{
get { return _mp; }
set
{
if (_mp == value)
return;
_mp = value;
SynchronizeField("mp", _mp);
}
}
/// <summary>
/// Gets or sets the name of the ItemEntity.
/// </summary>
public string Name
{
get { return _name; }
set
{
if (_name == value)
return;
_name = value;
SynchronizeField("name", _name);
}
}
/// <summary>
/// Gets or sets the value of the database column `range`.
/// </summary>
public ushort Range
{
get { return _range; }
set
{
if (_range == value)
return;
_range = value;
SynchronizeField("range", _range);
}
}
/// <summary>
/// Gets an IEnumerable of KeyValuePairs containing the values in the `ReqStat` collection. The
/// key is the collection's key and the value is the value for that corresponding key.
/// </summary>
IEnumerable<KeyValuePair<StatType, int>> IItemTable.ReqStats
{
get { return ReqStats.Cast<KeyValuePair<StatType, int>>(); }
}
/// <summary>
/// Gets an IEnumerable of KeyValuePairs containing the values in the `Stat` collection. The
/// key is the collection's key and the value is the value for that corresponding key.
/// </summary>
IEnumerable<KeyValuePair<StatType, int>> IItemTable.Stats
{
get { return BaseStats.Cast<KeyValuePair<StatType, int>>(); }
}
/// <summary>
/// Gets or sets the type of ItemEntity this is.
/// </summary>
public ItemType Type
{
get { return _type; }
set
{
if (_type == value)
return;
_type = value;
SynchronizeField("type", (byte)_type);
}
}
/// <summary>
/// Gets or sets the value of the ItemEntity.
/// </summary>
public int Value
{
get { return _value; }
set
{
if (_value == value)
return;
_value = value;
SynchronizeField("value", _value);
}
}
/// <summary>
/// Gets or sets the value of the database column `weapon_type`.
/// </summary>
public WeaponType WeaponType
{
get { return _weaponType; }
set
{
if (_weaponType == value)
return;
_weaponType = value;
SynchronizeField("weapon_type", _weaponType);
}
}
/// <summary>
/// Gets the value of the database column `width`.
/// </summary>
byte IItemTable.Width
{
get { return (byte)Size.X; }
}
/// <summary>
/// Creates a deep copy of this table. All the values will be the same
/// but they will be contained in a different object instance.
/// </summary>
/// <returns>
/// A deep copy of this table.
/// </returns>
IItemTable IItemTable.DeepCopy()
{
return new ItemTable(this);
}
/// <summary>
/// Gets the value of the database column in the column collection `ReqStat`
/// that corresponds to the given <paramref name="key"/>.
/// </summary>
/// <param name="key">The key that represents the column in this column collection.</param>
/// <returns>
/// The value of the database column with the corresponding <paramref name="key"/>.
/// </returns>
int IItemTable.GetReqStat(StatType key)
{
return _reqStats[key];
}
/// <summary>
/// Gets the value of the database column in the column collection `Stat`
/// that corresponds to the given <paramref name="key"/>.
/// </summary>
/// <param name="key">The key that represents the column in this column collection.</param>
/// <returns>
/// The value of the database column with the corresponding <paramref name="key"/>.
/// </returns>
int IItemTable.GetStat(StatType key)
{
return _baseStats[key];
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using Cluster.Accounts.Api;
using Cluster.System.Api;
using NakedObjects;
namespace Cluster.Accounts.Impl
{
public class Account : IAccount, IUpdateableEntity
{
#region Injected Services
public IDomainObjectContainer Container { set; protected get; }
public AccountsService AccountsService { set; protected get; }
public IClock Clock { set; protected get; }
#endregion
#region Life Cycle Methods
public virtual void Persisting()
{
LastModified = Clock.Now();
}
public void Updating()
{
LastModified = Clock.Now();
}
#endregion
public override string ToString()
{
TitleBuilder t = new TitleBuilder();
t.Append(Code).Append(" -", Name);
return t.ToString();
}
#region Properties
[NakedObjectsIgnore]
public virtual int Id { get; set; }
[Disabled, MemberOrder(5)]
public virtual string Code { get; set; }
#region Name
[MemberOrder(10)]
public virtual string Name { get; set; }
public virtual string DisableName()
{
return null; //To be potentially overridden in sub-classes
}
#endregion
[MemberOrder(20), Disabled]
public virtual AccountTypes Type { get; set; }
[MemberOrder(30), Disabled]
public virtual string Currency { get; set; }
[MemberOrder(40), NotPersisted, NotMapped, TableView(false, "Date", "Description", "Debit", "Credit", "Transaction"), Eagerly(EagerlyAttribute.Do.Rendering)]
public ICollection<IAccountEntry> Entries
{
get
{
int id = Id;
var views = new List<IAccountEntry>();
var bal = GetMostRecentPersistedBalance();
views.Add(bal);
foreach (Transaction tr in AllTransactionsForAccountFrom(bal.Date))
{
var view = Container.NewViewModel<TransactionInAccountView>();
view.AccountViewedFrom = this;
view.Transaction = tr;
views.Add(view);
}
views.Add(CreateCurrentBalance());
return views;
}
}
[ConcurrencyCheck, Disabled, MemberOrder(1000)]
public virtual DateTime LastModified { get; set; }
#endregion
private IQueryable<Transaction> AllTransactionsForAccountFrom(DateTime after)
{
int id = Id;
return Container.Instances<Transaction>().Where(x => (x.CreditAccount.Id == id ||
x.DebitAccount.Id == id)
&& x.Date > after);
}
internal void PersistBalance(DateTime asOf)
{
var pb = NewTransientBalance(asOf, PersistedBalance.PeriodCloseBalance);
pb.Date = asOf;
SetDebitOrCreditOnBalance(pb);
Container.Persist(ref pb);
}
private IAccountEntry CreateCurrentBalance()
{
var currentBalance = Container.NewViewModel<CurrentBalance>();
SetDebitOrCreditOnBalance(currentBalance);
return currentBalance;
}
private void SetDebitOrCreditOnBalance(IAccountBalance balance)
{
var openingbalance = GetMostRecentPersistedBalance();
decimal openingDebitValue = openingbalance.Debit ?? new decimal(0);
decimal openingCreditValue = openingbalance.Credit ?? new decimal(0);
var trans = AllTransactionsForAccountFrom(openingbalance.Date);
var newDebits = trans.Where(x => x.DebitAccount.Id == Id).Select(x => x.Amount).DefaultIfEmpty(0).Sum(); //Cant' use Sum(x => x.Amount) if there are no Transactions
var newCredits = trans.Where(x => x.CreditAccount.Id == Id).Select(x => x.Amount).DefaultIfEmpty(0).Sum();
var currentDebit = openingDebitValue + newDebits;
var currentCredit = openingCreditValue + newCredits;
if (currentCredit == currentDebit)
{
switch (Type)
{
case AccountTypes.Income:
balance.Credit = new decimal(0);
balance.Debit = null;
break;
case AccountTypes.Expense:
balance.Credit = null;
balance.Debit = new decimal(0);
break;
case AccountTypes.Asset:
balance.Credit = null;
balance.Debit = new decimal(0);
break;
case AccountTypes.Liability:
balance.Credit = new decimal(0);
balance.Debit = null;
break;
default:
throw new DomainException("Unrecognised Account Type");
}
}
else if (currentCredit > currentDebit)
{
balance.Credit = currentCredit - currentDebit;
}
else
{
balance.Debit = currentDebit - currentCredit;
}
}
#region Balances
internal PersistedBalance GetMostRecentPersistedBalance()
{
return Container.Instances<PersistedBalance>().Where(x => x.Account.Id == Id).OrderByDescending(x => x.Date).ThenBy(x => x.Id).FirstOrDefault();
}
internal PersistedBalance CreateOpeningBalance(decimal balance, DateTime asOf)
{
switch (Type)
{
case AccountTypes.Income:
return SetOpeningBalance(null, balance, asOf);
case AccountTypes.Expense:
return SetOpeningBalance(balance, null, asOf);
case AccountTypes.Asset:
return SetOpeningBalance(balance, null, asOf);
case AccountTypes.Liability:
return SetOpeningBalance(null, balance, asOf);
}
throw new DomainException("Unrecognised Account Type");
}
private PersistedBalance SetOpeningBalance(decimal? debitAmount, decimal? creditAmount, DateTime asOf)
{
var bal = NewTransientBalance(asOf, PersistedBalance.OpeningBalance);
bal.Debit = debitAmount;
bal.Credit = creditAmount;
Container.Persist(ref bal);
return bal;
}
private PersistedBalance NewTransientBalance(DateTime asOf, string description)
{
var bal = Container.NewTransientInstance<PersistedBalance>();
bal.Account = this;
bal.Description = description;
bal.Debit = null;
bal.Credit = null;
bal.Date = asOf;
return bal;
}
#endregion
#region Reconciliation
public IQueryable<TransactionInAccountView> UnreconciledTransactions()
{
//Find all transactions on this account that are not reconciled.
//Present them as TransactionInAccountView
throw new NotImplementedException();
}
#endregion
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using PrimerProObjects;
using PrimerProLocalization;
using GenLib;
namespace PrimerProForms
{
/// <summary>
/// Summary description for FormSearchOptions.
/// </summary>
public class FormGeneralTD : System.Windows.Forms.Form
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private System.Windows.Forms.Button btnOK;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.CheckBox ckVwlSame;
private System.Windows.Forms.Label labWordCV;
private System.Windows.Forms.TextBox tbWordCV;
private bool m_ParaFormat; //how to display the results
private bool m_UseGraphemesTaught; //restrict to graphemes taught
private bool m_NoDuplicates; //do not display duplicate words
private bool m_IsIdenticalVowelsInWord;
private string m_WordCVShape;
private int m_MinSyllables;
private int m_MaxSyllables;
private NumericUpDown nudMinSyllables;
private Label labMinSyllable;
private Label labMaxSyllables;
private NumericUpDown nudMaxSyllables;
//private string m_Title; //Search title
private Settings m_Settings; // Global settings
private Font m_DefaultFont;
private CheckBox ckNoDup;
private CheckBox ckGraphemesTaught;
private CheckBox ckParaFmt; // Default Font
private bool m_ViewParaSentWord; //Flag for viewing ParaSentWord number
public FormGeneralTD(Settings s)
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
m_Settings = s;
m_DefaultFont = m_Settings.OptionSettings.GetDefaultFont();
m_ViewParaSentWord = m_Settings.OptionSettings.ViewParaSentWord;
m_ParaFormat = false;
m_UseGraphemesTaught = false;
m_NoDuplicates = false;
m_IsIdenticalVowelsInWord = false;
m_WordCVShape = "";
m_MinSyllables = 0;
m_MaxSyllables = 0;
}
public FormGeneralTD(Settings s, LocalizationTable table)
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
m_Settings = s;
m_DefaultFont = m_Settings.OptionSettings.GetDefaultFont();
m_ViewParaSentWord = m_Settings.OptionSettings.ViewParaSentWord;
m_ParaFormat = false;
m_UseGraphemesTaught = false;
m_NoDuplicates = false;
m_IsIdenticalVowelsInWord = false;
m_WordCVShape = "";
m_MinSyllables = 0;
m_MaxSyllables = 0;
this.UpdateFormForLocalization(table);
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormGeneralTD));
this.btnOK = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.ckVwlSame = new System.Windows.Forms.CheckBox();
this.labWordCV = new System.Windows.Forms.Label();
this.tbWordCV = new System.Windows.Forms.TextBox();
this.nudMinSyllables = new System.Windows.Forms.NumericUpDown();
this.labMinSyllable = new System.Windows.Forms.Label();
this.labMaxSyllables = new System.Windows.Forms.Label();
this.nudMaxSyllables = new System.Windows.Forms.NumericUpDown();
this.ckNoDup = new System.Windows.Forms.CheckBox();
this.ckGraphemesTaught = new System.Windows.Forms.CheckBox();
this.ckParaFmt = new System.Windows.Forms.CheckBox();
((System.ComponentModel.ISupportInitialize)(this.nudMinSyllables)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.nudMaxSyllables)).BeginInit();
this.SuspendLayout();
//
// btnOK
//
this.btnOK.DialogResult = System.Windows.Forms.DialogResult.OK;
this.btnOK.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnOK.Location = new System.Drawing.Point(302, 183);
this.btnOK.Name = "btnOK";
this.btnOK.Size = new System.Drawing.Size(86, 26);
this.btnOK.TabIndex = 10;
this.btnOK.Text = "OK";
this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
//
// btnCancel
//
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnCancel.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnCancel.Location = new System.Drawing.Point(423, 183);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(85, 26);
this.btnCancel.TabIndex = 11;
this.btnCancel.Text = "Cancel";
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// ckVwlSame
//
this.ckVwlSame.AutoSize = true;
this.ckVwlSame.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.ckVwlSame.Location = new System.Drawing.Point(24, 24);
this.ckVwlSame.Name = "ckVwlSame";
this.ckVwlSame.Size = new System.Drawing.Size(149, 19);
this.ckVwlSame.TabIndex = 0;
this.ckVwlSame.Text = "&All vowels are identical";
this.ckVwlSame.CheckedChanged += new System.EventHandler(this.ckVwlSame_CheckedChanged);
//
// labWordCV
//
this.labWordCV.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labWordCV.Location = new System.Drawing.Point(24, 64);
this.labWordCV.Name = "labWordCV";
this.labWordCV.Size = new System.Drawing.Size(140, 19);
this.labWordCV.TabIndex = 1;
this.labWordCV.Text = "Word CV Shape";
//
// tbWordCV
//
this.tbWordCV.CharacterCasing = System.Windows.Forms.CharacterCasing.Upper;
this.tbWordCV.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.tbWordCV.Location = new System.Drawing.Point(160, 64);
this.tbWordCV.Name = "tbWordCV";
this.tbWordCV.Size = new System.Drawing.Size(103, 21);
this.tbWordCV.TabIndex = 2;
this.tbWordCV.TextChanged += new System.EventHandler(this.tbWordCV_TextChanged);
//
// nudMinSyllables
//
this.nudMinSyllables.Location = new System.Drawing.Point(236, 102);
this.nudMinSyllables.Maximum = new decimal(new int[] {
9,
0,
0,
0});
this.nudMinSyllables.Name = "nudMinSyllables";
this.nudMinSyllables.Size = new System.Drawing.Size(32, 21);
this.nudMinSyllables.TabIndex = 4;
this.nudMinSyllables.ValueChanged += new System.EventHandler(this.nudMinSyllables_ValueChanged);
//
// labMinSyllable
//
this.labMinSyllable.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labMinSyllable.Location = new System.Drawing.Point(24, 102);
this.labMinSyllable.Name = "labMinSyllable";
this.labMinSyllable.Size = new System.Drawing.Size(204, 19);
this.labMinSyllable.TabIndex = 3;
this.labMinSyllable.Text = "Minimal Number of Syllables";
//
// labMaxSyllables
//
this.labMaxSyllables.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labMaxSyllables.Location = new System.Drawing.Point(24, 132);
this.labMaxSyllables.Name = "labMaxSyllables";
this.labMaxSyllables.Size = new System.Drawing.Size(203, 19);
this.labMaxSyllables.TabIndex = 5;
this.labMaxSyllables.Text = "Maximal Number of Syllables";
//
// nudMaxSyllables
//
this.nudMaxSyllables.Location = new System.Drawing.Point(236, 132);
this.nudMaxSyllables.Maximum = new decimal(new int[] {
9,
0,
0,
0});
this.nudMaxSyllables.Name = "nudMaxSyllables";
this.nudMaxSyllables.Size = new System.Drawing.Size(32, 21);
this.nudMaxSyllables.TabIndex = 6;
this.nudMaxSyllables.ValueChanged += new System.EventHandler(this.nudMaxSyllables_ValueChanged);
//
// ckNoDup
//
this.ckNoDup.AutoSize = true;
this.ckNoDup.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.ckNoDup.Location = new System.Drawing.Point(330, 120);
this.ckNoDup.Margin = new System.Windows.Forms.Padding(2);
this.ckNoDup.Name = "ckNoDup";
this.ckNoDup.Size = new System.Drawing.Size(103, 19);
this.ckNoDup.TabIndex = 9;
this.ckNoDup.Text = "No Duplicates";
this.ckNoDup.UseVisualStyleBackColor = true;
//
// ckGraphemesTaught
//
this.ckGraphemesTaught.AutoSize = true;
this.ckGraphemesTaught.Location = new System.Drawing.Point(330, 72);
this.ckGraphemesTaught.Name = "ckGraphemesTaught";
this.ckGraphemesTaught.Size = new System.Drawing.Size(189, 19);
this.ckGraphemesTaught.TabIndex = 8;
this.ckGraphemesTaught.Text = "&Restrict to Graphemes Taught";
this.ckGraphemesTaught.UseVisualStyleBackColor = true;
//
// ckParaFmt
//
this.ckParaFmt.AutoSize = true;
this.ckParaFmt.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.ckParaFmt.Location = new System.Drawing.Point(330, 24);
this.ckParaFmt.Name = "ckParaFmt";
this.ckParaFmt.Size = new System.Drawing.Size(177, 19);
this.ckParaFmt.TabIndex = 7;
this.ckParaFmt.Text = "Display in ¶graph format";
this.ckParaFmt.UseVisualStyleBackColor = true;
this.ckParaFmt.CheckedChanged += new System.EventHandler(this.ckParaFmt_CheckedChanged);
//
// FormGeneralTD
//
this.AcceptButton = this.btnOK;
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.CancelButton = this.btnCancel;
this.ClientSize = new System.Drawing.Size(571, 221);
this.Controls.Add(this.ckNoDup);
this.Controls.Add(this.ckGraphemesTaught);
this.Controls.Add(this.ckParaFmt);
this.Controls.Add(this.labMaxSyllables);
this.Controls.Add(this.nudMaxSyllables);
this.Controls.Add(this.labMinSyllable);
this.Controls.Add(this.nudMinSyllables);
this.Controls.Add(this.tbWordCV);
this.Controls.Add(this.labWordCV);
this.Controls.Add(this.ckVwlSame);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnOK);
this.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "FormGeneralTD";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "General Search";
((System.ComponentModel.ISupportInitialize)(this.nudMinSyllables)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.nudMaxSyllables)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
public bool ParaFormat
{
get { return m_ParaFormat; }
}
public bool UseGraphemesTaught
{
get { return m_UseGraphemesTaught; }
}
public bool NoDuplicates
{
get { return m_NoDuplicates; }
}
public bool IsIdenticalVowelsInWord
{
get {return m_IsIdenticalVowelsInWord;}
}
public string WordCVShape
{
get {return m_WordCVShape;}
}
public int MinSyllables
{
get { return m_MinSyllables; }
}
public int MaxSyllables
{
get { return m_MaxSyllables; }
}
private void ckVwlSame_CheckedChanged(object sender, System.EventArgs e)
{
//ckVwlInRootSame.Checked = ckVwlSame.Checked;
}
private void tbWordCV_TextChanged(object sender, System.EventArgs e)
{
string str1 = tbWordCV.Text;
string str2 = "";
for (int i = 0; i < str1.Length; i++)
{
if ( (str1.Substring(i,1) == "C") || (str1.Substring(i,1) == "V") )
str2 += str1.Substring(i,1);
}
tbWordCV.Text = str2;
}
private void nudMinSyllables_ValueChanged(object sender, EventArgs e)
{
if (nudMaxSyllables.Value < nudMinSyllables.Value)
nudMaxSyllables.Value = nudMinSyllables.Value;
}
private void nudMaxSyllables_ValueChanged(object sender, EventArgs e)
{
if (nudMinSyllables.Value > nudMaxSyllables.Value)
nudMinSyllables.Value = nudMaxSyllables.Value;
}
private void ckParaFmt_CheckedChanged(object sender, EventArgs e)
{
if (ckParaFmt.Checked)
{
ckNoDup.Checked = false;
ckNoDup.Enabled = false;
}
else ckNoDup.Enabled = true;
}
private void btnOK_Click(object sender, System.EventArgs e)
{
m_IsIdenticalVowelsInWord = ckVwlSame.Checked;
m_WordCVShape = tbWordCV.Text;
m_MinSyllables = Convert.ToInt16(nudMinSyllables.Value);
m_MaxSyllables = Convert.ToInt16(nudMaxSyllables.Value);
m_ParaFormat = ckParaFmt.Checked;
m_UseGraphemesTaught = ckGraphemesTaught.Checked;
m_NoDuplicates = ckNoDup.Checked;
}
private void btnCancel_Click(object sender, System.EventArgs e)
{
m_IsIdenticalVowelsInWord = false;
m_WordCVShape = "";
m_MinSyllables = 0;
m_MaxSyllables = 0;
this.Close();
}
private void UpdateFormForLocalization(LocalizationTable table)
{
string strText = "";
strText = table.GetForm("FormGeneralTDT");
if (strText != "")
this.Text = strText;
strText = table.GetForm("FormGeneralTD0");
if (strText != "")
this.ckVwlSame.Text = strText;
strText = table.GetForm("FormGeneralTD1");
if (strText != "")
this.labWordCV.Text = strText;
strText = table.GetForm("FormGeneralTD3");
if (strText != "")
this.labMinSyllable.Text = strText;
strText = table.GetForm("FormGeneralTD5");
if (strText != "")
this.labMaxSyllables.Text = strText;
strText = table.GetForm("FormGeneralTD7");
if (strText != "")
this.ckParaFmt.Text = strText;
strText = table.GetForm("FormGeneralTD8");
if (strText != "")
this.ckGraphemesTaught.Text = strText;
strText = table.GetForm("FormGeneralTD9");
if (strText != "")
this.ckNoDup.Text = strText;
strText = table.GetForm("FormGeneralTD10");
if (strText != "")
this.btnOK.Text = strText;
strText = table.GetForm("FormGeneralTD11");
if (strText != "")
this.btnCancel.Text = strText;
return;
}
}
}
| |
//! \file ArcCPZ.cs
//! \date Tue Nov 24 11:27:23 2015
//! \brief Purple Software resource archive.
//
// Copyright (C) 2015-2019 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using GameRes.Utility;
namespace GameRes.Formats.Purple
{
[Serializable]
public class CmvsScheme
{
public int Version;
public uint[] Cpz5Secret;
public Cmvs.Md5Variant Md5Variant;
public uint DecoderFactor;
public uint EntryInitKey;
public uint EntrySubKey = 0x5C29E87B;
public byte EntryTailKey;
public byte EntryKeyPos = 9;
public uint IndexSeed = 0x2A65CB4E;
public uint IndexAddend = 0x784C5962;
public uint IndexSubtrahend = 0x79;
public uint[] DirKeyAddend = DefaultDirKeyAddend;
static readonly uint[] DefaultDirKeyAddend = { 0, 0x00112233, 0, 0x34258765 };
}
internal class CpzEntry : Entry
{
public uint CheckSum;
public uint Key;
}
internal class CpzArchive : ArcFile
{
public CpzHeader Header;
public Cpz5Decoder Decoder;
public ArchiveKey Key;
public CpzArchive (ArcView arc, ArchiveFormat impl, ICollection<Entry> dir, CpzHeader header, Cpz5Decoder decoder, ArchiveKey key)
: base (arc, impl, dir)
{
Header = header;
Decoder = decoder;
Key = key;
}
}
[Serializable]
public class CpzScheme : ResourceScheme
{
public Dictionary<string, CmvsScheme> KnownSchemes;
}
[Export(typeof(ArchiveFormat))]
public class CpzOpener : ArchiveFormat
{
public override string Tag { get { return "CPZ"; } }
public override string Description { get { return "CMVS engine resource archive"; } }
public override uint Signature { get { return 0x355A5043; } } // 'CPZ5'
public override bool IsHierarchic { get { return true; } }
public override bool CanWrite { get { return false; } }
public CpzOpener ()
{
Signatures = new uint[] { 0x355A5043, 0x365A5043, 0x375A5043 };
}
static CpzScheme DefaultScheme = new CpzScheme();
internal Dictionary<string, CmvsScheme> KnownSchemes { get { return DefaultScheme.KnownSchemes; } }
public override ResourceScheme Scheme
{
get { return DefaultScheme; }
set { DefaultScheme = (CpzScheme)value; }
}
public override ArcFile TryOpen (ArcView file)
{
if (null == KnownSchemes)
throw new OperationCanceledException ("Outdated encryption schemes database");
var cpz = CpzHeader.Parse (file);
if (null == cpz)
return null;
var index = file.View.ReadBytes (cpz.IndexOffset, cpz.IndexSize);
if (!cpz.VerifyIndex (index))
return null;
int file_table_size = cpz.DirEntriesSize + cpz.FileEntriesSize;
if (cpz.IndexKeySize > 24)
{
var index_key = UnpackIndexKey (index, file_table_size, cpz.IndexKeySize);
for (int i = 0; i < file_table_size; ++i)
{
index[i] ^= index_key[(i + 3) % 0x3FF];
}
}
ArchiveKey arc_key = null;
if (cpz.Version > 6)
arc_key = FindArchiveKey (file.Name);
if (null == arc_key)
arc_key = new ArchiveKey();
var index_copy = new CowArray<byte> (index, 0, file_table_size).ToArray();
var cmvs_md5 = cpz.CmvsMd5.Clone() as uint[];
foreach (var scheme in KnownSchemes.Values.Where (s => s.Version == cpz.Version))
{
var arc = ReadIndex (file, scheme, cpz, index, arc_key);
if (null != arc)
return arc;
// both CmvsMd5 and index was altered by ReadIndex in decryption attempt
Array.Copy (cmvs_md5, cpz.CmvsMd5, 4);
Array.Copy (index, index_copy, file_table_size);
}
throw new UnknownEncryptionScheme();
}
internal ArcFile ReadIndex (ArcView file, CmvsScheme scheme, CpzHeader cpz, byte[] index, ArchiveKey arc_key)
{
var cmvs_md5 = Cmvs.MD5.Create (scheme.Md5Variant);
cmvs_md5.Compute (cpz.CmvsMd5);
DecryptIndexStage1 (index, cpz.MasterKey ^ 0x3795B39A, scheme);
var decoder = new Cpz5Decoder (scheme, cpz.MasterKey, cpz.CmvsMd5[1]);
decoder.Decode (index, 0, cpz.DirEntriesSize, 0x3A);
var key = new uint[4];
key[0] = cpz.CmvsMd5[0] ^ (cpz.MasterKey + 0x76A3BF29);
key[1] = cpz.CmvsMd5[1] ^ cpz.MasterKey;
key[2] = cpz.CmvsMd5[2] ^ (cpz.MasterKey + 0x10000000);
key[3] = cpz.CmvsMd5[3] ^ cpz.MasterKey;
DecryptIndexDirectory (index, cpz.DirEntriesSize, key, arc_key.IndexDirKey);
decoder.Init (cpz.MasterKey, cpz.CmvsMd5[2]);
uint base_offset = cpz.IndexOffset + cpz.IndexSize;
int dir_offset = 0;
var dir = new List<Entry>();
for (int i = 0; i < cpz.DirCount; ++i)
{
int dir_size = LittleEndian.ToInt32 (index, dir_offset);
if (dir_size <= 0x10 || dir_size > index.Length)
return null;
int file_count = LittleEndian.ToInt32 (index, dir_offset+4);
if (file_count >= 0x10000)
return null;
int entries_offset = LittleEndian.ToInt32 (index, dir_offset+8);
uint dir_key = LittleEndian.ToUInt32 (index, dir_offset+0xC);
var dir_name = Binary.GetCString (index, dir_offset+0x10, dir_size-0x10);
int next_entries_offset;
if (i + 1 == cpz.DirCount)
next_entries_offset = cpz.FileEntriesSize;
else
next_entries_offset = LittleEndian.ToInt32 (index, dir_offset + dir_size + 8);
int cur_entries_size = next_entries_offset - entries_offset;
if (cur_entries_size <= 0)
return null;
int cur_offset = cpz.DirEntriesSize + entries_offset;
int cur_entries_end = cur_offset + cur_entries_size;
decoder.Decode (index, cur_offset, cur_entries_size, 0x7E);
for (int j = 0; j < 4; ++j)
key[j] = cpz.CmvsMd5[j] ^ (dir_key + scheme.DirKeyAddend[j]);
DecryptIndexEntry (index, cur_offset, cur_entries_size, key, scheme.IndexSeed, arc_key.IndexEntryKey);
bool is_root_dir = dir_name == "root";
dir.Capacity = dir.Count + file_count;
for (int j = 0; j < file_count; ++j)
{
int entry_size = LittleEndian.ToInt32 (index, cur_offset);
if (entry_size > index.Length || entry_size <= cpz.EntryNameOffset)
return null;
int name_offset = cur_offset + cpz.EntryNameOffset;
var name = Binary.GetCString (index, name_offset, cur_entries_end - name_offset);
if (!is_root_dir)
name = Path.Combine (dir_name, name);
var entry = FormatCatalog.Instance.Create<CpzEntry> (name);
entry.Offset = LittleEndian.ToInt64 (index, cur_offset+4) + base_offset;
entry.Size = LittleEndian.ToUInt32 (index, cur_offset+0xC);
int key_offset = cur_offset + 0x10;
if (cpz.IsLongSize)
key_offset += 4;
entry.CheckSum = LittleEndian.ToUInt32 (index, key_offset);
entry.Key = LittleEndian.ToUInt32 (index, key_offset+4) + dir_key;
if (!entry.CheckPlacement (file.MaxOffset))
return null;
dir.Add (entry);
cur_offset += entry_size;
}
dir_offset += dir_size;
}
if (cpz.IsEncrypted)
decoder.Init (cpz.CmvsMd5[3], cpz.MasterKey);
return new CpzArchive (file, this, dir, cpz, decoder, arc_key);
}
public override Stream OpenEntry (ArcFile arc, Entry entry)
{
var carc = arc as CpzArchive;
var cent = entry as CpzEntry;
if (null == carc || null == cent)
return base.OpenEntry (arc, entry);
var data = carc.File.View.ReadBytes (entry.Offset, entry.Size);
if (carc.Header.IsEncrypted)
{
uint key = (carc.Header.MasterKey ^ cent.Key) + (uint)carc.Header.DirCount;
key ^= carc.Key.EntryDataKey2;
key -= carc.Decoder.Scheme.EntrySubKey;
key ^= carc.Header.EntryKey + carc.Key.EntryDataKey1;
carc.Decoder.DecryptEntry (data, carc.Header.CmvsMd5, key);
}
if (data.Length > 0x30 && Binary.AsciiEqual (data, 0, "PS2A"))
data = UnpackPs2 (data);
else if (data.Length > 0x40 && Binary.AsciiEqual (data, 0, "PB3B"))
DecryptPb3 (data);
return new BinMemoryStream (data, entry.Name);
}
internal byte[] UnpackIndexKey (byte[] data, int offset, int length)
{
int key_offset = offset + 20;
int packed_offset = offset + 24;
int packed_length = length - 24;
for (int i = 0; i < packed_length; ++i)
{
data[packed_offset + i] ^= data[key_offset + (i & 3)];
}
int unpacked_length = data.ToInt32 (offset + 16);
var output = new byte[unpacked_length];
var decoder = new HuffmanDecoder (data, packed_offset, packed_length, output);
return decoder.Unpack();
}
void DecryptIndexStage1 (byte[] data, uint key, CmvsScheme scheme)
{
var secret = scheme.Cpz5Secret;
var secret_key = new uint[24];
int secret_length = Math.Min (24, secret.Length);
for (int i = 0; i < secret_length; ++i)
secret_key[i] = secret[i] - key;
int shift = (int)(((key >> 24) ^ (key >> 16) ^ (key >> 8) ^ key ^ 0xB) & 0xF) + 7;
unsafe
{
fixed (byte* raw = data)
{
uint* data32 = (uint*)raw;
int i = 5;
for (int n = data.Length / 4; n > 0; --n)
{
*data32 = Binary.RotR ((secret_key[i] ^ *data32) + scheme.IndexAddend, shift) + 0x01010101;
++data32;
i = (i + 1) % 24;
}
byte* data8 = (byte*)data32;
for (int n = data.Length & 3; n > 0; --n)
{
*data8 = (byte)((*data8 ^ (secret_key[i] >> (n * 4))) - scheme.IndexSubtrahend);
++data8;
i = (i + 1) % 24;
}
}
}
}
void EncryptIndexStage1 (byte[] data, uint key, CmvsScheme scheme)
{
var secret = scheme.Cpz5Secret;
var secret_key = new uint[24];
int secret_length = Math.Min(24, secret.Length);
for (int i = 0; i < secret_length; ++i)
secret_key[i] = secret[i] - key;
int shift = (int)(((key >> 24) ^ (key >> 16) ^ (key >> 8) ^ key ^ 0xB) & 0xF) + 7;
unsafe
{
fixed (byte* raw = data)
{
uint* data32 = (uint*)raw;
int i = 5;
for (int n = data.Length / 4; n > 0; --n)
{
*data32 = (Binary.RotL((*data32 - 0x01010101), shift) - scheme.IndexAddend) ^ secret_key[i];
++data32;
i = (i + 1) % 24;
}
byte* data8 = (byte*)data32;
for (int n = data.Length & 3; n > 0; --n)
{
*data8 = (byte)((*data8 + scheme.IndexSubtrahend) ^ (secret_key[i] >> (n * 4)));
++data8;
i = (i + 1) % 24;
}
}
}
}
void DecryptIndexDirectory (byte[] data, int length, uint[] key, uint arc_key)
{
uint seed = 0x76548AEF;
unsafe
{
fixed (byte* raw = data)
{
uint* data32 = (uint*)raw;
int i;
for (i = 0; i < length / 4; ++i)
{
*data32 = Binary.RotL ((*data32 ^ key[i & 3]) - 0x4A91C262, 3) - seed;
++data32;
seed += 0x10FB562Au ^ arc_key;
}
byte* data8 = (byte*)data32;
for (int j = length & 3; j > 0; --j)
{
*data8 = (byte)((*data8 ^ (key[i++ & 3] >> 6)) + 0x37);
++data8;
}
}
}
}
void EncryptIndexDirectory (byte[] data, int length, uint[] key)
{
uint seed = 0x76548AEF;
unsafe
{
fixed (byte* raw = data)
{
uint* data32 = (uint*)raw;
int i;
for (i = 0; i < length / 4; ++i)
{
*data32 = (Binary.RotR(*data32 + seed, 3) + 0x4A91C262) ^ key[i & 3];
++data32;
seed += 0x10FB562A;
}
byte* data8 = (byte*)data32;
for (int j = length & 3; j > 0; --j)
{
*data8 = (byte)((*data8 - 0x37) ^ (key[i++ & 3] >> 6));
++data8;
}
}
}
}
void DecryptIndexEntry (byte[] data, int offset, int length, uint[] key, uint seed, uint arc_key)
{
if (offset < 0 || offset > data.Length)
throw new ArgumentOutOfRangeException ("offset");
if (length < 0 || length > data.Length || length > data.Length-offset)
throw new ArgumentException ("length");
unsafe
{
fixed (byte* raw = &data[offset])
{
uint* data32 = (uint*)raw;
int i;
for (i = 0; i < length / 4; ++i)
{
*data32 = Binary.RotL ((*data32 ^ key[i & 3]) - seed, 2) + 0x37A19E8B;
++data32;
seed -= 0x139FA9B ^ arc_key;
}
byte* data8 = (byte*)data32;
for (int j = length & 3; j > 0; --j)
{
*data8 = (byte)((*data8 ^ (key[i++ & 3] >> 4)) + 5);
++data8;
}
}
}
}
void EncryptIndexEntry (byte[] data, int offset, int length, uint[] key, uint seed)
{
if (offset < 0 || offset > data.Length)
throw new ArgumentOutOfRangeException("offset");
if (length < 0 || length > data.Length || length > data.Length - offset)
throw new ArgumentException("length");
unsafe
{
fixed (byte* raw = &data[offset])
{
uint* data32 = (uint*)raw;
int i;
for (i = 0; i < length / 4; ++i)
{
*data32 = (Binary.RotR((*data32 - 0x37A19E8B), 2) + seed) ^ key[i & 3];
++data32;
seed -= 0x139FA9B;
}
byte* data8 = (byte*)data32;
for (int j = length & 3; j > 0; --j)
{
*data8 = (byte)((*data8 - 5) ^ (key[i++ & 3] >> 4));
++data8;
}
}
}
}
byte[] UnpackPs2 (byte[] data)
{
DecryptPs2 (data);
return UnpackLzss (data);
}
internal static byte[] UnpackLzss (byte[] data)
{
byte[] frame = new byte[0x800];
int frame_pos = 0x7DF;
int unpacked_size = LittleEndian.ToInt32 (data, 0x28);
byte[] output = new byte[0x30+unpacked_size];
Buffer.BlockCopy (data, 0, output, 0, 0x30);
int src = 0x30;
int dst = 0x30;
int ctl = 1;
while (dst < output.Length && src < data.Length)
{
if (1 == ctl)
ctl = data[src++] | 0x100;
if (0 != (ctl & 1))
{
byte b = data[src++];
output[dst++] = b;
frame[frame_pos++] = b;
frame_pos &= 0x7FF;
}
else
{
int lo = data[src++];
int hi = data[src++];
int offset = lo | (hi & 0xE0) << 3;
int count = (hi & 0x1F) + 2;
for (int i = 0; i < count; ++i)
{
byte b = frame[(offset + i) & 0x7FF];
output[dst++] = b;
frame[frame_pos++] = b;
frame_pos &= 0x7FF;
}
}
ctl >>= 1;
}
return output;
}
void DecryptPs2 (byte[] data)
{
uint key = LittleEndian.ToUInt32 (data, 12);
int shift = (int)(key >> 20) % 5 + 1;
key = (key >> 24) + (key >> 3);
for (int i = 0x30; i < data.Length; ++i)
{
data[i] = Binary.RotByteR ((byte)(key ^ (data[i] - 0x7Cu)), shift);
}
}
void DecryptPb3 (byte[] data)
{
byte key1 = data[data.Length-3];
byte key2 = data[data.Length-2];
int src = data.Length - 0x2F;
for (int i = 8; i < 0x34; i += 2)
{
data[i ] ^= key1;
data[i ] -= data[src++];
data[i+1] ^= key2;
data[i+1] -= data[src++];
}
}
void EncryptPb3 (byte[] data)
{
byte key1 = data[data.Length - 3];
byte key2 = data[data.Length - 2];
int src = data.Length - 0x2F;
for (int i = 8; i < 0x34; i += 2)
{
data[i] += data[src++];
data[i] ^= key1;
data[i + 1] += data[src++];
data[i + 1] ^= key2;
}
}
ArchiveKey FindArchiveKey (string arc_name)
{
// look for "start.ps3" in the same directory as an archive
var start_name = VFS.ChangeFileName (arc_name, "start.ps3");
if (!VFS.FileExists (start_name))
return null;
byte[] start_data;
using (var start = VFS.OpenView (start_name))
{
if (!start.View.AsciiEqual (0, "PS2A"))
return null;
start_data = start.View.ReadBytes (0, (uint)start.MaxOffset);
}
arc_name = Path.GetFileName (arc_name);
start_data = UnpackPs2 (start_data);
int table_count = start_data.ToInt32 (0x10);
int strings_offset = 0x30 + table_count * 4 + start_data.ToInt32 (0x14);
int strings_size = start_data.ToInt32 (0x1C);
if (strings_offset < 0x30 || strings_offset + strings_size > start_data.Length)
return null;
// search strings table for archive name
int string_pos = strings_offset;
int strings_end = strings_offset + strings_size;
int arc_id = -1;
while (string_pos < strings_end)
{
int end_pos = Array.IndexOf<byte> (start_data, 0, string_pos);
if (-1 == end_pos)
end_pos = strings_offset + strings_size;
if (end_pos != string_pos)
{
var text = Encodings.cp932.GetString (start_data, string_pos, end_pos - string_pos);
if (VFS.IsPathEqualsToFileName (text, arc_name))
{
arc_id = string_pos - strings_offset;
break;
}
}
string_pos = end_pos + 1;
}
if (-1 == arc_id)
return null;
// search bytecode for a reference to archive name found above
var id_bytes = new byte[4];
LittleEndian.Pack (arc_id, id_bytes, 0);
for (int data_pos = 0x30 + table_count * 4; data_pos + 4 <= strings_offset; ++data_pos)
{
if (start_data[data_pos+0] == id_bytes[0] && start_data[data_pos+1] == id_bytes[1] &&
start_data[data_pos+2] == id_bytes[2] && start_data[data_pos+3] == id_bytes[3])
{
if (start_data[data_pos-0x33] == 2 && start_data[data_pos-0x32] == 0 &&
start_data[data_pos-0x31] == 1)
{
return new ArchiveKey {
IndexDirKey = start_data.ToUInt32 (data_pos-0x0C),
IndexEntryKey = start_data.ToUInt32 (data_pos-0x18),
EntryDataKey1 = start_data.ToUInt32 (data_pos-0x24),
EntryDataKey2 = start_data.ToUInt32 (data_pos-0x30),
};
}
}
}
return null;
}
}
internal class Cpz5Decoder
{
protected byte[] m_decode_table = new byte[0x100];
protected CmvsScheme m_scheme;
public CmvsScheme Scheme { get { return m_scheme; } }
public Cpz5Decoder (CmvsScheme scheme, uint key, uint summand)
{
m_scheme = scheme;
Init (key, summand);
}
public void Init (uint key, uint summand)
{
for (int i = 0; i < 0x100; ++i)
m_decode_table[i] = (byte)i;
for (int i = 0; i < 0x100; ++i)
{
uint i0 = (key >> 16) & 0xFF;
uint i1 = key & 0xFF;
var tmp = m_decode_table[i0];
m_decode_table[i0] = m_decode_table[i1];
m_decode_table[i1] = tmp;
i0 = (key >> 8) & 0xFF;
i1 = key >> 24;
tmp = m_decode_table[i0];
m_decode_table[i0] = m_decode_table[i1];
m_decode_table[i1] = tmp;
key = summand + m_scheme.DecoderFactor * Binary.RotR (key, 2);
}
}
public void Decode (byte[] data, int offset, int length, byte key)
{
for (int i = 0; i < length; ++i)
data[offset+i] = m_decode_table[key ^ data[offset+i]];
}
public void Encode (byte[] data, int offset, int length, byte key)
{
for (int i = 0; i < length; ++i)
{
for (int s = 0; s < m_decode_table.Length; s++)
{
if (data[offset+i] == m_decode_table[s])
{
data[offset+i] = (byte)(key ^ s);
break;
}
}
}
}
public void DecryptEntry (byte[] data, uint[] cmvs_md5, uint seed)
{
if (null == data)
throw new ArgumentNullException ("data");
if (null == cmvs_md5 || cmvs_md5.Length < 4)
throw new ArgumentException ("cmvs_md5");
int secret_length = Math.Min (m_scheme.Cpz5Secret.Length, 0x10) * sizeof(uint);
byte[] key_bytes = new byte[secret_length];
uint key = cmvs_md5[1] >> 2;
Buffer.BlockCopy (m_scheme.Cpz5Secret, 0, key_bytes, 0, secret_length);
for (int i = 0; i < secret_length; ++i)
key_bytes[i] = (byte)(key ^ m_decode_table[key_bytes[i]]);
uint[] secret_key = new uint[0x10];
Buffer.BlockCopy (key_bytes, 0, secret_key, 0, secret_length);
for (int i = 0; i < secret_key.Length; ++i)
secret_key[i] ^= seed;
unsafe
{
fixed (byte* raw = data)
{
uint* data32 = (uint*)raw;
key = m_scheme.EntryInitKey;
int k = m_scheme.EntryKeyPos;
for (int i = data.Length / 4; i > 0; --i)
{
*data32 = cmvs_md5[key & 3] ^ ((*data32 ^ secret_key[(key >> 6) & 0xf] ^ (secret_key[k] >> 1)) - seed);
k = (k + 1) & 0xf;
key += seed + *data32++;
}
byte* data8 = (byte*)data32;
for (int i = data.Length & 3; i > 0; --i)
{
*data8 = m_decode_table[*data8 ^ m_scheme.EntryTailKey];
++data8;
}
}
}
}
public void EncryptEntry (byte[] data, uint[] cmvs_md5, uint seed)
{
if (null == data)
throw new ArgumentNullException("data");
if (null == cmvs_md5 || cmvs_md5.Length < 4)
throw new ArgumentException("cmvs_md5");
int secret_length = Math.Min(m_scheme.Cpz5Secret.Length, 0x10) * sizeof(uint);
byte[] key_bytes = new byte[secret_length];
uint key = cmvs_md5[1] >> 2;
Buffer.BlockCopy(m_scheme.Cpz5Secret, 0, key_bytes, 0, secret_length);
for (int i = 0; i < secret_length; ++i)
key_bytes[i] = (byte)(key ^ m_decode_table[key_bytes[i]]);
uint[] secret_key = new uint[0x10];
Buffer.BlockCopy(key_bytes, 0, secret_key, 0, secret_length);
for (int i = 0; i < secret_key.Length; ++i)
secret_key[i] ^= seed;
unsafe
{
fixed (byte* raw = data)
{
uint* data32 = (uint*)raw;
key = m_scheme.EntryInitKey;
int k = m_scheme.EntryKeyPos;
for (int i = data.Length / 4; i > 0; --i)
{
uint backup = *data32;
*data32 = (((cmvs_md5[key & 3] ^ *data32) + seed) ^ (secret_key[k] >> 1)) ^ secret_key[(key >> 6) & 0xf];
k = (k + 1) & 0xf;
key += seed + backup;
++data32;
}
byte* data8 = (byte*)data32;
for (int i = data.Length & 3; i > 0; --i)
{
for (int s = 0; s < m_decode_table.Length; s++)
{
if (*data8 == m_decode_table[s])
{
*data8 = (byte)(s ^ m_scheme.EntryTailKey);
break;
}
}
++data8;
}
}
}
}
}
[Serializable]
public class ArchiveKey
{
public uint IndexDirKey;
public uint IndexEntryKey;
public uint EntryDataKey1;
public uint EntryDataKey2;
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type WorkbookTablesCollectionRequest.
/// </summary>
public partial class WorkbookTablesCollectionRequest : BaseRequest, IWorkbookTablesCollectionRequest
{
/// <summary>
/// Constructs a new WorkbookTablesCollectionRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public WorkbookTablesCollectionRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Adds the specified WorkbookTable to the collection via POST.
/// </summary>
/// <param name="workbookTable">The WorkbookTable to add.</param>
/// <returns>The created WorkbookTable.</returns>
public System.Threading.Tasks.Task<WorkbookTable> AddAsync(WorkbookTable workbookTable)
{
return this.AddAsync(workbookTable, CancellationToken.None);
}
/// <summary>
/// Adds the specified WorkbookTable to the collection via POST.
/// </summary>
/// <param name="workbookTable">The WorkbookTable to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created WorkbookTable.</returns>
public System.Threading.Tasks.Task<WorkbookTable> AddAsync(WorkbookTable workbookTable, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
return this.SendAsync<WorkbookTable>(workbookTable, cancellationToken);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <returns>The collection page.</returns>
public System.Threading.Tasks.Task<IWorkbookTablesCollectionPage> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The collection page.</returns>
public async System.Threading.Tasks.Task<IWorkbookTablesCollectionPage> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var response = await this.SendAsync<WorkbookTablesCollectionResponse>(null, cancellationToken).ConfigureAwait(false);
if (response != null && response.Value != null && response.Value.CurrentPage != null)
{
if (response.AdditionalData != null)
{
object nextPageLink;
response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
response.Value.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
// Copy the additional data collection to the page itself so that information is not lost
response.Value.AdditionalData = response.AdditionalData;
}
return response.Value;
}
return null;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookTablesCollectionRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookTablesCollectionRequest Expand(Expression<Func<WorkbookTable, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookTablesCollectionRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookTablesCollectionRequest Select(Expression<Func<WorkbookTable, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Adds the specified top value to the request.
/// </summary>
/// <param name="value">The top value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookTablesCollectionRequest Top(int value)
{
this.QueryOptions.Add(new QueryOption("$top", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified filter value to the request.
/// </summary>
/// <param name="value">The filter value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookTablesCollectionRequest Filter(string value)
{
this.QueryOptions.Add(new QueryOption("$filter", value));
return this;
}
/// <summary>
/// Adds the specified skip value to the request.
/// </summary>
/// <param name="value">The skip value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookTablesCollectionRequest Skip(int value)
{
this.QueryOptions.Add(new QueryOption("$skip", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified orderby value to the request.
/// </summary>
/// <param name="value">The orderby value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookTablesCollectionRequest OrderBy(string value)
{
this.QueryOptions.Add(new QueryOption("$orderby", value));
return this;
}
}
}
| |
using Microsoft.DirectX.Direct3D;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using TGC.Core.Direct3D;
using TGC.Core.Mathematica;
using TGC.Core.SceneLoader;
using TGC.Core.Terrain;
using TGC.Examples.Camara;
using TGC.Examples.Example;
using TGC.Examples.UserControls;
using TGC.Examples.UserControls.Modifier;
namespace TGC.Examples.WorkshopShaders
{
public class HDRLighting : TGCExampleViewer
{
private TGCBooleanModifier activarGlowModifier;
private TGCBooleanModifier pantallaCompletaModifier;
private TGCEnumModifier tmIzqModifier;
private TGCEnumModifier tmDerModifier;
private TGCIntervalModifier adaptacionPupilaModifier;
private List<TgcMesh> meshes;
private TgcSkyBox skyBox;
private TgcSimpleTerrain terrain;
private TgcMesh pasto, arbol, arbusto;
private Effect effect;
private Surface g_pDepthStencil; // Depth-stencil buffer
private Texture g_pRenderTarget, g_pGlowMap, g_pRenderTarget4, g_pRenderTarget4Aux;
private const int NUM_REDUCE_TX = 5;
private Texture[] g_pLuminance = new Texture[NUM_REDUCE_TX];
private Texture g_pLuminance_ant;
private VertexBuffer g_pVBV3D;
private int cant_pasadas = 5;
private float pupila_time = 0;
private float MAX_PUPILA_TIME = 3;
public enum ToneMapping : int
{
Nada = 0,
Reinhard = 1,
Modified_Reinhard = 2,
Logaritmico = 3,
MiddleGray = 4
};
public HDRLighting(string mediaDir, string shadersDir, TgcUserVars userVars, Panel modifiersPanel)
: base(mediaDir, shadersDir, userVars, modifiersPanel)
{
Category = "Shaders";
Name = "Workshop-HDRLighting";
Description = "HDR lighting";
}
public override void Init()
{
Device d3dDevice = D3DDevice.Instance.Device;
//Cargamos un escenario
TgcSceneLoader loader = new TgcSceneLoader();
TgcScene scene = loader.loadSceneFromFile(MediaDir + "MeshCreator\\Scenes\\Selva\\Selva-TgcScene.xml");
meshes = scene.Meshes;
TgcScene scene2 = loader.loadSceneFromFile(MediaDir + "MeshCreator\\Meshes\\Vegetacion\\Pasto\\Pasto-TgcScene.xml");
pasto = scene2.Meshes[0];
TgcScene scene3 = loader.loadSceneFromFile(MediaDir + "MeshCreator\\Meshes\\Vegetacion\\ArbolSelvatico\\ArbolSelvatico-TgcScene.xml");
arbol = scene3.Meshes[0];
arbol.Transform = TGCMatrix.Scaling(1, 3, 1);
TgcScene scene4 = loader.loadSceneFromFile(MediaDir + "MeshCreator\\Meshes\\Vegetacion\\Arbusto2\\Arbusto2-TgcScene.xml");
arbusto = scene4.Meshes[0];
//Cargar terreno: cargar heightmap y textura de color
terrain = new TgcSimpleTerrain();
terrain.loadHeightmap(MediaDir + "Heighmaps\\" + "TerrainTexture2.jpg", 20, 0.3f, new TGCVector3(0, -115, 0));
terrain.loadTexture(MediaDir + "Heighmaps\\" + "grass.jpg");
//Crear SkyBox
skyBox = new TgcSkyBox();
skyBox.Center = new TGCVector3(0, 500, 0);
skyBox.Size = new TGCVector3(10000, 10000, 10000);
string texturesPath = MediaDir + "Texturas\\Quake\\SkyBox2\\";
skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Up, texturesPath + "lun4_up.jpg");
skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Down, texturesPath + "lun4_dn.jpg");
skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Left, texturesPath + "lun4_lf.jpg");
skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Right, texturesPath + "lun4_rt.jpg");
skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Front, texturesPath + "lun4_bk.jpg");
skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Back, texturesPath + "lun4_ft.jpg");
skyBox.Init();
//Cargar Shader personalizado
string compilationErrors;
effect = Effect.FromFile(d3dDevice, ShadersDir + "WorkshopShaders\\GaussianBlur.fx", null, null, ShaderFlags.PreferFlowControl, null, out compilationErrors);
if (effect == null)
{
throw new Exception("Error al cargar shader. Errores: " + compilationErrors);
}
//Configurar Technique dentro del shader
effect.Technique = "DefaultTechnique";
//Camara en primera persona
TGCVector3 positionEye = new TGCVector3(-944.1269f, 100f, -1033.307f);
Camera = new TgcFpsCamera(positionEye, 300, 10, Input);
g_pDepthStencil = d3dDevice.CreateDepthStencilSurface(d3dDevice.PresentationParameters.BackBufferWidth, d3dDevice.PresentationParameters.BackBufferHeight, DepthFormat.D24S8, MultiSampleType.None, 0, true);
// inicializo el render target
g_pRenderTarget = new Texture(d3dDevice, d3dDevice.PresentationParameters.BackBufferWidth, d3dDevice.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget, Format.A16B16G16R16F, Pool.Default);
g_pGlowMap = new Texture(d3dDevice, d3dDevice.PresentationParameters.BackBufferWidth, d3dDevice.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget, Format.A16B16G16R16F, Pool.Default);
g_pRenderTarget4 = new Texture(d3dDevice, d3dDevice.PresentationParameters.BackBufferWidth / 4, d3dDevice.PresentationParameters.BackBufferHeight / 4, 1, Usage.RenderTarget, Format.A16B16G16R16F, Pool.Default);
g_pRenderTarget4Aux = new Texture(d3dDevice, d3dDevice.PresentationParameters.BackBufferWidth / 4, d3dDevice.PresentationParameters.BackBufferHeight / 4, 1, Usage.RenderTarget, Format.A16B16G16R16F, Pool.Default);
// Para computar el promedio de Luminance
int tx_size = 1;
for (int i = 0; i < NUM_REDUCE_TX; ++i)
{
g_pLuminance[i] = new Texture(d3dDevice, tx_size, tx_size, 1, Usage.RenderTarget, Format.A16B16G16R16F, Pool.Default);
tx_size *= 4;
}
g_pLuminance_ant = new Texture(d3dDevice, 1, 1, 1, Usage.RenderTarget, Format.A16B16G16R16F, Pool.Default);
effect.SetValue("g_RenderTarget", g_pRenderTarget);
// Resolucion de pantalla
effect.SetValue("screen_dx", d3dDevice.PresentationParameters.BackBufferWidth);
effect.SetValue("screen_dy", d3dDevice.PresentationParameters.BackBufferHeight);
CustomVertex.PositionTextured[] vertices = new CustomVertex.PositionTextured[]
{
new CustomVertex.PositionTextured( -1, 1, 1, 0,0),
new CustomVertex.PositionTextured(1, 1, 1, 1,0),
new CustomVertex.PositionTextured(-1, -1, 1, 0,1),
new CustomVertex.PositionTextured(1,-1, 1, 1,1)
};
//vertex buffer de los triangulos
g_pVBV3D = new VertexBuffer(typeof(CustomVertex.PositionTextured), 4, d3dDevice, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionTextured.Format, Pool.Default);
g_pVBV3D.SetData(vertices, 0, LockFlags.None);
activarGlowModifier = AddBoolean("activar_glow", "Activar Glow", true);
pantallaCompletaModifier = AddBoolean("pantalla_completa", "Pant.completa", true);
tmIzqModifier = AddEnum("tm_izq", typeof(ToneMapping), ToneMapping.MiddleGray);
tmDerModifier = AddEnum("tm_der", typeof(ToneMapping), ToneMapping.Nada);
adaptacionPupilaModifier = AddInterval("adaptacion_pupila", new object[] { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f }, 2);
}
public override void Update()
{
Camera.UpdateCamera(ElapsedTime);
}
public override void Render()
{
renderConEfectos(ElapsedTime);
}
public void renderSinEfectos(float elapsedTime)
{
Device d3dDevice = D3DDevice.Instance.Device;
// dibujo la escena una textura
effect.Technique = "DefaultTechnique";
d3dDevice.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
d3dDevice.BeginScene();
//Dibujamos todos los meshes del escenario
renderScene("DefaultTechnique");
//Render skybox
skyBox.Render();
d3dDevice.EndScene();
}
public void renderConEfectos(float elapsedTime)
{
Device d3dDevice = D3DDevice.Instance.Device;
// Resolucion de pantalla
float screen_dx = d3dDevice.PresentationParameters.BackBufferWidth;
float screen_dy = d3dDevice.PresentationParameters.BackBufferHeight;
effect.SetValue("screen_dx", screen_dx);
effect.SetValue("screen_dy", screen_dy);
// dibujo la escena una textura
effect.Technique = "DefaultTechnique";
// guardo el Render target anterior y seteo la textura como render target
Surface pOldRT = d3dDevice.GetRenderTarget(0);
Surface pSurf = g_pRenderTarget.GetSurfaceLevel(0);
d3dDevice.SetRenderTarget(0, pSurf);
// hago lo mismo con el depthbuffer, necesito el que no tiene multisampling
Surface pOldDS = d3dDevice.DepthStencilSurface;
d3dDevice.DepthStencilSurface = g_pDepthStencil;
d3dDevice.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
effect.SetValue("KLum", 0.05f);
d3dDevice.BeginScene();
//Dibujamos todos los meshes del escenario
renderScene("DefaultTechnique");
// y el skybox (el skybox no tiene efectos, va por fixed OJOOO)
skyBox.Render();
d3dDevice.EndScene();
pSurf.Dispose();
MAX_PUPILA_TIME = (float)adaptacionPupilaModifier.Value;
bool glow = activarGlowModifier.Value;
effect.SetValue("glow", glow);
if (glow)
{
// dibujo el glow map
effect.SetValue("KLum", 1.0f);
effect.Technique = "DefaultTechnique";
pSurf = g_pGlowMap.GetSurfaceLevel(0);
d3dDevice.SetRenderTarget(0, pSurf);
d3dDevice.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
d3dDevice.BeginScene();
// dibujo el skybox que es brillante, con la tecnica estandard
skyBox.Render();
// El resto opacos
renderScene("DibujarObjetosOscuros");
d3dDevice.EndScene();
pSurf.Dispose();
// Hago un blur sobre el glow map
// 1er pasada: downfilter x 4
// -----------------------------------------------------
pSurf = g_pRenderTarget4.GetSurfaceLevel(0);
d3dDevice.SetRenderTarget(0, pSurf);
d3dDevice.BeginScene();
effect.Technique = "DownFilter4";
d3dDevice.VertexFormat = CustomVertex.PositionTextured.Format;
d3dDevice.SetStreamSource(0, g_pVBV3D, 0);
effect.SetValue("g_RenderTarget", g_pGlowMap);
d3dDevice.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
effect.Begin(FX.None);
effect.BeginPass(0);
d3dDevice.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2);
effect.EndPass();
effect.End();
pSurf.Dispose();
d3dDevice.EndScene();
d3dDevice.DepthStencilSurface = pOldDS;
// Pasadas de blur
for (int P = 0; P < cant_pasadas; ++P)
{
// Gaussian blur Horizontal
// -----------------------------------------------------
pSurf = g_pRenderTarget4Aux.GetSurfaceLevel(0);
d3dDevice.SetRenderTarget(0, pSurf);
// dibujo el quad pp dicho :
d3dDevice.BeginScene();
effect.Technique = "GaussianBlurSeparable";
d3dDevice.VertexFormat = CustomVertex.PositionTextured.Format;
d3dDevice.SetStreamSource(0, g_pVBV3D, 0);
effect.SetValue("g_RenderTarget", g_pRenderTarget4);
d3dDevice.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
effect.Begin(FX.None);
effect.BeginPass(0);
d3dDevice.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2);
effect.EndPass();
effect.End();
pSurf.Dispose();
d3dDevice.EndScene();
pSurf = g_pRenderTarget4.GetSurfaceLevel(0);
d3dDevice.SetRenderTarget(0, pSurf);
pSurf.Dispose();
// Gaussian blur Vertical
// -----------------------------------------------------
d3dDevice.BeginScene();
effect.Technique = "GaussianBlurSeparable";
d3dDevice.VertexFormat = CustomVertex.PositionTextured.Format;
d3dDevice.SetStreamSource(0, g_pVBV3D, 0);
effect.SetValue("g_RenderTarget", g_pRenderTarget4Aux);
d3dDevice.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
effect.Begin(FX.None);
effect.BeginPass(1);
d3dDevice.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2);
effect.EndPass();
effect.End();
d3dDevice.EndScene();
}
//TextureLoader.Save("glowmap", ImageFileFormat.Bmp, g_pRenderTarget4Aux);
}
// computo el promedio
pSurf = g_pLuminance[NUM_REDUCE_TX - 1].GetSurfaceLevel(0);
screen_dx = pSurf.Description.Width;
screen_dy = pSurf.Description.Height;
d3dDevice.SetRenderTarget(0, pSurf);
d3dDevice.BeginScene();
effect.Technique = "DownFilter4";
d3dDevice.VertexFormat = CustomVertex.PositionTextured.Format;
d3dDevice.SetStreamSource(0, g_pVBV3D, 0);
effect.SetValue("g_RenderTarget", g_pRenderTarget);
d3dDevice.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
effect.Begin(FX.None);
effect.BeginPass(0);
d3dDevice.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2);
effect.EndPass();
effect.End();
pSurf.Dispose();
d3dDevice.EndScene();
d3dDevice.DepthStencilSurface = pOldDS;
string fname2 = string.Format("Pass{0:D}.bmp", NUM_REDUCE_TX);
//SurfaceLoader.Save(fname2, ImageFileFormat.Bmp, pSurf);
// Reduce
for (int i = NUM_REDUCE_TX - 1; i > 0; i--)
{
pSurf = g_pLuminance[i - 1].GetSurfaceLevel(0);
effect.SetValue("screen_dx", screen_dx);
effect.SetValue("screen_dy", screen_dy);
d3dDevice.SetRenderTarget(0, pSurf);
effect.SetValue("g_RenderTarget", g_pLuminance[i]);
d3dDevice.BeginScene();
d3dDevice.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
effect.Begin(FX.None);
effect.BeginPass(0);
d3dDevice.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2);
effect.EndPass();
effect.End();
pSurf.Dispose();
d3dDevice.EndScene();
string fname = string.Format("Pass{0:D}.bmp", i);
//SurfaceLoader.Save(fname, ImageFileFormat.Bmp, pSurf);
screen_dx /= 4.0f;
screen_dy /= 4.0f;
}
// Tone mapping
// -----------------------------------------------------
effect.SetValue("tone_mapping_izq", (int)tmIzqModifier.Value);
effect.SetValue("tone_mapping_der", (int)tmDerModifier.Value);
effect.SetValue("pantalla_completa", pantallaCompletaModifier.Value);
effect.SetValue("screen_dx", d3dDevice.PresentationParameters.BackBufferWidth);
effect.SetValue("screen_dy", d3dDevice.PresentationParameters.BackBufferHeight);
d3dDevice.SetRenderTarget(0, pOldRT);
d3dDevice.BeginScene();
effect.Technique = "ToneMapping";
d3dDevice.VertexFormat = CustomVertex.PositionTextured.Format;
d3dDevice.SetStreamSource(0, g_pVBV3D, 0);
effect.SetValue("g_RenderTarget", g_pRenderTarget);
effect.SetValue("g_GlowMap", g_pRenderTarget4Aux);
pupila_time += elapsedTime;
if (pupila_time >= MAX_PUPILA_TIME)
{
pupila_time = 0;
effect.SetValue("g_Luminance_ant", g_pLuminance[0]);
Texture aux = g_pLuminance[0];
g_pLuminance[0] = g_pLuminance_ant;
g_pLuminance_ant = aux;
}
else
{
effect.SetValue("g_Luminance", g_pLuminance[0]);
}
effect.SetValue("pupila_time", pupila_time / MAX_PUPILA_TIME); // 0..1
d3dDevice.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
effect.Begin(FX.None);
effect.BeginPass(0);
d3dDevice.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2);
effect.EndPass();
effect.End();
PostRender();
}
public void renderScene(string Technique)
{
//Dibujamos todos los meshes del escenario
Random rnd = new Random(1);
pasto.Effect = effect;
pasto.Technique = Technique;
for (int i = 0; i < 10; ++i)
for (int j = 0; j < 10; ++j)
{
pasto.Transform = TGCMatrix.Scaling(3, 4 + rnd.Next(0, 4), 5) * TGCMatrix.Translation(-i * 200 + rnd.Next(0, 50), 0, -j * 200 + rnd.Next(0, 50));
pasto.Render();
}
arbusto.Effect = effect;
arbusto.Technique = Technique;
for (int i = 0; i < 5; ++i)
for (int j = 0; j < 5; ++j)
{
arbusto.Transform = TGCMatrix.Translation(-i * 400 + rnd.Next(0, 50), 0, -j * 400 + rnd.Next(0, 50));
arbusto.Render();
}
arbol.Effect = effect;
arbol.Technique = Technique;
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
{
arbol.Transform = TGCMatrix.Translation(-i * 700 + rnd.Next(0, 50), 0, -j * 700 + rnd.Next(0, 50));
arbol.Render();
}
// -------------------------------------
//Renderizar terreno
terrain.Effect = effect;
terrain.Technique = Technique;
terrain.Render();
}
public override void Dispose()
{
foreach (TgcMesh m in meshes)
{
m.Dispose();
}
effect.Dispose();
skyBox.Dispose();
terrain.Dispose();
pasto.Dispose();
arbol.Dispose();
arbusto.Dispose();
g_pRenderTarget.Dispose();
g_pGlowMap.Dispose();
g_pRenderTarget4Aux.Dispose();
g_pRenderTarget4.Dispose();
g_pVBV3D.Dispose();
g_pDepthStencil.Dispose();
for (int i = 0; i < NUM_REDUCE_TX; i++)
{
g_pLuminance[i].Dispose();
}
g_pLuminance_ant.Dispose();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using bv.common.Configuration;
using bv.common.Core;
using bv.model.Model.Core;
using bv.winclient.Core;
using DevExpress.Utils;
using DevExpress.XtraGrid;
using DevExpress.XtraTreeList;
using DevExpress.XtraTreeList.Nodes;
using DevExpress.XtraTreeList.ViewInfo;
using eidss.avr.BaseComponents;
using eidss.avr.BaseComponents.Views;
using eidss.avr.db.AvrEventArgs.AvrEventArgs;
using eidss.model.Avr;
using eidss.model.Avr.Tree;
using eidss.model.Core;
using eidss.model.Reports.OperationContext;
using eidss.model.Resources;
namespace eidss.avr.QueryLayoutTree
{
public sealed partial class QueryLayoutTreePanel : BaseAvrDetailPresenterPanel, IQueryLayoutTreeView
{
private const int ImageIndexFolderCollapsed = 0;
private const int ImageIndexFolderExpanded = 1;
private const int ImageIndexQueryCollapsed = 2;
private const int ImageIndexQueryExpanded = 3;
private const int ImageIndexLayout = 4;
private readonly string m_MessageFolderExists;
private readonly string m_DefaultFolderName;
private readonly string m_NationalFolderName;
public event EventHandler<AvrTreeSelectedElementEventArgs> OnElementSelect;
public event EventHandler<AvrTreeSelectedElementEventArgs> OnElementEdit;
public event EventHandler<AvrTreeSelectedElementEventArgs> OnElementPopup;
private string m_OldDefaultName;
private string m_OldNationalName;
private List<AvrTreeElement> m_DataSource;
private bool m_ReadOnly;
public QueryLayoutTreePanel()
{
InitializeComponent();
if (WinUtils.IsComponentInDesignMode(this))
{
return;
}
TreePresenter = (QueryLayoutTreePresenter) BaseAvrPresenter;
AvrQueryLayoutTreeDbHelper.InitWarnings();
columnAuthor.Visible = AvrPermissions.AccessToAVRAdministrationPermission;
m_DefaultFolderName = EidssMessages.Get("msgDefaultFolderName", "New folder", Localizer.lngEn);
m_NationalFolderName = EidssMessages.Get("msgDefaultFolderName", "New folder");
m_MessageFolderExists = EidssMessages.Get("msgFolderExists",
"Cannot rename {0}: A folder with the name you specified already exists. Specify a different folder name.");
}
/// <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)
{
try
{
if (toolTipController != null)
{
toolTipController.GetActiveObjectInfo -= toolTipController_GetActiveObjectInfo;
toolTipController.Dispose();
toolTipController = null;
}
if (TreePresenter != null)
{
if (TreePresenter.SharedPresenter != null)
{
TreePresenter.SharedPresenter.UnregisterView(this);
}
TreePresenter.Dispose();
TreePresenter = null;
}
if (disposing && (components != null))
{
components.Dispose();
}
}
finally
{
base.Dispose(disposing);
}
}
protected override void DefineBinding()
{
if (!BaseSettings.ScanFormsMode)
{
using (SharedPresenter.ContextKeeper.CreateNewContext(ContextValue.DefineBinding))
{
EidssUserContext.CheckUserLoggedIn();
DataSource = TreePresenter.LoadData();
}
}
}
#region Properties
[DefaultValue(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public new bool ReadOnly
{
get { return m_ReadOnly; }
set
{
m_ReadOnly = value;
tree.AllowDrop = !value;
}
}
private QueryLayoutTreePresenter TreePresenter { get; set; }
private List<AvrTreeElement> DataSource
{
get { return m_DataSource; }
set
{
m_DataSource = value ?? new List<AvrTreeElement>();
tree.Nodes.Clear();
tree.DataSource = m_DataSource;
tree.ExpandAll();
}
}
/// <summary>
/// this field need for workaround because of DevExpress issue
/// http://www.devexpress.com/Support/Center/Question/Details/B136845
/// </summary>
//public bool WorkaroundIsFocusedNode { get; set; }
public bool IsFocusedNodeReadOnly
{
get { return tree.FocusedNode != null && tree.FocusedNode.IsReadOnlyNode(); }
}
#endregion
#region Query Layout update operations
public void ReloadQueryLayoutFolder(long id, AvrTreeElementType type)
{
AvrTreeElement element = null;
switch (type)
{
case AvrTreeElementType.Query:
element = AvrQueryLayoutTreeDbHelper.ReloadQuery(id);
break;
case AvrTreeElementType.Layout:
element = AvrQueryLayoutTreeDbHelper.ReloadLayout(id);
break;
case AvrTreeElementType.Folder:
element = AvrQueryLayoutTreeDbHelper.ReloadFolder(id);
break;
}
if (element != null)
{
UpdateNode(element);
Refresh();
}
}
private void UpdateNode(AvrTreeElement newElement)
{
if (DataSource != null)
{
AvrTreeElement currentElement = DataSource.SingleOrDefault(n => n.ID == newElement.ID);
if (currentElement != null)
{
currentElement.DefaultName = newElement.DefaultName;
currentElement.NationalName = newElement.NationalName;
currentElement.Description = newElement.Description;
if (newElement.ReadOnly)
{
SetAllParentsReadonly(currentElement);
}
else
{
ClearAllChildrenReadonly(currentElement);
}
}
else
{
DataSource.Add(newElement);
}
tree.RefreshDataSource();
tree.BeginSort();
tree.Columns[0].SortIndex = 0;
tree.Columns[0].SortMode = ColumnSortMode.DisplayText;
tree.Columns[0].SortOrder = SortOrder.Ascending;
tree.EndSort();
}
}
private void SetAllParentsReadonly(AvrTreeElement element)
{
while (element != null)
{
element.ReadOnly = true;
element = DataSource.SingleOrDefault(c => c.ID == element.ParentID);
}
}
private void ClearAllChildrenReadonly(AvrTreeElement element)
{
element.ReadOnly = false;
List<AvrTreeElement> elements = DataSource.Where(c => c.ParentID == element.ID).ToList();
foreach (AvrTreeElement child in elements)
{
ClearAllChildrenReadonly(child);
}
}
#endregion
#region Folder operations
public void EditFolder(AvrTreeSelectedElementEventArgs e, bool isNewObject = false)
{
if (TreePresenter == null)
{
throw new AvrException(@"QuaryLayoutTreePresenter is not initialized for LayoutTreeListKeeper");
}
if (!e.ElementId.HasValue)
{
return;
}
TreeListNode node = GetNode(e.ElementId.Value, tree.Nodes);
if (node == null || ReadOnly || !AvrPermissions.InsertPermission || IsFolderDepthTooBig())
{
return;
}
string englishName = isNewObject
? GetFolderNameWithPrefix(false)
: node.GetNodeDefaultName();
string nationalName = isNewObject
? GetFolderNameWithPrefix(true)
: node.GetNodeNationalName();
using (var form = new RenameFolderDialog(englishName, nationalName, e, !isNewObject && node.IsReadOnlyNode(), isNewObject))
{
if (form.ShowDialog(ParentForm) == DialogResult.OK)
{
englishName = form.EnglishName;
nationalName = form.NationalName;
if (isNewObject)
{
TreeListNode queryNode = node.IsQueryNode() ? node : node.RootNode;
long queryId = queryNode.GetNodeId();
TreeListNode parentNode = node.IsLayoutNode() ? node.ParentNode : node;
long parentId = parentNode.GetNodeId();
long? folderId = parentNode.IsFolderNode() ? parentId : (long?) null;
long nodeId = TreePresenter.NewId();
var newElement = new AvrTreeElement(nodeId, parentId, null, AvrTreeElementType.Folder, queryId,
englishName, nationalName, string.Empty, false);
DataSource.Add(newElement);
tree.RefreshDataSource();
TreeListNode folder = GetNode(nodeId, tree.Nodes);
tree.FocusedNode = folder;
TreePresenter.SaveFolder(nodeId, folderId, queryId, newElement.DefaultName, newElement.NationalName);
}
else
{
long queryId = node.RootNode.GetNodeId();
long parentId = node.ParentNode.GetNodeId();
long? folderId = node.ParentNode.IsFolderNode() ? parentId : (long?) null;
long nodeId = node.GetNodeId();
TreePresenter.SaveFolder(nodeId, folderId, queryId, englishName, nationalName);
ReloadQueryLayoutFolder(nodeId, AvrTreeElementType.Folder);
}
}
}
}
#endregion
#region click handlers
private void tree_EditorKeyDown(object sender, KeyEventArgs e)
{
m_OldDefaultName = tree.FocusedNode.GetNodeDefaultName();
m_OldNationalName = tree.FocusedNode.GetNodeNationalName();
}
private void tree_CellValueChanged(object sender, CellValueChangedEventArgs e)
{
TreeListNode node = e.Node;
if (!node.IsFolderNode())
{
throw new AvrException("Could not change Node that is not a folder");
}
foreach (AvrTreeElement element in DataSource)
{
if ((e.Column == columnName) &&
(element.DefaultName.ToLowerInvariant() == Utils.Str(e.Value).ToLowerInvariant()) &&
(node.GetNodeId() != element.ID))
{
MessageForm.Show(string.Format(m_MessageFolderExists, Utils.Str(e.Value)));
node.SetValue(TreeListNodeExtender.DefaultColumnName, m_OldDefaultName);
return;
}
if ((e.Column == columnNationalName) &&
(element.NationalName.ToLowerInvariant() == Utils.Str(e.Value).ToLowerInvariant()) &&
(node.GetNodeId() != element.ID))
{
MessageForm.Show(string.Format(m_MessageFolderExists, Utils.Str(e.Value)));
node.SetValue(TreeListNodeExtender.NationalColumnName, m_OldNationalName);
return;
}
}
long? parentFolderId = node.ParentNode.IsFolderNode()
? node.ParentNode.GetNodeId()
: (long?) null;
string defaultName = Utils.Str(node.GetValue(TreeListNodeExtender.DefaultColumnName));
string nationalName = (ModelUserContext.CurrentLanguage == Localizer.lngEn)
? defaultName
: Utils.Str(node.GetValue(TreeListNodeExtender.NationalColumnName));
TreePresenter.SaveFolder(node.GetNodeId(), parentFolderId, node.RootNode.GetNodeId(),
defaultName, nationalName);
}
private void tree_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter && !tree.FocusedNode.IsFolderNode())
{
OnElementEdit.SafeRaise(this, tree.FocusedNode.GetTreeElementEventArgs());
}
}
private void tree_DoubleClick(object sender, EventArgs e)
{
if ((e is MouseEventArgs) && ((MouseEventArgs) e).Button == MouseButtons.Left)
{
OnElementEdit.SafeRaise(this, tree.FocusedNode.GetTreeElementEventArgs());
FocusedNodeReload();
}
}
private void tree_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right && ModifierKeys == Keys.None && tree.State == TreeListState.Regular)
{
Point pt = tree.PointToClient(MousePosition);
TreeListHitInfo info = tree.CalcHitInfo(pt);
if (info != null && info.HitInfoType == HitInfoType.Cell)
{
tree.FocusedNode = info.Node;
OnElementPopup.SafeRaise(this, info.Node.GetTreeElementEventArgs());
}
}
}
#endregion
#region Appearence
public void DeleteFocusedNode()
{
tree.DeleteNode(tree.FocusedNode);
tree.RefreshDataSource();
}
public void DeleteNodeWithId(long id)
{
TreeListNode node = GetNode(id, tree.Nodes);
if (node != null)
{
tree.DeleteNode(node);
tree.RefreshDataSource();
}
}
public AvrTreeSelectedElementEventArgs GetTreeSelectedElementEventArgs()
{
return tree.FocusedNode.GetTreeElementEventArgs();
}
public TreeListNode GetNodeByElementId(long elementId)
{
TreeListNode node = GetNode(elementId, tree.Nodes);
return node;
}
public void SetTreeFocusedNodeByElementId(long elementId)
{
TreeListNode node = GetNode(elementId, tree.Nodes);
tree.FocusedNode = node;
}
public void FocusedNodeReload()
{
tree_FocusedNodeChanged(this, new FocusedNodeChangedEventArgs(tree.FocusedNode, tree.FocusedNode));
}
private void tree_FocusedNodeChanged(object sender, FocusedNodeChangedEventArgs e)
{
OnElementSelect.SafeRaise(this, e.Node.GetTreeElementEventArgs());
}
private void tree_GetStateImage(object sender, GetStateImageEventArgs e)
{
if (e.Node.IsLayoutNode())
{
e.NodeImageIndex = ImageIndexLayout;
}
else if (e.Node.IsQueryNode())
{
e.NodeImageIndex = e.Node.Expanded ? ImageIndexQueryExpanded : ImageIndexQueryCollapsed;
}
else
{
e.NodeImageIndex = e.Node.Expanded ? ImageIndexFolderExpanded : ImageIndexFolderCollapsed;
}
}
private void tree_CustomDrawNodeCell(object sender, CustomDrawNodeCellEventArgs e)
{
bool readOnly = e.Node.IsReadOnlyNode();
if (readOnly && e.Appearance.Font.Style != FontStyle.Bold)
{
e.Appearance.Font = new Font(e.Appearance.Font, FontStyle.Bold);
}
if (!readOnly && e.Appearance.Font.Style != FontStyle.Regular)
{
e.Appearance.Font = new Font(e.Appearance.Font, FontStyle.Regular);
}
}
private void toolTipController_GetActiveObjectInfo(object sender, ToolTipControllerGetActiveObjectInfoEventArgs e)
{
if (e.SelectedControl is TreeList)
{
// TreeList tree = (TreeList)e.SelectedControl;
TreeListHitInfo hit = tree.CalcHitInfo(e.ControlMousePosition);
if (hit != null && hit.Node != null)
{
AvrTreeElement element = DataSource.SingleOrDefault(n => n.ID == hit.Node.GetNodeId());
if (element != null)
{
object cellInfo = new TreeListCellToolTipInfo(hit.Node, hit.Column, null);
string toolTip = element.Description;
e.Info = new ToolTipControlInfo(cellInfo, toolTip);
}
}
}
}
#endregion
#region Drag Methods
private void tree_DragOver(object sender, DragEventArgs e)
{
DragHandler(e);
}
private void tree_DragDrop(object sender, DragEventArgs e)
{
DragHandler(e);
if (e.Effect == DragDropEffects.None)
{
return;
}
TreeListNode sourceNode = GetSourceNode(e);
AvrTreeElement childElement = DataSource.Find(element => element.ID == sourceNode.GetNodeId());
TreeListNode parentNode = GetDestNode(e);
if (IsFolderDepthTooBig(parentNode, GetNode(childElement.ID, tree.Nodes)))
{
return;
}
long? parentId = (parentNode == null) ? null : (long?) parentNode.GetNodeId();
childElement.ParentID = parentId;
tree.RefreshDataSource();
if (parentNode != null)
{
parentNode.ExpandAll();
}
e.Effect = DragDropEffects.None;
long? folderId = parentNode.IsFolderNode() ? parentId : null;
if (sourceNode.IsLayoutNode())
{
TreePresenter.SaveLayoutLocation(childElement.ID, folderId);
}
else if (sourceNode.IsFolderNode())
{
TreePresenter.SaveFolder(childElement.ID, folderId, sourceNode.RootNode.GetNodeId(),
childElement.DefaultName, childElement.NationalName);
}
}
private void DragHandler(DragEventArgs e)
{
e.Effect = DragDropEffects.Move;
TreeListNode sourceNode = GetSourceNode(e);
TreeListNode destNode = GetDestNode(e);
if (ReadOnly ||
sourceNode.IsReadOnlyNode() ||
sourceNode.IsQueryNode() ||
sourceNode == destNode ||
destNode == null ||
destNode.IsLayoutNode() ||
sourceNode.RootNode != destNode.RootNode ||
ContainsNodeInParentTree(destNode, sourceNode))
{
e.Effect = DragDropEffects.None;
}
}
#endregion
#region Helper methods
private string GetFolderNameWithPrefix(bool isNational)
{
string initialFolderName = isNational ? m_NationalFolderName : m_DefaultFolderName;
string folderName = initialFolderName;
for (int index = 2; index < int.MaxValue; index++)
{
bool isDublicate = DataSource.Any(
element =>
(element.ElementType == AvrTreeElementType.Folder) &&
((element.NationalName == folderName) && isNational) ||
(element.DefaultName == folderName && !isNational));
if (!isDublicate)
{
break;
}
folderName = string.Format("{0} ({1})", Utils.Str(initialFolderName), index);
}
return folderName;
}
private static TreeListNode GetSourceNode(DragEventArgs e)
{
return GetDragNode(e.Data);
}
private TreeListNode GetDestNode(DragEventArgs e)
{
TreeListHitInfo hi = tree.CalcHitInfo(tree.PointToClient(new Point(e.X, e.Y)));
return hi.Node;
}
private static TreeListNode GetDragNode(IDataObject data)
{
Utils.CheckNotNull(data, "data");
return data.GetData(typeof (TreeListNode)) as TreeListNode;
}
private TreeListNode GetNode(long id, IEnumerable<TreeListNode> nodes)
{
foreach (TreeListNode node in nodes)
{
if (node.GetNodeId() == id)
{
return node;
}
TreeListNode foundNode = GetNode(id, node.Nodes);
if (foundNode != null)
{
return foundNode;
}
}
return null;
}
private bool IsFolderDepthTooBig()
{
int count = tree.FocusedNode.GetParentDepth();
if (tree.FocusedNode.IsLayoutNode())
{
count--;
}
return ShowMessageIfFolderDepthTooBig(count);
}
private bool IsFolderDepthTooBig(TreeListNode parentNode, TreeListNode childNode)
{
int count = parentNode.GetParentDepth() + childNode.GetChildDepth();
return ShowMessageIfFolderDepthTooBig(count);
}
private static bool ShowMessageIfFolderDepthTooBig(int count)
{
int maxDepth = Math.Min(Config.GetIntSetting("MaxRamFolderDepth", 16), 30);
bool isFolderDepthTooBig = count >= maxDepth;
if (isFolderDepthTooBig)
{
MessageForm.Show(string.Format(EidssMessages.Get("msgTooBigFolderDepth"), count, maxDepth));
}
return isFolderDepthTooBig;
}
private bool ContainsNodeInParentTree(TreeListNode destNode, TreeListNode searchingNode)
{
TreeListNode parentNode = destNode;
while (parentNode != null)
{
if (parentNode == searchingNode)
{
return true;
}
parentNode = parentNode.ParentNode;
}
return false;
}
#endregion
}
}
| |
//
// CFRunLoop.cs: Main Loop
//
// Authors:
// Miguel de Icaza ([email protected])
//
// 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.Runtime.InteropServices;
using MonoMac.ObjCRuntime;
using MonoMac.Foundation;
namespace MonoMac.CoreFoundation {
public enum CFRunLoopExitReason {
Finished = 1,
Stopped = 2,
TimedOut = 3,
HandledSource = 4
}
#if false // this will eventually need to be exposed for CFNetwork.ExecuteAutoConfiguration*()
public class CFRunLoopSource : INativeObject, IDisposable {
internal IntPtr handle;
internal CFRunLoopSource (IntPtr handle)
{
CFObject.CFRetain (handle);
this.handle = handle;
}
~CFRunLoopSource ()
{
Dispose (false);
}
// TODO: Bind struct CFRunLoopSourceContext and its callbacks
//[DllImport (Constants.CoreFoundationLibrary)]
//extern static IntPtr CFRunLoopSourceCreate (IntPtr allocator, int order, IntPtr context);
//public static CFRunLoopSource Create (int order, CFRunLoopSourceContext context)
//{
// IntPtr source = CFRunLoopSourceCreate (IntPtr.Zero, order, context);
//
// if (source != IntPtr.Zero)
// return new CFRunLoopSource (source);
//
// return null;
//}
public IntPtr Handle {
get {
return handle;
}
}
[DllImport (Constants.CoreFoundationLibrary)]
// FIXME: CFRunLoopSourceGetOrder() returns CFIndex which is a typedef for 'signed long'
extern static int CFRunLoopSourceGetOrder (IntPtr source);
public int Order {
get {
return CFRunLoopSourceGetOrder (handle);
}
}
[DllImport (Constants.CoreFoundationLibrary)]
extern static void CFRunLoopSourceInvalidate (IntPtr source);
public void Invalidate ()
{
CFRunLoopSourceInvalidate (handle);
}
[DllImport (Constants.CoreFoundationLibrary)]
extern static int CFRunLoopSourceIsValid (IntPtr source);
public bool IsValid {
get {
return CFRunLoopSourceIsValid (handle) != 0;
}
}
[DllImport (Constants.CoreFoundationLibrary)]
extern static void CFRunLoopSourceSignal (IntPtr source);
public void Signal ()
{
CFRunLoopSourceSignal (handle);
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
public virtual void Dispose (bool disposing)
{
if (handle != IntPtr.Zero) {
CFObject.CFRelease (handle);
handle = IntPtr.Zero;
}
}
}
#endif
public class CFRunLoop : INativeObject, IDisposable {
static IntPtr CoreFoundationLibraryHandle = Dlfcn.dlopen (Constants.CoreFoundationLibrary, 0);
internal IntPtr handle;
static NSString _CFDefaultRunLoopMode;
public static NSString CFDefaultRunLoopMode {
get {
if (_CFDefaultRunLoopMode == null)
_CFDefaultRunLoopMode = Dlfcn.GetStringConstant (CoreFoundationLibraryHandle, "kCFDefaultRunLoopMode");
return _CFDefaultRunLoopMode;
}
}
static NSString _CFRunLoopCommonModes;
public static NSString CFRunLoopCommonModes {
get {
if (_CFRunLoopCommonModes == null)
_CFRunLoopCommonModes = Dlfcn.GetStringConstant (CoreFoundationLibraryHandle, "kCFRunLoopCommonModes");
return _CFRunLoopCommonModes;
}
}
// Note: This is a broken binding... we do not know what the values of the constant strings are, just their variable names and things are done by comparing CFString pointers, not a string compare anyway.
public const string ModeDefault = "kCFRunLoopDefaultMode";
public const string ModeCommon = "kCFRunLoopCommonModes";
[DllImport (Constants.CoreFoundationLibrary)]
extern static IntPtr CFRunLoopGetCurrent ();
static public CFRunLoop Current {
get {
return new CFRunLoop (CFRunLoopGetCurrent ());
}
}
[DllImport (Constants.CoreFoundationLibrary)]
extern static IntPtr CFRunLoopGetMain ();
static public CFRunLoop Main {
get {
return new CFRunLoop (CFRunLoopGetMain ());
}
}
[DllImport (Constants.CoreFoundationLibrary)]
extern static void CFRunLoopRun ();
public void Run ()
{
CFRunLoopRun ();
}
[DllImport (Constants.CoreFoundationLibrary)]
extern static void CFRunLoopStop (IntPtr loop);
public void Stop ()
{
CFRunLoopStop (handle);
}
[DllImport (Constants.CoreFoundationLibrary)]
extern static void CFRunLoopWakeUp (IntPtr loop);
public void WakeUp ()
{
CFRunLoopWakeUp (handle);
}
[DllImport (Constants.CoreFoundationLibrary)]
extern static int CFRunLoopIsWaiting (IntPtr loop);
public bool IsWaiting {
get {
return CFRunLoopIsWaiting (handle) != 0;
}
}
[DllImport (Constants.CoreFoundationLibrary)]
extern static int CFRunLoopRunInMode (IntPtr mode, double seconds, int returnAfterSourceHandled);
public CFRunLoopExitReason RunInMode (NSString mode, double seconds, bool returnAfterSourceHandled)
{
if (mode == null)
throw new ArgumentNullException ("mode");
return (CFRunLoopExitReason) CFRunLoopRunInMode (mode.Handle, seconds, returnAfterSourceHandled ? 1 : 0);
}
[Obsolete ("Use the NSString version of CFRunLoop.RunInMode() instead.")]
public CFRunLoopExitReason RunInMode (string mode, double seconds, bool returnAfterSourceHandled)
{
if (mode == null)
throw new ArgumentNullException ("mode");
CFString s = new CFString (mode);
var v = CFRunLoopRunInMode (s.Handle, seconds, returnAfterSourceHandled ? 1 : 0);
s.Dispose ();
return (CFRunLoopExitReason) v;
}
#if false // will eventually be needed by CFNetwork.ExecuteAutoConfiguration*()
[DllImport (Constants.CoreFoundationLibrary)]
extern static void CFRunLoopAddSource (IntPtr loop, IntPtr source, IntPtr mode);
public void AddSource (CFRunLoopSource source, NSString mode)
{
if (mode == null)
throw new ArgumentNullException ("mode");
CFRunLoopAddSource (handle, source.Handle, mode.Handle);
}
[DllImport (Constants.CoreFoundationLibrary)]
extern static bool CFRunLoopContainsSource (IntPtr loop, IntPtr source, IntPtr mode);
public bool ContainsSource (CFRunLoopSource source, NSString mode)
{
if (mode == null)
throw new ArgumentNullException ("mode");
return CFRunLoopContainsSource (handle, source.Handle, mode.Handle);
}
[DllImport (Constants.CoreFoundationLibrary)]
extern static bool CFRunLoopRemoveSource (IntPtr loop, IntPtr source, IntPtr mode);
public bool RemoveSource (CFRunLoopSource source, NSString mode)
{
if (mode == null)
throw new ArgumentNullException ("mode");
return CFRunLoopRemoveSource (handle, source.Handle, mode.Handle);
}
#endif
internal CFRunLoop (IntPtr handle)
{
CFObject.CFRetain (handle);
this.handle = handle;
}
~CFRunLoop ()
{
Dispose (false);
}
public IntPtr Handle {
get {
return handle;
}
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
public virtual void Dispose (bool disposing)
{
if (handle != IntPtr.Zero){
CFObject.CFRelease (handle);
handle = IntPtr.Zero;
}
}
public static bool operator == (CFRunLoop a, CFRunLoop b)
{
return Object.Equals (a, b);
}
public static bool operator != (CFRunLoop a, CFRunLoop b)
{
return !Object.Equals (a, b);
}
public override int GetHashCode ()
{
return handle.GetHashCode ();
}
public override bool Equals (object other)
{
CFRunLoop cfother = other as CFRunLoop;
if (cfother == null)
return false;
return cfother.Handle == Handle;
}
}
}
| |
// This file has been generated by the GUI designer. Do not modify.
public partial class MainWindow
{
private global::Gtk.UIManager UIManager;
private global::Gtk.Action FileAction;
private global::Gtk.Action SettingsAction;
private global::Gtk.Action QuitAction;
private global::Gtk.Action ReloadPluginsAction;
private global::Gtk.Action ReloadAction;
private global::Gtk.Action QuitAction1;
private global::Gtk.Action GeneralAction;
private global::Gtk.Action CarriersAction;
private global::Gtk.Action printAction;
private global::Gtk.Action openAction;
private global::Gtk.Action editAction;
private global::Gtk.Action WMSAction;
private global::Gtk.Action OpenOrderAction;
private global::Gtk.VBox WindowLayout;
private global::Gtk.MenuBar MainMenu;
private global::Gtk.HBox MainLayout;
private global::Gtk.VBox ActivityLayout;
private global::Gtk.VBox DetailsLayout;
private global::Gtk.VBox StatusLayout;
private global::Gtk.HBox StatusIndicatorsLayout;
private global::Gtk.VBox ProcessStatusLayout;
private global::Gtk.Image ProcessStatusImage;
private global::Gtk.Label ProcessStatusLabel;
private global::Gtk.VBox APIStatusLayout;
private global::Gtk.Image APIStatusImage;
private global::Gtk.Label APIStatusLabel;
private global::Gtk.ProgressBar StatusProgress;
private global::Gtk.VBox ControlsLayout;
private global::Gtk.HBox OrderControlsLayout;
private global::Gtk.ToggleButton AutoCheckButton;
private global::Gtk.ToggleButton AutoSendButton;
private global::Gtk.HBox AdvancedControlsLayout;
private global::Gtk.Button ManualCheckButton;
private global::Gtk.Button RepeatOrderButton;
private global::Gtk.HBox InspectControlsLayout;
private global::Gtk.Button SkipOrderButton;
private global::Gtk.Button SendOrderButton;
private global::Gtk.ScrolledWindow LogScrolledWindow;
private global::Gtk.TextView LogTextView;
private global::Gtk.VBox OrderEditorLayout;
private global::Gtk.HBox OrderHighlightLayout;
private global::Gtk.Label OrderNumberLabel;
private global::Gtk.Label OrderEmailLabel;
private global::Gtk.ScrolledWindow OrderEditorScrolledWindow;
private global::Gtk.TreeView OrderTableTreeview;
protected virtual void Build()
{
global::Stetic.Gui.Initialize(this);
// Widget MainWindow
this.UIManager = new global::Gtk.UIManager();
global::Gtk.ActionGroup w1 = new global::Gtk.ActionGroup("Default");
this.FileAction = new global::Gtk.Action("FileAction", global::Mono.Unix.Catalog.GetString("File"), null, null);
this.FileAction.ShortLabel = "File";
w1.Add(this.FileAction, null);
this.SettingsAction = new global::Gtk.Action("SettingsAction", global::Mono.Unix.Catalog.GetString("Settings"), null, null);
this.SettingsAction.ShortLabel = "Settings";
w1.Add(this.SettingsAction, null);
this.QuitAction = new global::Gtk.Action("QuitAction", global::Mono.Unix.Catalog.GetString("Quit"), null, null);
this.QuitAction.ShortLabel = global::Mono.Unix.Catalog.GetString("Quit");
w1.Add(this.QuitAction, null);
this.ReloadPluginsAction = new global::Gtk.Action("ReloadPluginsAction", global::Mono.Unix.Catalog.GetString("Reload Plugins"), null, null);
this.ReloadPluginsAction.ShortLabel = global::Mono.Unix.Catalog.GetString("Reload Plugins");
w1.Add(this.ReloadPluginsAction, null);
this.ReloadAction = new global::Gtk.Action("ReloadAction", global::Mono.Unix.Catalog.GetString("Reload"), global::Mono.Unix.Catalog.GetString("Reloads all Carriers, Rules and Zones."), "refresh");
this.ReloadAction.ShortLabel = "Reload Plugins";
w1.Add(this.ReloadAction, null);
this.QuitAction1 = new global::Gtk.Action("QuitAction1", global::Mono.Unix.Catalog.GetString("Quit"), global::Mono.Unix.Catalog.GetString("Exit UberDespatch."), "quit");
this.QuitAction1.ShortLabel = "Quit";
w1.Add(this.QuitAction1, null);
this.GeneralAction = new global::Gtk.Action("GeneralAction", global::Mono.Unix.Catalog.GetString("General"), global::Mono.Unix.Catalog.GetString("Configure UberDespatch (folder paths, logging, etc)."), "settings");
this.GeneralAction.ShortLabel = "General";
w1.Add(this.GeneralAction, null);
this.CarriersAction = new global::Gtk.Action("CarriersAction", global::Mono.Unix.Catalog.GetString("Carriers"), global::Mono.Unix.Catalog.GetString("Open the configuration menus for loaded carriers."), "plugin");
this.CarriersAction.ShortLabel = "Configure Carriers";
w1.Add(this.CarriersAction, null);
this.printAction = new global::Gtk.Action("printAction", global::Mono.Unix.Catalog.GetString("Printer Manager"), global::Mono.Unix.Catalog.GetString("Opens the Printer Manager which can be used to setup printer profiles to corrospo" +
"nd to the printers set by rules this includes the default printing settings."), "gtk-print");
this.printAction.ShortLabel = global::Mono.Unix.Catalog.GetString("Printer Manager");
w1.Add(this.printAction, null);
this.openAction = new global::Gtk.Action("openAction", global::Mono.Unix.Catalog.GetString("Open Archive Folder"), global::Mono.Unix.Catalog.GetString("Open the order archive folder."), "gtk-open");
this.openAction.ShortLabel = global::Mono.Unix.Catalog.GetString("Open Archive Folder");
w1.Add(this.openAction, null);
this.editAction = new global::Gtk.Action("editAction", global::Mono.Unix.Catalog.GetString("Rules"), global::Mono.Unix.Catalog.GetString("Set the local paths or remote URLs for rule information, this includes zones, lab" +
"els, alerts, etc."), "gtk-edit");
this.editAction.ShortLabel = global::Mono.Unix.Catalog.GetString("Rules");
w1.Add(this.editAction, null);
this.WMSAction = new global::Gtk.Action("WMSAction", global::Mono.Unix.Catalog.GetString("WMS"), global::Mono.Unix.Catalog.GetString("Open the Warehouse Management System settings."), "plugin");
this.WMSAction.ShortLabel = global::Mono.Unix.Catalog.GetString("Configure Warehouse Management System");
w1.Add(this.WMSAction, null);
this.OpenOrderAction = new global::Gtk.Action("OpenOrderAction", global::Mono.Unix.Catalog.GetString("Open Order"), global::Mono.Unix.Catalog.GetString("Open an order from file such as an old archived order."), "gtk-open");
this.OpenOrderAction.ShortLabel = global::Mono.Unix.Catalog.GetString("Open Order");
w1.Add(this.OpenOrderAction, null);
this.UIManager.InsertActionGroup(w1, 0);
this.AddAccelGroup(this.UIManager.AccelGroup);
this.Name = "MainWindow";
this.Title = global::Mono.Unix.Catalog.GetString("UberDespatch");
this.Icon = new global::Gdk.Pixbuf(global::System.IO.Path.Combine(global::System.AppDomain.CurrentDomain.BaseDirectory, "./icon.png"));
this.WindowPosition = ((global::Gtk.WindowPosition)(4));
// Container child MainWindow.Gtk.Container+ContainerChild
this.WindowLayout = new global::Gtk.VBox();
this.WindowLayout.Name = "WindowLayout";
this.WindowLayout.Spacing = 6;
// Container child WindowLayout.Gtk.Box+BoxChild
this.UIManager.AddUiFromString(@"<ui><menubar name='MainMenu'><menu name='FileAction' action='FileAction'><menuitem name='ReloadAction' action='ReloadAction'/><menuitem name='openAction' action='openAction'/><menuitem name='OpenOrderAction' action='OpenOrderAction'/><separator/><menuitem name='QuitAction1' action='QuitAction1'/></menu><menu name='SettingsAction' action='SettingsAction'><menuitem name='GeneralAction' action='GeneralAction'/><menuitem name='printAction' action='printAction'/><menuitem name='editAction' action='editAction'/><separator/><menuitem name='WMSAction' action='WMSAction'/><menuitem name='CarriersAction' action='CarriersAction'/></menu></menubar></ui>");
this.MainMenu = ((global::Gtk.MenuBar)(this.UIManager.GetWidget("/MainMenu")));
this.MainMenu.Name = "MainMenu";
this.WindowLayout.Add(this.MainMenu);
global::Gtk.Box.BoxChild w2 = ((global::Gtk.Box.BoxChild)(this.WindowLayout[this.MainMenu]));
w2.Position = 0;
w2.Expand = false;
w2.Fill = false;
// Container child WindowLayout.Gtk.Box+BoxChild
this.MainLayout = new global::Gtk.HBox();
this.MainLayout.Name = "MainLayout";
this.MainLayout.Spacing = 6;
// Container child MainLayout.Gtk.Box+BoxChild
this.ActivityLayout = new global::Gtk.VBox();
this.ActivityLayout.Name = "ActivityLayout";
this.ActivityLayout.Spacing = 6;
// Container child ActivityLayout.Gtk.Box+BoxChild
this.DetailsLayout = new global::Gtk.VBox();
this.DetailsLayout.Name = "DetailsLayout";
this.DetailsLayout.Spacing = 6;
// Container child DetailsLayout.Gtk.Box+BoxChild
this.StatusLayout = new global::Gtk.VBox();
this.StatusLayout.Name = "StatusLayout";
this.StatusLayout.Spacing = 6;
// Container child StatusLayout.Gtk.Box+BoxChild
this.StatusIndicatorsLayout = new global::Gtk.HBox();
this.StatusIndicatorsLayout.Name = "StatusIndicatorsLayout";
this.StatusIndicatorsLayout.Spacing = 6;
// Container child StatusIndicatorsLayout.Gtk.Box+BoxChild
this.ProcessStatusLayout = new global::Gtk.VBox();
this.ProcessStatusLayout.Name = "ProcessStatusLayout";
this.ProcessStatusLayout.Spacing = 6;
// Container child ProcessStatusLayout.Gtk.Box+BoxChild
this.ProcessStatusImage = new global::Gtk.Image();
this.ProcessStatusImage.TooltipMarkup = "Order process status.";
this.ProcessStatusImage.WidthRequest = 150;
this.ProcessStatusImage.HeightRequest = 50;
this.ProcessStatusImage.Name = "ProcessStatusImage";
this.ProcessStatusImage.Pixbuf = new global::Gdk.Pixbuf(global::System.IO.Path.Combine(global::System.AppDomain.CurrentDomain.BaseDirectory, "./Icons/png/execute.png"));
this.ProcessStatusLayout.Add(this.ProcessStatusImage);
global::Gtk.Box.BoxChild w3 = ((global::Gtk.Box.BoxChild)(this.ProcessStatusLayout[this.ProcessStatusImage]));
w3.Position = 0;
// Container child ProcessStatusLayout.Gtk.Box+BoxChild
this.ProcessStatusLabel = new global::Gtk.Label();
this.ProcessStatusLabel.TooltipMarkup = "Order process status.";
this.ProcessStatusLabel.WidthRequest = 150;
this.ProcessStatusLabel.Name = "ProcessStatusLabel";
this.ProcessStatusLabel.LabelProp = "Starting Up...";
this.ProcessStatusLabel.UseMarkup = true;
this.ProcessStatusLabel.Justify = ((global::Gtk.Justification)(2));
this.ProcessStatusLabel.SingleLineMode = true;
this.ProcessStatusLayout.Add(this.ProcessStatusLabel);
global::Gtk.Box.BoxChild w4 = ((global::Gtk.Box.BoxChild)(this.ProcessStatusLayout[this.ProcessStatusLabel]));
w4.Position = 1;
this.StatusIndicatorsLayout.Add(this.ProcessStatusLayout);
global::Gtk.Box.BoxChild w5 = ((global::Gtk.Box.BoxChild)(this.StatusIndicatorsLayout[this.ProcessStatusLayout]));
w5.Position = 0;
// Container child StatusIndicatorsLayout.Gtk.Box+BoxChild
this.APIStatusLayout = new global::Gtk.VBox();
this.APIStatusLayout.Name = "APIStatusLayout";
this.APIStatusLayout.Spacing = 6;
// Container child APIStatusLayout.Gtk.Box+BoxChild
this.APIStatusImage = new global::Gtk.Image();
this.APIStatusImage.TooltipMarkup = "PeopleVox API connection status.";
this.APIStatusImage.WidthRequest = 150;
this.APIStatusImage.HeightRequest = 50;
this.APIStatusImage.Name = "APIStatusImage";
this.APIStatusImage.Pixbuf = new global::Gdk.Pixbuf(global::System.IO.Path.Combine(global::System.AppDomain.CurrentDomain.BaseDirectory, "./Icons/png/refresh.png"));
this.APIStatusLayout.Add(this.APIStatusImage);
global::Gtk.Box.BoxChild w6 = ((global::Gtk.Box.BoxChild)(this.APIStatusLayout[this.APIStatusImage]));
w6.Position = 0;
// Container child APIStatusLayout.Gtk.Box+BoxChild
this.APIStatusLabel = new global::Gtk.Label();
this.APIStatusLabel.TooltipMarkup = "PeopleVox API connection status.";
this.APIStatusLabel.WidthRequest = 150;
this.APIStatusLabel.Name = "APIStatusLabel";
this.APIStatusLabel.LabelProp = "WMS: Connecting";
this.APIStatusLabel.UseMarkup = true;
this.APIStatusLabel.Justify = ((global::Gtk.Justification)(2));
this.APIStatusLabel.SingleLineMode = true;
this.APIStatusLayout.Add(this.APIStatusLabel);
global::Gtk.Box.BoxChild w7 = ((global::Gtk.Box.BoxChild)(this.APIStatusLayout[this.APIStatusLabel]));
w7.Position = 1;
this.StatusIndicatorsLayout.Add(this.APIStatusLayout);
global::Gtk.Box.BoxChild w8 = ((global::Gtk.Box.BoxChild)(this.StatusIndicatorsLayout[this.APIStatusLayout]));
w8.Position = 1;
this.StatusLayout.Add(this.StatusIndicatorsLayout);
global::Gtk.Box.BoxChild w9 = ((global::Gtk.Box.BoxChild)(this.StatusLayout[this.StatusIndicatorsLayout]));
w9.Position = 0;
w9.Expand = false;
w9.Fill = false;
// Container child StatusLayout.Gtk.Box+BoxChild
this.StatusProgress = new global::Gtk.ProgressBar();
this.StatusProgress.TooltipMarkup = "Current action progress.";
this.StatusProgress.HeightRequest = 1;
this.StatusProgress.Name = "StatusProgress";
this.StatusLayout.Add(this.StatusProgress);
global::Gtk.Box.BoxChild w10 = ((global::Gtk.Box.BoxChild)(this.StatusLayout[this.StatusProgress]));
w10.Position = 1;
w10.Expand = false;
w10.Fill = false;
this.DetailsLayout.Add(this.StatusLayout);
global::Gtk.Box.BoxChild w11 = ((global::Gtk.Box.BoxChild)(this.DetailsLayout[this.StatusLayout]));
w11.Position = 0;
w11.Expand = false;
w11.Fill = false;
// Container child DetailsLayout.Gtk.Box+BoxChild
this.ControlsLayout = new global::Gtk.VBox();
this.ControlsLayout.Name = "ControlsLayout";
this.ControlsLayout.Spacing = 6;
// Container child ControlsLayout.Gtk.Box+BoxChild
this.OrderControlsLayout = new global::Gtk.HBox();
this.OrderControlsLayout.Name = "OrderControlsLayout";
this.OrderControlsLayout.Spacing = 6;
// Container child OrderControlsLayout.Gtk.Box+BoxChild
this.AutoCheckButton = new global::Gtk.ToggleButton();
this.AutoCheckButton.TooltipMarkup = "When enabled, UberDespatch will automatically check for a new order every few sec" +
"onds.";
this.AutoCheckButton.WidthRequest = 150;
this.AutoCheckButton.HeightRequest = 40;
this.AutoCheckButton.CanFocus = true;
this.AutoCheckButton.Name = "AutoCheckButton";
this.AutoCheckButton.UseUnderline = true;
this.AutoCheckButton.Label = "Auto Check (Off)";
global::Gtk.Image w12 = new global::Gtk.Image();
w12.Pixbuf = new global::Gdk.Pixbuf(global::System.IO.Path.Combine(global::System.AppDomain.CurrentDomain.BaseDirectory, "./Icons/png/no-small.png"));
this.AutoCheckButton.Image = w12;
this.OrderControlsLayout.Add(this.AutoCheckButton);
global::Gtk.Box.BoxChild w13 = ((global::Gtk.Box.BoxChild)(this.OrderControlsLayout[this.AutoCheckButton]));
w13.Position = 0;
// Container child OrderControlsLayout.Gtk.Box+BoxChild
this.AutoSendButton = new global::Gtk.ToggleButton();
this.AutoSendButton.TooltipMarkup = "When enabled, ever order will be flagged for edit.";
this.AutoSendButton.WidthRequest = 150;
this.AutoSendButton.HeightRequest = 40;
this.AutoSendButton.CanFocus = true;
this.AutoSendButton.Name = "AutoSendButton";
this.AutoSendButton.UseUnderline = true;
this.AutoSendButton.Label = "Auto Send (On)";
global::Gtk.Image w14 = new global::Gtk.Image();
w14.Pixbuf = new global::Gdk.Pixbuf(global::System.IO.Path.Combine(global::System.AppDomain.CurrentDomain.BaseDirectory, "./Icons/png/edit-small.png"));
this.AutoSendButton.Image = w14;
this.OrderControlsLayout.Add(this.AutoSendButton);
global::Gtk.Box.BoxChild w15 = ((global::Gtk.Box.BoxChild)(this.OrderControlsLayout[this.AutoSendButton]));
w15.Position = 1;
this.ControlsLayout.Add(this.OrderControlsLayout);
global::Gtk.Box.BoxChild w16 = ((global::Gtk.Box.BoxChild)(this.ControlsLayout[this.OrderControlsLayout]));
w16.Position = 0;
w16.Expand = false;
w16.Fill = false;
// Container child ControlsLayout.Gtk.Box+BoxChild
this.AdvancedControlsLayout = new global::Gtk.HBox();
this.AdvancedControlsLayout.Name = "AdvancedControlsLayout";
this.AdvancedControlsLayout.Spacing = 6;
// Container child AdvancedControlsLayout.Gtk.Box+BoxChild
this.ManualCheckButton = new global::Gtk.Button();
this.ManualCheckButton.TooltipMarkup = "Click to search for a new order right now.";
this.ManualCheckButton.WidthRequest = 150;
this.ManualCheckButton.HeightRequest = 40;
this.ManualCheckButton.CanFocus = true;
this.ManualCheckButton.Name = "ManualCheckButton";
this.ManualCheckButton.UseUnderline = true;
this.ManualCheckButton.Label = "Manual Check";
global::Gtk.Image w17 = new global::Gtk.Image();
w17.Pixbuf = new global::Gdk.Pixbuf(global::System.IO.Path.Combine(global::System.AppDomain.CurrentDomain.BaseDirectory, "./Icons/png/find-small.png"));
this.ManualCheckButton.Image = w17;
this.AdvancedControlsLayout.Add(this.ManualCheckButton);
global::Gtk.Box.BoxChild w18 = ((global::Gtk.Box.BoxChild)(this.AdvancedControlsLayout[this.ManualCheckButton]));
w18.Position = 0;
// Container child AdvancedControlsLayout.Gtk.Box+BoxChild
this.RepeatOrderButton = new global::Gtk.Button();
this.RepeatOrderButton.TooltipMarkup = "Repeats the last order that was successful, failed or skipped. This can be used w" +
"ith Inspection enabled to correct orders that have failed.";
this.RepeatOrderButton.WidthRequest = 150;
this.RepeatOrderButton.HeightRequest = 40;
this.RepeatOrderButton.CanFocus = true;
this.RepeatOrderButton.Name = "RepeatOrderButton";
this.RepeatOrderButton.UseUnderline = true;
this.RepeatOrderButton.Label = "Repeat Order";
global::Gtk.Image w19 = new global::Gtk.Image();
w19.Pixbuf = new global::Gdk.Pixbuf(global::System.IO.Path.Combine(global::System.AppDomain.CurrentDomain.BaseDirectory, "./Icons/png/refresh-small.png"));
this.RepeatOrderButton.Image = w19;
this.AdvancedControlsLayout.Add(this.RepeatOrderButton);
global::Gtk.Box.BoxChild w20 = ((global::Gtk.Box.BoxChild)(this.AdvancedControlsLayout[this.RepeatOrderButton]));
w20.Position = 1;
this.ControlsLayout.Add(this.AdvancedControlsLayout);
global::Gtk.Box.BoxChild w21 = ((global::Gtk.Box.BoxChild)(this.ControlsLayout[this.AdvancedControlsLayout]));
w21.Position = 1;
w21.Expand = false;
w21.Fill = false;
// Container child ControlsLayout.Gtk.Box+BoxChild
this.InspectControlsLayout = new global::Gtk.HBox();
this.InspectControlsLayout.Name = "InspectControlsLayout";
this.InspectControlsLayout.Spacing = 6;
// Container child InspectControlsLayout.Gtk.Box+BoxChild
this.SkipOrderButton = new global::Gtk.Button();
this.SkipOrderButton.TooltipMarkup = "Use to skip the current problematic order, the skipped order will be archived.";
this.SkipOrderButton.WidthRequest = 150;
this.SkipOrderButton.HeightRequest = 40;
this.SkipOrderButton.CanFocus = true;
this.SkipOrderButton.Name = "SkipOrderButton";
this.SkipOrderButton.UseUnderline = true;
this.SkipOrderButton.Label = "Skip Order";
global::Gtk.Image w22 = new global::Gtk.Image();
w22.Pixbuf = new global::Gdk.Pixbuf(global::System.IO.Path.Combine(global::System.AppDomain.CurrentDomain.BaseDirectory, "./Icons/png/skip-small.png"));
this.SkipOrderButton.Image = w22;
this.InspectControlsLayout.Add(this.SkipOrderButton);
global::Gtk.Box.BoxChild w23 = ((global::Gtk.Box.BoxChild)(this.InspectControlsLayout[this.SkipOrderButton]));
w23.Position = 0;
// Container child InspectControlsLayout.Gtk.Box+BoxChild
this.SendOrderButton = new global::Gtk.Button();
this.SendOrderButton.TooltipMarkup = "Send the current order (only needed when editing orders).";
this.SendOrderButton.WidthRequest = 150;
this.SendOrderButton.HeightRequest = 40;
this.SendOrderButton.CanFocus = true;
this.SendOrderButton.Name = "SendOrderButton";
this.SendOrderButton.UseUnderline = true;
this.SendOrderButton.Label = "Send Order";
global::Gtk.Image w24 = new global::Gtk.Image();
w24.Pixbuf = new global::Gdk.Pixbuf(global::System.IO.Path.Combine(global::System.AppDomain.CurrentDomain.BaseDirectory, "./Icons/png/play-small.png"));
this.SendOrderButton.Image = w24;
this.InspectControlsLayout.Add(this.SendOrderButton);
global::Gtk.Box.BoxChild w25 = ((global::Gtk.Box.BoxChild)(this.InspectControlsLayout[this.SendOrderButton]));
w25.Position = 1;
this.ControlsLayout.Add(this.InspectControlsLayout);
global::Gtk.Box.BoxChild w26 = ((global::Gtk.Box.BoxChild)(this.ControlsLayout[this.InspectControlsLayout]));
w26.Position = 2;
w26.Expand = false;
w26.Fill = false;
this.DetailsLayout.Add(this.ControlsLayout);
global::Gtk.Box.BoxChild w27 = ((global::Gtk.Box.BoxChild)(this.DetailsLayout[this.ControlsLayout]));
w27.Position = 1;
w27.Expand = false;
w27.Fill = false;
this.ActivityLayout.Add(this.DetailsLayout);
global::Gtk.Box.BoxChild w28 = ((global::Gtk.Box.BoxChild)(this.ActivityLayout[this.DetailsLayout]));
w28.Position = 0;
w28.Expand = false;
w28.Fill = false;
// Container child ActivityLayout.Gtk.Box+BoxChild
this.LogScrolledWindow = new global::Gtk.ScrolledWindow();
this.LogScrolledWindow.Name = "LogScrolledWindow";
this.LogScrolledWindow.ShadowType = ((global::Gtk.ShadowType)(1));
// Container child LogScrolledWindow.Gtk.Container+ContainerChild
this.LogTextView = new global::Gtk.TextView();
this.LogTextView.WidthRequest = 500;
this.LogTextView.HeightRequest = 300;
this.LogTextView.CanFocus = true;
this.LogTextView.Name = "LogTextView";
this.LogTextView.Editable = false;
this.LogTextView.WrapMode = ((global::Gtk.WrapMode)(2));
this.LogTextView.LeftMargin = 4;
this.LogTextView.RightMargin = 4;
this.LogScrolledWindow.Add(this.LogTextView);
this.ActivityLayout.Add(this.LogScrolledWindow);
global::Gtk.Box.BoxChild w30 = ((global::Gtk.Box.BoxChild)(this.ActivityLayout[this.LogScrolledWindow]));
w30.Position = 1;
this.MainLayout.Add(this.ActivityLayout);
global::Gtk.Box.BoxChild w31 = ((global::Gtk.Box.BoxChild)(this.MainLayout[this.ActivityLayout]));
w31.Position = 0;
w31.Expand = false;
w31.Fill = false;
// Container child MainLayout.Gtk.Box+BoxChild
this.OrderEditorLayout = new global::Gtk.VBox();
this.OrderEditorLayout.Name = "OrderEditorLayout";
this.OrderEditorLayout.Spacing = 6;
// Container child OrderEditorLayout.Gtk.Box+BoxChild
this.OrderHighlightLayout = new global::Gtk.HBox();
this.OrderHighlightLayout.Name = "OrderHighlightLayout";
this.OrderHighlightLayout.Spacing = 6;
// Container child OrderHighlightLayout.Gtk.Box+BoxChild
this.OrderNumberLabel = new global::Gtk.Label();
this.OrderNumberLabel.TooltipMarkup = "PeopleVox API connection status.";
this.OrderNumberLabel.WidthRequest = 150;
this.OrderNumberLabel.Name = "OrderNumberLabel";
this.OrderNumberLabel.UseMarkup = true;
this.OrderNumberLabel.Justify = ((global::Gtk.Justification)(2));
this.OrderNumberLabel.SingleLineMode = true;
this.OrderHighlightLayout.Add(this.OrderNumberLabel);
global::Gtk.Box.BoxChild w32 = ((global::Gtk.Box.BoxChild)(this.OrderHighlightLayout[this.OrderNumberLabel]));
w32.Position = 0;
// Container child OrderHighlightLayout.Gtk.Box+BoxChild
this.OrderEmailLabel = new global::Gtk.Label();
this.OrderEmailLabel.TooltipMarkup = "Order process status.";
this.OrderEmailLabel.WidthRequest = 150;
this.OrderEmailLabel.Name = "OrderEmailLabel";
this.OrderEmailLabel.UseMarkup = true;
this.OrderEmailLabel.Justify = ((global::Gtk.Justification)(2));
this.OrderEmailLabel.SingleLineMode = true;
this.OrderHighlightLayout.Add(this.OrderEmailLabel);
global::Gtk.Box.BoxChild w33 = ((global::Gtk.Box.BoxChild)(this.OrderHighlightLayout[this.OrderEmailLabel]));
w33.Position = 1;
this.OrderEditorLayout.Add(this.OrderHighlightLayout);
global::Gtk.Box.BoxChild w34 = ((global::Gtk.Box.BoxChild)(this.OrderEditorLayout[this.OrderHighlightLayout]));
w34.Position = 0;
w34.Expand = false;
w34.Fill = false;
// Container child OrderEditorLayout.Gtk.Box+BoxChild
this.OrderEditorScrolledWindow = new global::Gtk.ScrolledWindow();
this.OrderEditorScrolledWindow.Name = "OrderEditorScrolledWindow";
this.OrderEditorScrolledWindow.ShadowType = ((global::Gtk.ShadowType)(1));
// Container child OrderEditorScrolledWindow.Gtk.Container+ContainerChild
this.OrderTableTreeview = new global::Gtk.TreeView();
this.OrderTableTreeview.WidthRequest = 450;
this.OrderTableTreeview.CanFocus = true;
this.OrderTableTreeview.Name = "OrderTableTreeview";
this.OrderTableTreeview.HeadersVisible = false;
this.OrderTableTreeview.HoverSelection = true;
this.OrderEditorScrolledWindow.Add(this.OrderTableTreeview);
this.OrderEditorLayout.Add(this.OrderEditorScrolledWindow);
global::Gtk.Box.BoxChild w36 = ((global::Gtk.Box.BoxChild)(this.OrderEditorLayout[this.OrderEditorScrolledWindow]));
w36.Position = 1;
this.MainLayout.Add(this.OrderEditorLayout);
global::Gtk.Box.BoxChild w37 = ((global::Gtk.Box.BoxChild)(this.MainLayout[this.OrderEditorLayout]));
w37.Position = 1;
this.WindowLayout.Add(this.MainLayout);
global::Gtk.Box.BoxChild w38 = ((global::Gtk.Box.BoxChild)(this.WindowLayout[this.MainLayout]));
w38.Position = 1;
this.Add(this.WindowLayout);
if ((this.Child != null))
{
this.Child.ShowAll();
}
this.DefaultWidth = 988;
this.DefaultHeight = 590;
this.Show();
this.DeleteEvent += new global::Gtk.DeleteEventHandler(this.OnDeleteEvent);
this.ReloadAction.Activated += new global::System.EventHandler(this.OnReloadActivated);
this.QuitAction1.Activated += new global::System.EventHandler(this.OnQuitActionActivated);
this.GeneralAction.Activated += new global::System.EventHandler(this.OnOptionsActionActivated);
this.CarriersAction.Activated += new global::System.EventHandler(this.OnCarriersActionActivated);
this.printAction.Activated += new global::System.EventHandler(this.OnPrinterActionActivated);
this.openAction.Activated += new global::System.EventHandler(this.OnOpenArchiveActivated);
this.editAction.Activated += new global::System.EventHandler(this.OnRulesActionActivated);
this.WMSAction.Activated += new global::System.EventHandler(this.OnWMSActionActivated);
this.OpenOrderAction.Activated += new global::System.EventHandler(this.OnOpenOrderActivated);
this.AutoCheckButton.Toggled += new global::System.EventHandler(this.OnAutoCheckButtonReleased);
this.AutoSendButton.Toggled += new global::System.EventHandler(this.OnAutoSendButtonReleased);
this.ManualCheckButton.Released += new global::System.EventHandler(this.OnManualCheckButtonReleased);
this.RepeatOrderButton.Released += new global::System.EventHandler(this.OnRepeatOrderButtonReleased);
this.SkipOrderButton.Released += new global::System.EventHandler(this.OnSkipOrderButtonReleased);
this.SendOrderButton.Released += new global::System.EventHandler(this.OnSendOrderButtonReleased);
}
}
| |
using UnityEngine;
namespace UnityStandardAssets.Vehicles.Car
{
internal enum CarDriveType
{
FrontWheelDrive,
RearWheelDrive,
FourWheelDrive
}
internal enum SpeedType
{
MPH,
KPH
}
public class CarController : MonoBehaviour
{
[SerializeField] private CarDriveType m_CarDriveType = CarDriveType.FourWheelDrive;
[SerializeField] private WheelCollider[] m_WheelColliders = new WheelCollider[4];
[SerializeField] private GameObject[] m_WheelMeshes = new GameObject[4];
[SerializeField] private WheelEffects[] m_WheelEffects = new WheelEffects[4];
[SerializeField] private Vector3 m_CentreOfMassOffset;
[SerializeField] private float m_MaximumSteerAngle;
[Range(0, 1)] [SerializeField] private float m_SteerHelper; // 0 is raw physics , 1 the car will grip in the direction it is facing
[Range(0, 1)] [SerializeField] private float m_TractionControl; // 0 is no traction control, 1 is full interference
[SerializeField] private float m_FullTorqueOverAllWheels;
[SerializeField] private float m_ReverseTorque;
[SerializeField] private float m_MaxHandbrakeTorque;
[SerializeField] private float m_Downforce = 100f;
[SerializeField] private SpeedType m_SpeedType;
[SerializeField] private float m_Topspeed = 200;
[SerializeField] private static int NoOfGears = 5;
[SerializeField] private float m_RevRangeBoundary = 1f;
[SerializeField] private float m_SlipLimit;
[SerializeField] private float m_BrakeTorque;
private Quaternion[] m_WheelMeshLocalRotations;
private Vector3 m_Prevpos, m_Pos;
private float m_SteerAngle;
private int m_GearNum;
private float m_GearFactor;
private float m_OldRotation;
private float m_CurrentTorque;
private Rigidbody m_Rigidbody;
private const float k_ReversingThreshold = 0.01f;
public bool Skidding { get; private set; }
public float BrakeInput { get; private set; }
public float CurrentSteerAngle{ get { return m_SteerAngle; }}
public float CurrentSpeed{ get { return m_Rigidbody.velocity.magnitude*2.23693629f; }}
public float MaxSpeed{get { return m_Topspeed; }}
public float Revs { get; private set; }
public float AccelInput { get; private set; }
// Use this for initialization
private void Start()
{
m_WheelMeshLocalRotations = new Quaternion[4];
for (int i = 0; i < 4; i++)
{
m_WheelMeshLocalRotations[i] = m_WheelMeshes[i].transform.localRotation;
}
m_WheelColliders[0].attachedRigidbody.centerOfMass = m_CentreOfMassOffset;
m_MaxHandbrakeTorque = float.MaxValue;
m_Rigidbody = GetComponent<Rigidbody>();
m_CurrentTorque = m_FullTorqueOverAllWheels - (m_TractionControl*m_FullTorqueOverAllWheels);
}
private void GearChanging()
{
float f = Mathf.Abs(CurrentSpeed/MaxSpeed);
float upgearlimit = (1/(float) NoOfGears)*(m_GearNum + 1);
float downgearlimit = (1/(float) NoOfGears)*m_GearNum;
if (m_GearNum > 0 && f < downgearlimit)
{
m_GearNum--;
}
if (f > upgearlimit && (m_GearNum < (NoOfGears - 1)))
{
m_GearNum++;
}
}
// simple function to add a curved bias towards 1 for a value in the 0-1 range
private static float CurveFactor(float factor)
{
return 1 - (1 - factor)*(1 - factor);
}
// unclamped version of Lerp, to allow value to exceed the from-to range
private static float ULerp(float from, float to, float value)
{
return (1.0f - value)*from + value*to;
}
private void CalculateGearFactor()
{
float f = (1/(float) NoOfGears);
// gear factor is a normalised representation of the current speed within the current gear's range of speeds.
// We smooth towards the 'target' gear factor, so that revs don't instantly snap up or down when changing gear.
var targetGearFactor = Mathf.InverseLerp(f*m_GearNum, f*(m_GearNum + 1), Mathf.Abs(CurrentSpeed/MaxSpeed));
m_GearFactor = Mathf.Lerp(m_GearFactor, targetGearFactor, Time.deltaTime*5f);
}
private void CalculateRevs()
{
// calculate engine revs (for display / sound)
// (this is done in retrospect - revs are not used in force/power calculations)
CalculateGearFactor();
var gearNumFactor = m_GearNum/(float) NoOfGears;
var revsRangeMin = ULerp(0f, m_RevRangeBoundary, CurveFactor(gearNumFactor));
var revsRangeMax = ULerp(m_RevRangeBoundary, 1f, gearNumFactor);
Revs = ULerp(revsRangeMin, revsRangeMax, m_GearFactor);
}
public void Move(float steering, float accel, float footbrake, float handbrake)
{
for (int i = 0; i < 4; i++)
{
Quaternion quat;
Vector3 position;
m_WheelColliders[i].GetWorldPose(out position, out quat);
m_WheelMeshes[i].transform.position = position;
m_WheelMeshes[i].transform.rotation = quat;
}
//clamp input values
steering = Mathf.Clamp(steering, -1, 1);
AccelInput = accel = Mathf.Clamp(accel, 0, 1);
BrakeInput = footbrake = -1*Mathf.Clamp(footbrake, -1, 0);
handbrake = Mathf.Clamp(handbrake, 0, 1);
//Set the steer on the front wheels.
//Assuming that wheels 0 and 1 are the front wheels.
m_SteerAngle = steering*m_MaximumSteerAngle;
m_WheelColliders[0].steerAngle = m_SteerAngle;
m_WheelColliders[1].steerAngle = m_SteerAngle;
SteerHelper();
ApplyDrive(accel, footbrake);
CapSpeed();
//Set the handbrake.
//Assuming that wheels 2 and 3 are the rear wheels.
if (handbrake > 0f)
{
var hbTorque = handbrake*m_MaxHandbrakeTorque;
m_WheelColliders[2].brakeTorque = hbTorque;
m_WheelColliders[3].brakeTorque = hbTorque;
}
CalculateRevs();
GearChanging();
AddDownForce();
CheckForWheelSpin();
TractionControl();
}
private void CapSpeed()
{
float speed = m_Rigidbody.velocity.magnitude;
switch (m_SpeedType)
{
case SpeedType.MPH:
speed *= 2.23693629f;
if (speed > m_Topspeed)
m_Rigidbody.velocity = (m_Topspeed/2.23693629f) * m_Rigidbody.velocity.normalized;
break;
case SpeedType.KPH:
speed *= 3.6f;
if (speed > m_Topspeed)
m_Rigidbody.velocity = (m_Topspeed/3.6f) * m_Rigidbody.velocity.normalized;
break;
}
}
private void ApplyDrive(float accel, float footbrake)
{
float thrustTorque;
switch (m_CarDriveType)
{
case CarDriveType.FourWheelDrive:
thrustTorque = accel * (m_CurrentTorque / 4f);
for (int i = 0; i < 4; i++)
{
m_WheelColliders[i].motorTorque = thrustTorque;
}
break;
case CarDriveType.FrontWheelDrive:
thrustTorque = accel * (m_CurrentTorque / 2f);
m_WheelColliders[0].motorTorque = m_WheelColliders[1].motorTorque = thrustTorque;
break;
case CarDriveType.RearWheelDrive:
thrustTorque = accel * (m_CurrentTorque / 2f);
m_WheelColliders[2].motorTorque = m_WheelColliders[3].motorTorque = thrustTorque;
break;
}
for (int i = 0; i < 4; i++)
{
if (CurrentSpeed > 5 && Vector3.Angle(transform.forward, m_Rigidbody.velocity) < 50f)
{
m_WheelColliders[i].brakeTorque = m_BrakeTorque*footbrake;
}
else if (footbrake > 0)
{
m_WheelColliders[i].brakeTorque = 0f;
m_WheelColliders[i].motorTorque = -m_ReverseTorque*footbrake;
}
}
}
private void SteerHelper()
{
for (int i = 0; i < 4; i++)
{
WheelHit wheelhit;
m_WheelColliders[i].GetGroundHit(out wheelhit);
if (wheelhit.normal == Vector3.zero)
return; // wheels arent on the ground so dont realign the rigidbody velocity
}
// this if is needed to avoid gimbal lock problems that will make the car suddenly shift direction
if (Mathf.Abs(m_OldRotation - transform.eulerAngles.y) < 10f)
{
var turnadjust = (transform.eulerAngles.y - m_OldRotation) * m_SteerHelper;
Quaternion velRotation = Quaternion.AngleAxis(turnadjust, Vector3.up);
m_Rigidbody.velocity = velRotation * m_Rigidbody.velocity;
}
m_OldRotation = transform.eulerAngles.y;
}
// this is used to add more grip in relation to speed
private void AddDownForce()
{
m_WheelColliders[0].attachedRigidbody.AddForce(-transform.up*m_Downforce*
m_WheelColliders[0].attachedRigidbody.velocity.magnitude);
}
// checks if the wheels are spinning and is so does three things
// 1) emits particles
// 2) plays tiure skidding sounds
// 3) leaves skidmarks on the ground
// these effects are controlled through the WheelEffects class
private void CheckForWheelSpin()
{
// loop through all wheels
for (int i = 0; i < 4; i++)
{
WheelHit wheelHit;
m_WheelColliders[i].GetGroundHit(out wheelHit);
// is the tire slipping above the given threshhold
if (Mathf.Abs(wheelHit.forwardSlip) >= m_SlipLimit || Mathf.Abs(wheelHit.sidewaysSlip) >= m_SlipLimit)
{
m_WheelEffects[i].EmitTyreSmoke();
// avoiding all four tires screeching at the same time
// if they do it can lead to some strange audio artefacts
if (!AnySkidSoundPlaying())
{
m_WheelEffects[i].PlayAudio();
}
continue;
}
// if it wasnt slipping stop all the audio
if (m_WheelEffects[i].PlayingAudio)
{
m_WheelEffects[i].StopAudio();
}
// end the trail generation
m_WheelEffects[i].EndSkidTrail();
}
}
// crude traction control that reduces the power to wheel if the car is wheel spinning too much
private void TractionControl()
{
WheelHit wheelHit;
switch (m_CarDriveType)
{
case CarDriveType.FourWheelDrive:
// loop through all wheels
for (int i = 0; i < 4; i++)
{
m_WheelColliders[i].GetGroundHit(out wheelHit);
AdjustTorque(wheelHit.forwardSlip);
}
break;
case CarDriveType.RearWheelDrive:
m_WheelColliders[2].GetGroundHit(out wheelHit);
AdjustTorque(wheelHit.forwardSlip);
m_WheelColliders[3].GetGroundHit(out wheelHit);
AdjustTorque(wheelHit.forwardSlip);
break;
case CarDriveType.FrontWheelDrive:
m_WheelColliders[0].GetGroundHit(out wheelHit);
AdjustTorque(wheelHit.forwardSlip);
m_WheelColliders[1].GetGroundHit(out wheelHit);
AdjustTorque(wheelHit.forwardSlip);
break;
}
}
private void AdjustTorque(float forwardSlip)
{
if (forwardSlip >= m_SlipLimit && m_CurrentTorque >= 0)
{
m_CurrentTorque -= 10 * m_TractionControl;
}
else
{
m_CurrentTorque += 10 * m_TractionControl;
if (m_CurrentTorque > m_FullTorqueOverAllWheels)
{
m_CurrentTorque = m_FullTorqueOverAllWheels;
}
}
}
private bool AnySkidSoundPlaying()
{
for (int i = 0; i < 4; i++)
{
if (m_WheelEffects[i].PlayingAudio)
{
return true;
}
}
return false;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.AppService.Fluent
{
using Microsoft.Azure.Management.AppService.Fluent.Models;
using Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Definition;
using Microsoft.Azure.Management.AppService.Fluent.WebAppBase.Update;
using Microsoft.Azure.Management.AppService.Fluent.WebAppDiagnosticLogs.Definition;
using Microsoft.Azure.Management.AppService.Fluent.WebAppDiagnosticLogs.Update;
using Microsoft.Azure.Management.AppService.Fluent.WebAppDiagnosticLogs.UpdateDefinition;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Definition;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResourceActions;
/// <summary>
/// Implementation for WebAppDiagnosticLogs and its create and update interfaces.
/// </summary>
/// <typeparam name="FluentT">The fluent interface of the parent web app.</typeparam>
/// <typeparam name="FluentImplT">The fluent implementation of the parent web app.</typeparam>
///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50LmFwcHNlcnZpY2UuaW1wbGVtZW50YXRpb24uV2ViQXBwRGlhZ25vc3RpY0xvZ3NJbXBs
internal partial class WebAppDiagnosticLogsImpl<FluentT, FluentImplT, DefAfterRegionT, DefAfterGroupT, UpdateT> :
IndexableWrapper<Models.SiteLogsConfigInner>,
IWebAppDiagnosticLogs,
WebAppDiagnosticLogs.Definition.IDefinition<IWithCreate<FluentT>>,
IUpdateDefinition<WebAppBase.Update.IUpdate<FluentT>>
where FluentImplT : WebAppBaseImpl<FluentT, FluentImplT, DefAfterRegionT, DefAfterGroupT, UpdateT>, FluentT
where FluentT : class, IWebAppBase
where DefAfterRegionT : class
where DefAfterGroupT : class
where UpdateT : class, WebAppBase.Update.IUpdate<FluentT>
{
private LogLevel applicationLogLevel;
private WebAppBaseImpl<FluentT, FluentImplT, DefAfterRegionT, DefAfterGroupT, UpdateT> parent;
IWebAppBase IHasParent<IWebAppBase>.Parent => parent;
///GENMHASH:A874F3729AB077C5EF390CC63A3F30E2:AEC38C2D7C195C4FA0C12D9DBEC6444C
internal WebAppDiagnosticLogsImpl(SiteLogsConfigInner inner, WebAppBaseImpl<FluentT, FluentImplT, DefAfterRegionT, DefAfterGroupT, UpdateT> parent)
: base(inner)
{
if (inner.ApplicationLogs != null) {
inner.ApplicationLogs.AzureTableStorage = null;
}
this.parent = parent;
}
///GENMHASH:640E49ECE11D905EE9279149E32B0E3C:3FC67826902933894B11C0ADE9F7ED15
public LogLevel ApplicationLoggingFileSystemLogLevel()
{
if (Inner.ApplicationLogs == null
|| Inner.ApplicationLogs.FileSystem == null
|| Inner.ApplicationLogs.FileSystem.Level == null)
{
return LogLevel.Off;
}
else
{
return Inner.ApplicationLogs.FileSystem.Level.Value;
}
}
///GENMHASH:DF1D1F3518E219518D5CF955F655A9B8:00E2D31BD208E82AEA751C6142F22E6E
public string ApplicationLoggingStorageBlobContainer()
{
if (Inner.ApplicationLogs == null || Inner.ApplicationLogs.AzureBlobStorage == null)
{
return null;
}
else
{
return Inner.ApplicationLogs.AzureBlobStorage.SasUrl;
}
}
///GENMHASH:BA212403E436A3A1E0FD9BC3583417BF:C26946CA05312D3FBBCFCCB1B66C16D0
public LogLevel ApplicationLoggingStorageBlobLogLevel()
{
if (Inner.ApplicationLogs == null
|| Inner.ApplicationLogs.AzureBlobStorage == null
|| Inner.ApplicationLogs.AzureBlobStorage.Level == null)
{
return LogLevel.Off;
}
else
{
return Inner.ApplicationLogs.AzureBlobStorage.Level.Value;
}
}
///GENMHASH:138085714A711249FD08A63D789B7168:D88431B6604110BF0C650502C128F8E1
public int ApplicationLoggingStorageBlobRetentionDays()
{
if (Inner.ApplicationLogs == null || Inner.ApplicationLogs.AzureBlobStorage == null || Inner.ApplicationLogs.AzureBlobStorage.RetentionInDays == null)
{
return 0;
}
else
{
return (int) Inner.ApplicationLogs.AzureBlobStorage.RetentionInDays;
}
}
///GENMHASH:077EB7776EFFBFAA141C1696E75EF7B3:FE136D91D26FF654406776A4C5845948
public FluentImplT Attach()
{
return parent.WithDiagnosticLogs(this);
}
///GENMHASH:A6C3024A0F426DA6CF8B71DEF91E0C7E:9FE8762C1B9FACF15AB88DA1BF9597EC
public bool DetailedErrorMessages()
{
return Inner.DetailedErrorMessages != null && Inner.DetailedErrorMessages.Enabled.HasValue && Inner.DetailedErrorMessages.Enabled.Value;
}
///GENMHASH:34AF806990F25131F59A6070440823E0:A95CC561E4445BE3E7269A572A6BFCB2
public bool FailedRequestsTracing()
{
return Inner.FailedRequestsTracing != null && Inner.FailedRequestsTracing.Enabled.HasValue && Inner.FailedRequestsTracing.Enabled.Value;
}
///GENMHASH:ADA7023132C677B8E810845941E988DA:1964CEE67CCBAFF2114B8BBEF6D87DFA
public int WebServerLoggingFileSystemQuotaInMB()
{
if (Inner.HttpLogs == null || Inner.HttpLogs.FileSystem == null || Inner.HttpLogs.FileSystem.RetentionInMb == null)
{
return 0;
}
else
{
return (int) Inner.HttpLogs.FileSystem.RetentionInMb;
}
}
///GENMHASH:067ABA00B1A007275866AF73D61E7EB0:5DF1EA4CDB988A732F7C6C250E93EF80
public int WebServerLoggingFileSystemRetentionDays()
{
if (Inner.HttpLogs == null || Inner.HttpLogs.FileSystem == null || Inner.HttpLogs.FileSystem.RetentionInDays == null)
{
return 0;
}
else
{
return (int) Inner.HttpLogs.FileSystem.RetentionInDays;
}
}
///GENMHASH:4380C0F9DB8F7730F024F27525EABBA9:BDAEE1ED0012E446D0E3908E0C655613
public string WebServerLoggingStorageBlobContainer()
{
if (Inner.HttpLogs == null || Inner.HttpLogs.AzureBlobStorage == null)
{
return null;
}
else
{
return Inner.HttpLogs.AzureBlobStorage.SasUrl;
}
}
///GENMHASH:FF54EEFFDD547C3BAF368E6F2BC0B4D0:8F71A055A516FBEE1E418778C94BFFA0
public int WebServerLoggingStorageBlobRetentionDays()
{
if (Inner.HttpLogs == null || Inner.HttpLogs.AzureBlobStorage == null || Inner.HttpLogs.AzureBlobStorage.RetentionInDays == null)
{
return 0;
}
else
{
return (int) Inner.HttpLogs.AzureBlobStorage.RetentionInDays;
}
}
///GENMHASH:15135C1F5D2CD8350FC2B90B187EDE84:AA0B1A914CB4CA564701FB420E772E27
public WebAppDiagnosticLogsImpl<FluentT, FluentImplT, DefAfterRegionT, DefAfterGroupT, UpdateT> WithApplicationLogging()
{
Inner.ApplicationLogs = new ApplicationLogsConfig();
return this;
}
///GENMHASH:2ECCA6CF80BCF7658A648A571C2F7BF3:B467FF1F87E46050AB4C080D5E257D75
public WebAppDiagnosticLogsImpl<FluentT, FluentImplT, DefAfterRegionT, DefAfterGroupT, UpdateT> WithApplicationLogsStoredOnFileSystem()
{
if (Inner.ApplicationLogs != null)
{
Inner.ApplicationLogs.FileSystem = new FileSystemApplicationLogsConfig
{
Level = applicationLogLevel
};
}
return this;
}
///GENMHASH:2D1384E8FA51443AAA0CBEE56F1F9161:5A0ED936D134ACF180A420BD545A4716
public WebAppDiagnosticLogsImpl<FluentT, FluentImplT, DefAfterRegionT, DefAfterGroupT, UpdateT> WithApplicationLogsStoredOnStorageBlob(string containerSasUrl)
{
if (Inner.ApplicationLogs != null)
{
Inner.ApplicationLogs.AzureBlobStorage = new AzureBlobStorageApplicationLogsConfig
{
Level = applicationLogLevel,
SasUrl = containerSasUrl
};
}
return this;
}
///GENMHASH:9EBAFD920046C4740DBAEA42BD277594:9E7F221B795B1C3152BC026AA660D594
public WebAppDiagnosticLogsImpl<FluentT, FluentImplT, DefAfterRegionT, DefAfterGroupT, UpdateT> WithDetailedErrorMessages(bool enabled)
{
Inner.DetailedErrorMessages = new EnabledConfig
{
Enabled = enabled
};
return this;
}
///GENMHASH:CBAB4BC6DF1639835F4596ACD46F146A:068C62910AA8ACCD48B4BA6F6904041E
public WebAppDiagnosticLogsImpl<FluentT, FluentImplT, DefAfterRegionT, DefAfterGroupT, UpdateT> WithFailedRequestTracing(bool enabled)
{
Inner.FailedRequestsTracing = new EnabledConfig
{
Enabled = enabled
};
return this;
}
///GENMHASH:076D20B8AF8886B0F93ED62AB062F502:5B7EC9967CB8721E32E9BDA41F60BB0C
public WebAppDiagnosticLogsImpl<FluentT, FluentImplT, DefAfterRegionT, DefAfterGroupT, UpdateT> WithLogLevel(LogLevel logLevel)
{
this.applicationLogLevel = logLevel;
return this;
}
///GENMHASH:27B58505EB32F2C2A1069A5602161EB9:31DDB75D31D02F6E8C830CE7A9E778D3
public WebAppDiagnosticLogsImpl<FluentT, FluentImplT, DefAfterRegionT, DefAfterGroupT, UpdateT> WithLogRetentionDays(int retentionDays)
{
if (Inner.HttpLogs != null && Inner.HttpLogs.FileSystem != null && Inner.HttpLogs.FileSystem.Enabled.HasValue && Inner.HttpLogs.FileSystem.Enabled.Value)
{
Inner.HttpLogs.FileSystem.RetentionInDays = retentionDays;
}
if (Inner.HttpLogs != null && Inner.HttpLogs.AzureBlobStorage != null && Inner.HttpLogs.AzureBlobStorage.Enabled.HasValue && Inner.HttpLogs.AzureBlobStorage.Enabled.Value)
{
Inner.HttpLogs.AzureBlobStorage.RetentionInDays = retentionDays;
}
return this;
}
///GENMHASH:452C636B060054B19120D7A982C0649D:52D79141FDEBD298AE8513041D2469F7
public WebAppDiagnosticLogsImpl<FluentT, FluentImplT, DefAfterRegionT, DefAfterGroupT, UpdateT> WithoutApplicationLogging()
{
WithoutApplicationLogsStoredOnFileSystem();
WithoutApplicationLogsStoredOnStorageBlob();
return this;
}
///GENMHASH:C837B719BB763297B65FCAA693E77F40:8C9B01E3467F4A88E6F93FA6BD776EF2
public WebAppDiagnosticLogsImpl<FluentT, FluentImplT, DefAfterRegionT, DefAfterGroupT, UpdateT> WithoutApplicationLogsStoredOnFileSystem()
{
if (Inner.ApplicationLogs != null && Inner.ApplicationLogs.FileSystem != null)
{
Inner.ApplicationLogs.FileSystem.Level = LogLevel.Off;
}
return this;
}
///GENMHASH:C32A2DA398B0223CB3C25743147A346E:4E9B6CB1DA6A4C3D726237EB6101C250
public WebAppDiagnosticLogsImpl<FluentT, FluentImplT, DefAfterRegionT, DefAfterGroupT, UpdateT> WithoutApplicationLogsStoredOnStorageBlob()
{
if (Inner.ApplicationLogs != null && Inner.ApplicationLogs.AzureBlobStorage != null)
{
Inner.ApplicationLogs.AzureBlobStorage.Level = LogLevel.Off;
}
return this;
}
///GENMHASH:59DF92DA011A82A4DC9228B8304644B4:D2F5C9DE85C86DA5508E63A0C377A1E8
public WebAppDiagnosticLogsImpl<FluentT, FluentImplT, DefAfterRegionT, DefAfterGroupT, UpdateT> WithoutWebServerLogging()
{
WithoutWebServerLogsStoredOnFileSystem();
WithoutWebServerLogsStoredOnStorageBlob();
return this;
}
///GENMHASH:E13FA93DDF55EB08430E61891ACC6B9A:D6DC84B0700E4DC053A5C67280BEAC10
public WebAppDiagnosticLogsImpl<FluentT, FluentImplT, DefAfterRegionT, DefAfterGroupT, UpdateT> WithoutWebServerLogsStoredOnFileSystem()
{
if (Inner.HttpLogs != null && Inner.HttpLogs.FileSystem != null)
{
Inner.HttpLogs.FileSystem.Enabled = false;
}
return this;
}
///GENMHASH:CF3F55940F39CAC85C5BE54BDBF115CE:CF7750415ED20DECE355690C74FBB95D
public WebAppDiagnosticLogsImpl<FluentT, FluentImplT, DefAfterRegionT, DefAfterGroupT, UpdateT> WithoutWebServerLogsStoredOnStorageBlob()
{
if (Inner.HttpLogs != null && Inner.HttpLogs.AzureBlobStorage != null)
{
Inner.HttpLogs.AzureBlobStorage.Enabled = true;
}
return this;
}
///GENMHASH:0AA703FD4D7171D9DD761057420590D4:57E8D27F0D0112D8FDF8632C55262083
public WebAppDiagnosticLogsImpl<FluentT, FluentImplT, DefAfterRegionT, DefAfterGroupT, UpdateT> WithUnlimitedLogRetentionDays()
{
if (Inner.HttpLogs != null && Inner.HttpLogs.FileSystem != null && Inner.HttpLogs.FileSystem.Enabled.HasValue && Inner.HttpLogs.FileSystem.Enabled.Value)
{
Inner.HttpLogs.FileSystem.RetentionInDays = 0;
}
if (Inner.HttpLogs != null && Inner.HttpLogs.AzureBlobStorage != null && Inner.HttpLogs.FileSystem.Enabled.HasValue && Inner.HttpLogs.FileSystem.Enabled.Value)
{
Inner.HttpLogs.AzureBlobStorage.RetentionInDays = 0;
}
return this;
}
///GENMHASH:6779E4B38BCBB810944CA68774B310C3:072E24F1A9FC72304BBE1ED245652D70
public WebAppDiagnosticLogsImpl<FluentT, FluentImplT, DefAfterRegionT, DefAfterGroupT, UpdateT> WithWebServerFileSystemQuotaInMB(int quotaInMB)
{
if (Inner.HttpLogs != null && Inner.HttpLogs.FileSystem != null && Inner.HttpLogs.FileSystem.Enabled.HasValue && Inner.HttpLogs.FileSystem.Enabled.Value)
{
Inner.HttpLogs.FileSystem.RetentionInMb = quotaInMB;
}
return this;
}
///GENMHASH:7CF59D3DACD72ACA92253758D23178BA:6A3A214E822090F293BA8EB6EA24B70D
public WebAppDiagnosticLogsImpl<FluentT, FluentImplT, DefAfterRegionT, DefAfterGroupT, UpdateT> WithWebServerLogging()
{
Inner.HttpLogs = new HttpLogsConfig();
return this;
}
///GENMHASH:ECADC1490C060E360662B47F64D697D7:39A92D1755BC701B4187BAC4466E663A
public WebAppDiagnosticLogsImpl<FluentT, FluentImplT, DefAfterRegionT, DefAfterGroupT, UpdateT> WithWebServerLogsStoredOnFileSystem()
{
if (Inner.HttpLogs != null)
{
Inner.HttpLogs.FileSystem = new FileSystemHttpLogsConfig
{
Enabled = true
};
}
return this;
}
///GENMHASH:275EB20CC4AF95A4E8E3E4AC00B5944A:1DD740D5F021AFB813284B33709A769C
public WebAppDiagnosticLogsImpl<FluentT, FluentImplT, DefAfterRegionT, DefAfterGroupT, UpdateT> WithWebServerLogsStoredOnStorageBlob(string containerSasUrl)
{
if (Inner.HttpLogs != null)
{
Inner.HttpLogs.AzureBlobStorage =
new AzureBlobStorageHttpLogsConfig
{
Enabled = true,
SasUrl = containerSasUrl
};
}
return this;
}
}
}
| |
#region Header
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Copyright (c) 2007-2008 James Nies and NArrange contributors.
* All rights reserved.
*
* This program and the accompanying materials are made available under
* the terms of the Common Public License v1.0 which accompanies this
* distribution.
*
* 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
* 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.
*
*<author>James Nies</author>
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
#endregion Header
namespace NArrange.Core.CodeElements
{
using System;
using System.IO;
using System.Text;
using NArrange.Core.Configuration;
/// <summary>
/// Element utility methods.
/// </summary>
public static class ElementUtilities
{
#region Methods
/// <summary>
/// Gets a string representation of a code element using the specified
/// format.
/// </summary>
/// <param name="format">The format.</param>
/// <param name="codeElement">The code element.</param>
/// <returns>Formatted string representation of the code element.</returns>
public static string Format(string format, ICodeElement codeElement)
{
if (format == null)
{
throw new ArgumentNullException("format");
}
else if (codeElement == null)
{
throw new ArgumentNullException("codeElement");
}
StringBuilder formatted = new StringBuilder(format.Length * 2);
StringBuilder attributeBuilder = null;
bool inAttribute = false;
using (StringReader reader = new StringReader(format))
{
int data = reader.Read();
while (data > 0)
{
char ch = (char)data;
if (ch == ConditionExpressionParser.ExpressionPrefix &&
(char)(reader.Peek()) == ConditionExpressionParser.ExpressionStart)
{
reader.Read();
attributeBuilder = new StringBuilder(16);
inAttribute = true;
}
else if (inAttribute)
{
if (ch == ConditionExpressionParser.ExpressionEnd)
{
ElementAttributeType elementAttribute = (ElementAttributeType)Enum.Parse(
typeof(ElementAttributeType), attributeBuilder.ToString());
string attribute = GetAttribute(elementAttribute, codeElement);
formatted.Append(attribute);
attributeBuilder = new StringBuilder(16);
inAttribute = false;
}
else
{
attributeBuilder.Append(ch);
}
}
else
{
formatted.Append(ch);
}
data = reader.Read();
}
}
return formatted.ToString();
}
/// <summary>
/// Gets the string representation of a code element attribute.
/// </summary>
/// <param name="attributeType">Type of the attribute.</param>
/// <param name="codeElement">The code element.</param>
/// <returns>The code element attribute as text.</returns>
public static string GetAttribute(ElementAttributeType attributeType, ICodeElement codeElement)
{
string attributeString = null;
MemberElement memberElement;
TypeElement typeElement;
if (codeElement != null)
{
switch (attributeType)
{
case ElementAttributeType.Name:
attributeString = codeElement.Name;
break;
case ElementAttributeType.Access:
AttributedElement attributedElement = codeElement as AttributedElement;
if (attributedElement != null)
{
attributeString = EnumUtilities.ToString(attributedElement.Access);
}
break;
case ElementAttributeType.ElementType:
attributeString = EnumUtilities.ToString(codeElement.ElementType);
break;
case ElementAttributeType.Type:
attributeString = GetTypeAttribute(codeElement);
break;
case ElementAttributeType.Attributes:
attributeString = GetAttributesAttribute(codeElement);
break;
case ElementAttributeType.Modifier:
memberElement = codeElement as MemberElement;
if (memberElement != null)
{
attributeString = EnumUtilities.ToString(memberElement.MemberModifiers);
}
else
{
typeElement = codeElement as TypeElement;
if (typeElement != null)
{
attributeString = EnumUtilities.ToString(typeElement.TypeModifiers);
}
}
break;
default:
attributeString = string.Empty;
break;
}
}
if (attributeString == null)
{
attributeString = string.Empty;
}
return attributeString;
}
/// <summary>
/// Processes each element in a code element tree.
/// </summary>
/// <param name="codeElement">Code element to process.</param>
/// <param name="action">Action that performs processing.</param>
public static void ProcessElementTree(ICodeElement codeElement, Action<ICodeElement> action)
{
if (codeElement != null)
{
action(codeElement);
foreach (ICodeElement childElement in codeElement.Children)
{
ProcessElementTree(childElement, action);
}
}
}
/// <summary>
/// Gets the Attributes attribute.
/// </summary>
/// <param name="codeElement">The code element.</param>
/// <returns>Attributes as a comma-separated list.</returns>
private static string GetAttributesAttribute(ICodeElement codeElement)
{
StringBuilder attributesBuilder = new StringBuilder();
AttributedElement attributedElement = codeElement as AttributedElement;
if (attributedElement != null)
{
for (int attributeIndex = 0; attributeIndex < attributedElement.Attributes.Count; attributeIndex++)
{
IAttributeElement attribute = attributedElement.Attributes[attributeIndex];
attributesBuilder.Append(attribute.Name);
foreach (ICodeElement attributeChild in attribute.Children)
{
IAttributeElement childAttributeElement = attributeChild as IAttributeElement;
if (childAttributeElement != null)
{
attributesBuilder.Append(", ");
attributesBuilder.Append(childAttributeElement.Name);
}
}
if (attributeIndex < attributedElement.Attributes.Count - 1)
{
attributesBuilder.Append(", ");
}
}
}
return attributesBuilder.ToString();
}
/// <summary>
/// Gets the type attribute.
/// </summary>
/// <param name="codeElement">The code element.</param>
/// <returns>The type attibute as text.</returns>
private static string GetTypeAttribute(ICodeElement codeElement)
{
string attributeString = string.Empty;
MemberElement memberElement = codeElement as MemberElement;
if (memberElement != null)
{
attributeString = memberElement.Type;
}
else
{
switch (codeElement.ElementType)
{
case ElementType.Type:
attributeString = EnumUtilities.ToString(((TypeElement)codeElement).Type);
break;
case ElementType.Comment:
attributeString = EnumUtilities.ToString(((CommentElement)codeElement).Type);
break;
case ElementType.Using:
attributeString = EnumUtilities.ToString(((UsingElement)codeElement).Type);
break;
}
}
return attributeString;
}
#endregion Methods
}
}
| |
// 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 ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.dlgatecontravar2.dlgatecontravar2
{
// <Area>variance</Area>
// <Title> Basic Error Contravariance on delegates</Title>
// <Description> basic errorcontravariance on delegates - Incorrect type mismatch</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success></Expects>
// <Code>
//<Expects Status=warning>\(42,37\).*CS0168</Expects>
//<Expects Status=warning>\(53,26\).*CS0168</Expects>
using System;
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
public delegate void Foo<in T>(T t);
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
int result = 0;
bool ret = true;
dynamic f11 = (Foo<Tiger>)((Tiger a) =>
{
}
);
try
{
Foo<Animal> f12 = f11;
result++;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
ret = ErrorVerifier.Verify(ErrorMessageId.NoImplicitConvCast, e.Message, "C.Foo<Tiger>", "C.Foo<Animal>");
if (ret == false)
result++;
}
Foo<Tiger> f21 = (Tiger a) =>
{
}
;
try
{
dynamic f22 = (Foo<Animal>)f21;
result++;
}
catch (InvalidCastException e)
{
}
dynamic f31 = (Foo<Tiger>)((Tiger a) =>
{
}
);
try
{
dynamic f32 = (Foo<Animal>)f31;
result++;
}
catch (Exception e)
{
}
return result;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.dlgateconvar.dlgateconvar
{
// <Area>variance</Area>
// <Title> Basic Contravariance on delegates</Title>
// <Description> basic contravariance on delegates </Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
public delegate void Foo<in T>(T t);
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic f11 = (Foo<Animal>)((Animal a) =>
{
}
);
Foo<Tiger> f12 = (Foo<Tiger>)f11;
f12(new Tiger());
Foo<Animal> f21 = (Animal a) =>
{
}
;
dynamic f22 = (Foo<Tiger>)f21;
f22(new Tiger());
dynamic f31 = (Foo<Animal>)((Animal a) =>
{
}
);
dynamic f32 = (Foo<Tiger>)f31;
f32(new Tiger());
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.dlgatecov.dlgatecov
{
// <Area>variance</Area>
// <Title> Basic covariance on delegate types </Title>
// <Description> Having a covariant delegate and assigning it to a bigger type</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
public delegate T Foo<out T>();
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic f11 = (Foo<Tiger>)(() =>
{
return new Tiger();
}
);
Foo<Animal> f12 = f11;
Animal t1 = f12();
Foo<Tiger> f21 = () =>
{
return new Tiger();
}
;
dynamic f22 = (Foo<Animal>)f21;
Animal t2 = f22();
dynamic f31 = (Foo<Tiger>)(() =>
{
return new Tiger();
}
);
dynamic f32 = (Foo<Animal>)f31;
Animal t3 = f32();
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.dlgatecovar2.dlgatecovar2
{
// <Area>variance</Area>
// <Title> Error- Basic covariance on delegate types </Title>
// <Description> Having a covariant delegate and assigning it to a bigger type, incorrect types</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success></Expects>
// <Code>
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
public delegate T Foo<out T>();
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
int result = 0;
bool ret = true;
dynamic f11 = (Foo<Animal>)(() =>
{
return new Tiger();
}
);
try
{
result++;
Foo<Tiger> f12 = f11;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
result--;
ret = ErrorVerifier.Verify(ErrorMessageId.NoImplicitConvCast, ex.Message, "C.Foo<Animal>", "C.Foo<Tiger>");
if (!ret)
result++;
}
Foo<Animal> f21 = () =>
{
return new Tiger();
}
;
try
{
result++;
dynamic f22 = (Foo<Tiger>)f21;
}
catch (System.InvalidCastException)
{
result--;
}
dynamic f31 = (Foo<Animal>)(() =>
{
return new Tiger();
}
);
try
{
result++;
dynamic f32 = (Foo<Tiger>)f31;
}
catch (System.InvalidCastException)
{
result--;
}
return result;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.integeregererfacecontravar2.integeregererfacecontravar2
{
// <Area>variance</Area>
// <Title> Basic error contravariance on interfaces</Title>
// <Description> basic error contravariance on interfaces - wrong type assignments </Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success></Expects>
// <Code>
public interface iVariance<in T>
{
void Boo(T t);
}
public class Variance<T> : iVariance<T>
{
public void Boo(T t)
{
}
}
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
int count = 0;
int result = 0;
dynamic v11 = new Variance<Tiger>();
try
{
result++;
iVariance<Animal> v12 = v11;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
bool ret = ErrorVerifier.Verify(ErrorMessageId.NoImplicitConvCast, ex.Message, "Variance<Tiger>", "iVariance<Animal>");
if (ret)
{
result--;
}
}
Variance<Tiger> v21 = new Variance<Tiger>();
try
{
result++;
dynamic v22 = (iVariance<Animal>)v21;
}
catch (System.InvalidCastException)
{
result--;
}
Variance<Tiger> v31 = new Variance<Tiger>();
try
{
result++;
dynamic v32 = (iVariance<Animal>)v31;
}
catch (System.InvalidCastException)
{
result--;
}
return result;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.integeregererfaceconvar.integeregererfaceconvar
{
// <Area>variance</Area>
// <Title> Basic contravariance on interfaces</Title>
// <Description> basic contravariance on interfaces </Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public interface iVariance<in T>
{
void Boo(T t);
}
public class Variance<T> : iVariance<T>
{
public void Boo(T t)
{
}
}
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic v11 = new Variance<Animal>();
iVariance<Tiger> v12 = v11;
v12.Boo(new Tiger());
Variance<Animal> v21 = new Variance<Animal>();
dynamic v22 = (iVariance<Tiger>)v21;
v22.Boo(new Tiger());
Variance<Animal> v31 = new Variance<Animal>();
dynamic v32 = (iVariance<Tiger>)v31;
v32.Boo(new Tiger());
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.integeregererfacecovar2.integeregererfacecovar2
{
// <Area>variance</Area>
// <Title> Basic error covariance on interfaces</Title>
// <Description> basic error coavariance on interfaces - type mismatch</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success></Expects>
// <Code>
public interface iVariance<out T>
{
T Boo();
}
public class Variance<T> : iVariance<T> where T : new()
{
public T Boo()
{
return new T();
}
}
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
int result = 0;
dynamic v11 = new Variance<Animal>();
try
{
result++;
iVariance<Tiger> v12 = v11;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
bool ret = ErrorVerifier.Verify(ErrorMessageId.NoImplicitConvCast, ex.Message, "Variance<Animal>", "iVariance<Tiger>");
if (ret)
{
result--;
}
}
Variance<Animal> v21 = new Variance<Animal>();
try
{
result++;
dynamic v22 = (iVariance<Tiger>)v21;
}
catch (System.InvalidCastException)
{
result--;
}
dynamic v31 = new Variance<Animal>();
try
{
result++;
dynamic v32 = (iVariance<Tiger>)v31;
}
catch (System.InvalidCastException)
{
result--;
}
return result;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.integeregererfacecovar.integeregererfacecovar
{
// <Area>variance</Area>
// <Title> Basic covariance on interfaces</Title>
// <Description> basic coavariance on interfaces </Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success></Expects>
// <Code>
public interface iVariance<out T>
{
T Boo();
}
public class Variance<T> : iVariance<T> where T : new()
{
public T Boo()
{
return new T();
}
}
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Variance<Tiger> v11 = new Variance<Tiger>();
iVariance<Animal> v12 = v11;
var x1 = v12.Boo();
dynamic v21 = new Variance<Tiger>();
iVariance<Animal> v22 = v21;
var x2 = v22.Boo();
dynamic v31 = new Variance<Tiger>();
dynamic v32 = (iVariance<Animal>)v31;
var x3 = v32.Boo();
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.dlgatecontravar4.dlgatecontravar4
{
// <Area>variance</Area>
// <Title> Basic Error Contravariance on delegates</Title>
// <Description> basic errorcontravariance on delegates - Incorrect type mismatch</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success></Expects>
// <Code>
//<Expects Status=warning>\(40,37\).*CS0168</Expects>
//<Expects Status=warning>\(51,37\).*CS0168</Expects>
using System;
public class C
{
public delegate void Foo<in T>(T t);
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
int result = 0;
bool ret = true;
dynamic f11 = (Foo<string>)((string a) =>
{
}
);
try
{
Foo<dynamic> f12 = f11;
result++;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
ret = ErrorVerifier.Verify(ErrorMessageId.NoImplicitConvCast, e.Message, "C.Foo<string>", "C.Foo<object>");
if (!ret)
result++;
}
Foo<string> f21 = (string a) =>
{
}
;
try
{
dynamic f22 = (Foo<dynamic>)f21;
result++;
}
catch (InvalidCastException e)
{
}
dynamic f31 = (Foo<string>)((string a) =>
{
}
);
try
{
dynamic f32 = (Foo<dynamic>)f31;
result++;
}
catch (InvalidCastException e)
{
}
return result;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.dlgateconvar3.dlgateconvar3
{
// <Area>variance</Area>
// <Title> Basic Contravariance on delegates</Title>
// <Description> basic contravariance on delegates </Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public class C
{
public delegate void Foo<in T>(T t);
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic f11 = (Foo<dynamic>)((dynamic a) =>
{
}
);
Foo<string> f12 = (Foo<string>)f11;
f12(string.Empty);
Foo<dynamic> f21 = (dynamic a) =>
{
}
;
dynamic f22 = (Foo<string>)f21;
f22(null);
dynamic f31 = (Foo<dynamic>)((dynamic a) =>
{
}
);
dynamic f32 = (Foo<string>)f31;
f32("ABC");
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.dlgatecov3.dlgatecov3
{
// <Area>variance</Area>
// <Title> Basic covariance on delegate types </Title>
// <Description> Having a covariant delegate and assigning it to a bigger type</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public class C
{
public delegate T Foo<out T>();
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic f11 = (Foo<string>)(() =>
{
return null;
}
);
Foo<dynamic> f12 = f11;
dynamic t1 = f12();
Foo<string> f21 = () =>
{
return string.Empty;
}
;
dynamic f22 = (Foo<dynamic>)f21;
dynamic t2 = f22();
dynamic f31 = (Foo<string>)(() =>
{
return "ABC";
}
);
dynamic f32 = (Foo<dynamic>)f31;
dynamic t3 = f32();
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.dlgatecovar4.dlgatecovar4
{
// <Area>variance</Area>
// <Title> Error- Basic covariance on delegate types </Title>
// <Description> Having a covariant delegate and assigning it to a bigger type, incorrect types</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success></Expects>
// <Code>
public class C
{
public delegate T Foo<out T>();
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
int result = 0;
bool ret = true;
dynamic f11 = (Foo<dynamic>)(() =>
{
return 10;
}
);
try
{
result++;
Foo<C> f12 = f11;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
result--;
ret = ErrorVerifier.Verify(ErrorMessageId.NoImplicitConvCast, ex.Message, "C.Foo<object>", "C.Foo<C>");
if (!ret)
result++;
}
Foo<dynamic> f21 = () =>
{
return 10;
}
;
try
{
result++;
dynamic f22 = (Foo<C>)f21;
}
catch (System.InvalidCastException)
{
result--;
}
dynamic f31 = (Foo<dynamic>)(() =>
{
return 10;
}
);
try
{
result++;
dynamic f32 = (Foo<C>)f31;
}
catch (System.InvalidCastException)
{
result--;
}
return result;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.integeregererfacecontravar4.integeregererfacecontravar4
{
// <Area>variance</Area>
// <Title> Basic error contravariance on interfaces</Title>
// <Description> basic error contravariance on interfaces - wrong type assignments </Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success></Expects>
// <Code>
public interface iVariance<in T>
{
void Boo(T t);
}
public class Variance<T> : iVariance<T>
{
public void Boo(T t)
{
}
}
public class C
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
int result = 0;
dynamic v11 = new Variance<string>();
try
{
result++;
iVariance<dynamic> v12 = v11;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
bool ret = ErrorVerifier.Verify(ErrorMessageId.NoImplicitConvCast, ex.Message, "Variance<string>", "iVariance<object>");
if (ret)
{
result--;
}
}
Variance<string> v21 = new Variance<string>();
try
{
result++;
dynamic v22 = (iVariance<dynamic>)v21;
}
catch (System.InvalidCastException)
{
result--;
}
Variance<string> v31 = new Variance<string>();
try
{
result++;
dynamic v32 = (iVariance<dynamic>)v31;
}
catch (System.InvalidCastException)
{
result--;
}
return result;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.integeregererfaceconvar3.integeregererfaceconvar3
{
// <Area>variance</Area>
// <Title> Basic contravariance on interfaces</Title>
// <Description> basic contravariance on interfaces </Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public interface iVariance<in T>
{
void Boo(T t);
}
public class Variance<T> : iVariance<T>
{
public void Boo(T t)
{
}
}
public class C
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic v11 = new Variance<dynamic>();
iVariance<string> v12 = v11;
v12.Boo(string.Empty);
Variance<dynamic> v21 = new Variance<dynamic>();
dynamic v22 = (iVariance<string>)v21;
v22.Boo(null);
Variance<dynamic> v31 = new Variance<dynamic>();
dynamic v32 = (iVariance<string>)v31;
v32.Boo("ABC");
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.integeregererfacecovar4.integeregererfacecovar4
{
// <Area>variance</Area>
// <Title> Basic error covariance on interfaces</Title>
// <Description> basic error coavariance on interfaces - type mismatch</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success></Expects>
// <Code>
public interface iVariance<out T>
{
T Boo();
}
public class Variance<T> : iVariance<T> where T : new()
{
public T Boo()
{
return new T();
}
}
public class C
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
int result = 0;
dynamic v11 = new Variance<object>();
try
{
result++;
iVariance<C> v12 = v11;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
bool ret = ErrorVerifier.Verify(ErrorMessageId.NoImplicitConvCast, ex.Message, "Variance<object>", "iVariance<C>");
if (ret)
{
result--;
}
}
Variance<object> v21 = new Variance<object>();
try
{
result++;
dynamic v22 = (iVariance<C>)v21;
}
catch (System.InvalidCastException)
{
result--;
}
dynamic v31 = new Variance<object>();
try
{
result++;
dynamic v32 = (iVariance<C>)v31;
}
catch (System.InvalidCastException)
{
result--;
}
return result;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.integeregererfacecovar3.integeregererfacecovar3
{
// <Area>variance</Area>
// <Title> Basic covariance on interfaces</Title>
// <Description> basic coavariance on interfaces </Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success></Expects>
// <Code>
public interface iVariance<out T>
{
T Boo();
}
public class Variance<T> : iVariance<T> where T : new()
{
public T Boo()
{
return new T();
}
}
public class C
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Variance<C> v11 = new Variance<C>();
iVariance<dynamic> v12 = v11;
var x1 = v12.Boo();
dynamic v21 = new Variance<C>();
iVariance<dynamic> v22 = v21;
var x2 = v22.Boo();
dynamic v31 = new Variance<C>();
dynamic v32 = (iVariance<dynamic>)v31;
var x3 = v32.Boo();
return 0;
}
}
//</Code>
}
| |
// Generated by ProtoGen, Version=2.4.1.555, Culture=neutral, PublicKeyToken=55f7125234beb589. DO NOT EDIT!
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.ProtocolBuffers;
using pbc = global::Google.ProtocolBuffers.Collections;
using pbd = global::Google.ProtocolBuffers.Descriptors;
using scg = global::System.Collections.Generic;
namespace Google.ProtocolBuffers.TestProtos {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class UnitTestExtrasProtoFile {
#region Extension registration
public static void RegisterAllExtensions(pb::ExtensionRegistry registry) {
registry.Add(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedInt32Extension);
registry.Add(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedInt64Extension);
registry.Add(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedUint32Extension);
registry.Add(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedUint64Extension);
registry.Add(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedSint32Extension);
registry.Add(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedSint64Extension);
registry.Add(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedFixed32Extension);
registry.Add(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedFixed64Extension);
registry.Add(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedSfixed32Extension);
registry.Add(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedSfixed64Extension);
registry.Add(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedFloatExtension);
registry.Add(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedDoubleExtension);
registry.Add(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedBoolExtension);
registry.Add(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedEnumExtension);
}
#endregion
#region Extensions
public const int UnpackedInt32ExtensionFieldNumber = 90;
public static pb::GeneratedExtensionBase<scg::IList<int>> UnpackedInt32Extension;
public const int UnpackedInt64ExtensionFieldNumber = 91;
public static pb::GeneratedExtensionBase<scg::IList<long>> UnpackedInt64Extension;
public const int UnpackedUint32ExtensionFieldNumber = 92;
[global::System.CLSCompliant(false)]
public static pb::GeneratedExtensionBase<scg::IList<uint>> UnpackedUint32Extension;
public const int UnpackedUint64ExtensionFieldNumber = 93;
[global::System.CLSCompliant(false)]
public static pb::GeneratedExtensionBase<scg::IList<ulong>> UnpackedUint64Extension;
public const int UnpackedSint32ExtensionFieldNumber = 94;
public static pb::GeneratedExtensionBase<scg::IList<int>> UnpackedSint32Extension;
public const int UnpackedSint64ExtensionFieldNumber = 95;
public static pb::GeneratedExtensionBase<scg::IList<long>> UnpackedSint64Extension;
public const int UnpackedFixed32ExtensionFieldNumber = 96;
[global::System.CLSCompliant(false)]
public static pb::GeneratedExtensionBase<scg::IList<uint>> UnpackedFixed32Extension;
public const int UnpackedFixed64ExtensionFieldNumber = 97;
[global::System.CLSCompliant(false)]
public static pb::GeneratedExtensionBase<scg::IList<ulong>> UnpackedFixed64Extension;
public const int UnpackedSfixed32ExtensionFieldNumber = 98;
public static pb::GeneratedExtensionBase<scg::IList<int>> UnpackedSfixed32Extension;
public const int UnpackedSfixed64ExtensionFieldNumber = 99;
public static pb::GeneratedExtensionBase<scg::IList<long>> UnpackedSfixed64Extension;
public const int UnpackedFloatExtensionFieldNumber = 100;
public static pb::GeneratedExtensionBase<scg::IList<float>> UnpackedFloatExtension;
public const int UnpackedDoubleExtensionFieldNumber = 101;
public static pb::GeneratedExtensionBase<scg::IList<double>> UnpackedDoubleExtension;
public const int UnpackedBoolExtensionFieldNumber = 102;
public static pb::GeneratedExtensionBase<scg::IList<bool>> UnpackedBoolExtension;
public const int UnpackedEnumExtensionFieldNumber = 103;
public static pb::GeneratedExtensionBase<scg::IList<global::Google.ProtocolBuffers.TestProtos.UnpackedExtensionsForeignEnum>> UnpackedEnumExtension;
#endregion
#region Static variables
internal static pbd::MessageDescriptor internal__static_protobuf_unittest_extra_TestUnpackedExtensions__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.TestUnpackedExtensions, global::Google.ProtocolBuffers.TestProtos.TestUnpackedExtensions.Builder> internal__static_protobuf_unittest_extra_TestUnpackedExtensions__FieldAccessorTable;
#endregion
#region Descriptor
public static pbd::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbd::FileDescriptor descriptor;
static UnitTestExtrasProtoFile() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"ChxleHRlc3QvdW5pdHRlc3RfZXh0cmFzLnByb3RvEhdwcm90b2J1Zl91bml0",
"dGVzdF9leHRyYRokZ29vZ2xlL3Byb3RvYnVmL2NzaGFycF9vcHRpb25zLnBy",
"b3RvIiIKFlRlc3RVbnBhY2tlZEV4dGVuc2lvbnMqCAgBEICAgIACKlIKHVVu",
"cGFja2VkRXh0ZW5zaW9uc0ZvcmVpZ25FbnVtEg8KC0ZPUkVJR05fRk9PEAQS",
"DwoLRk9SRUlHTl9CQVIQBRIPCgtGT1JFSUdOX0JBWhAGOlEKGHVucGFja2Vk",
"X2ludDMyX2V4dGVuc2lvbhIvLnByb3RvYnVmX3VuaXR0ZXN0X2V4dHJhLlRl",
"c3RVbnBhY2tlZEV4dGVuc2lvbnMYWiADKAU6UQoYdW5wYWNrZWRfaW50NjRf",
"ZXh0ZW5zaW9uEi8ucHJvdG9idWZfdW5pdHRlc3RfZXh0cmEuVGVzdFVucGFj",
"a2VkRXh0ZW5zaW9ucxhbIAMoAzpSChl1bnBhY2tlZF91aW50MzJfZXh0ZW5z",
"aW9uEi8ucHJvdG9idWZfdW5pdHRlc3RfZXh0cmEuVGVzdFVucGFja2VkRXh0",
"ZW5zaW9ucxhcIAMoDTpSChl1bnBhY2tlZF91aW50NjRfZXh0ZW5zaW9uEi8u",
"cHJvdG9idWZfdW5pdHRlc3RfZXh0cmEuVGVzdFVucGFja2VkRXh0ZW5zaW9u",
"cxhdIAMoBDpSChl1bnBhY2tlZF9zaW50MzJfZXh0ZW5zaW9uEi8ucHJvdG9i",
"dWZfdW5pdHRlc3RfZXh0cmEuVGVzdFVucGFja2VkRXh0ZW5zaW9ucxheIAMo",
"ETpSChl1bnBhY2tlZF9zaW50NjRfZXh0ZW5zaW9uEi8ucHJvdG9idWZfdW5p",
"dHRlc3RfZXh0cmEuVGVzdFVucGFja2VkRXh0ZW5zaW9ucxhfIAMoEjpTChp1",
"bnBhY2tlZF9maXhlZDMyX2V4dGVuc2lvbhIvLnByb3RvYnVmX3VuaXR0ZXN0",
"X2V4dHJhLlRlc3RVbnBhY2tlZEV4dGVuc2lvbnMYYCADKAc6UwoadW5wYWNr",
"ZWRfZml4ZWQ2NF9leHRlbnNpb24SLy5wcm90b2J1Zl91bml0dGVzdF9leHRy",
"YS5UZXN0VW5wYWNrZWRFeHRlbnNpb25zGGEgAygGOlQKG3VucGFja2VkX3Nm",
"aXhlZDMyX2V4dGVuc2lvbhIvLnByb3RvYnVmX3VuaXR0ZXN0X2V4dHJhLlRl",
"c3RVbnBhY2tlZEV4dGVuc2lvbnMYYiADKA86VAobdW5wYWNrZWRfc2ZpeGVk",
"NjRfZXh0ZW5zaW9uEi8ucHJvdG9idWZfdW5pdHRlc3RfZXh0cmEuVGVzdFVu",
"cGFja2VkRXh0ZW5zaW9ucxhjIAMoEDpRChh1bnBhY2tlZF9mbG9hdF9leHRl",
"bnNpb24SLy5wcm90b2J1Zl91bml0dGVzdF9leHRyYS5UZXN0VW5wYWNrZWRF",
"eHRlbnNpb25zGGQgAygCOlIKGXVucGFja2VkX2RvdWJsZV9leHRlbnNpb24S",
"Ly5wcm90b2J1Zl91bml0dGVzdF9leHRyYS5UZXN0VW5wYWNrZWRFeHRlbnNp",
"b25zGGUgAygBOlAKF3VucGFja2VkX2Jvb2xfZXh0ZW5zaW9uEi8ucHJvdG9i",
"dWZfdW5pdHRlc3RfZXh0cmEuVGVzdFVucGFja2VkRXh0ZW5zaW9ucxhmIAMo",
"CDqIAQoXdW5wYWNrZWRfZW51bV9leHRlbnNpb24SLy5wcm90b2J1Zl91bml0",
"dGVzdF9leHRyYS5UZXN0VW5wYWNrZWRFeHRlbnNpb25zGGcgAygOMjYucHJv",
"dG9idWZfdW5pdHRlc3RfZXh0cmEuVW5wYWNrZWRFeHRlbnNpb25zRm9yZWln",
"bkVudW1CVgoTY29tLmdvb2dsZS5wcm90b2J1ZsI+PgohR29vZ2xlLlByb3Rv",
"Y29sQnVmZmVycy5UZXN0UHJvdG9zEhdVbml0VGVzdEV4dHJhc1Byb3RvRmls",
"ZUgB"));
pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) {
descriptor = root;
internal__static_protobuf_unittest_extra_TestUnpackedExtensions__Descriptor = Descriptor.MessageTypes[0];
internal__static_protobuf_unittest_extra_TestUnpackedExtensions__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.TestUnpackedExtensions, global::Google.ProtocolBuffers.TestProtos.TestUnpackedExtensions.Builder>(internal__static_protobuf_unittest_extra_TestUnpackedExtensions__Descriptor,
new string[] { });
global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedInt32Extension = pb::GeneratedRepeatExtension<int>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.Descriptor.Extensions[0]);
global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedInt64Extension = pb::GeneratedRepeatExtension<long>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.Descriptor.Extensions[1]);
global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedUint32Extension = pb::GeneratedRepeatExtension<uint>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.Descriptor.Extensions[2]);
global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedUint64Extension = pb::GeneratedRepeatExtension<ulong>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.Descriptor.Extensions[3]);
global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedSint32Extension = pb::GeneratedRepeatExtension<int>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.Descriptor.Extensions[4]);
global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedSint64Extension = pb::GeneratedRepeatExtension<long>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.Descriptor.Extensions[5]);
global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedFixed32Extension = pb::GeneratedRepeatExtension<uint>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.Descriptor.Extensions[6]);
global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedFixed64Extension = pb::GeneratedRepeatExtension<ulong>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.Descriptor.Extensions[7]);
global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedSfixed32Extension = pb::GeneratedRepeatExtension<int>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.Descriptor.Extensions[8]);
global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedSfixed64Extension = pb::GeneratedRepeatExtension<long>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.Descriptor.Extensions[9]);
global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedFloatExtension = pb::GeneratedRepeatExtension<float>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.Descriptor.Extensions[10]);
global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedDoubleExtension = pb::GeneratedRepeatExtension<double>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.Descriptor.Extensions[11]);
global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedBoolExtension = pb::GeneratedRepeatExtension<bool>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.Descriptor.Extensions[12]);
global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.UnpackedEnumExtension = pb::GeneratedRepeatExtension<global::Google.ProtocolBuffers.TestProtos.UnpackedExtensionsForeignEnum>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.Descriptor.Extensions[13]);
pb::ExtensionRegistry registry = pb::ExtensionRegistry.CreateInstance();
RegisterAllExtensions(registry);
global::Google.ProtocolBuffers.DescriptorProtos.CSharpOptions.RegisterAllExtensions(registry);
return registry;
};
pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbd::FileDescriptor[] {
global::Google.ProtocolBuffers.DescriptorProtos.CSharpOptions.Descriptor,
}, assigner);
}
#endregion
}
#region Enums
public enum UnpackedExtensionsForeignEnum {
FOREIGN_FOO = 4,
FOREIGN_BAR = 5,
FOREIGN_BAZ = 6,
}
#endregion
#region Messages
[global::System.SerializableAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class TestUnpackedExtensions : pb::ExtendableMessage<TestUnpackedExtensions, TestUnpackedExtensions.Builder> {
private TestUnpackedExtensions() { }
private static readonly TestUnpackedExtensions defaultInstance = new TestUnpackedExtensions().MakeReadOnly();
private static readonly string[] _testUnpackedExtensionsFieldNames = new string[] { };
private static readonly uint[] _testUnpackedExtensionsFieldTags = new uint[] { };
public static TestUnpackedExtensions DefaultInstance {
get { return defaultInstance; }
}
public override TestUnpackedExtensions DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override TestUnpackedExtensions ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.internal__static_protobuf_unittest_extra_TestUnpackedExtensions__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<TestUnpackedExtensions, TestUnpackedExtensions.Builder> InternalFieldAccessors {
get { return global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.internal__static_protobuf_unittest_extra_TestUnpackedExtensions__FieldAccessorTable; }
}
public override bool IsInitialized {
get {
if (!ExtensionsAreInitialized) return false;
return true;
}
}
public override void WriteTo(pb::ICodedOutputStream output) {
CalcSerializedSize();
string[] field_names = _testUnpackedExtensionsFieldNames;
pb::ExtendableMessage<TestUnpackedExtensions, TestUnpackedExtensions.Builder>.ExtensionWriter extensionWriter = CreateExtensionWriter(this);
extensionWriter.WriteUntil(536870912, output);
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;
size += ExtensionsSerializedSize;
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
public static TestUnpackedExtensions ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static TestUnpackedExtensions ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static TestUnpackedExtensions ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static TestUnpackedExtensions ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static TestUnpackedExtensions ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static TestUnpackedExtensions ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static TestUnpackedExtensions ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static TestUnpackedExtensions ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static TestUnpackedExtensions ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static TestUnpackedExtensions ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private TestUnpackedExtensions 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(TestUnpackedExtensions prototype) {
return new Builder(prototype);
}
[global::System.SerializableAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::ExtendableBuilder<TestUnpackedExtensions, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(TestUnpackedExtensions cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private TestUnpackedExtensions result;
private TestUnpackedExtensions PrepareBuilder() {
if (resultIsReadOnly) {
TestUnpackedExtensions original = result;
result = new TestUnpackedExtensions();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override TestUnpackedExtensions MessageBeingBuilt {
get { return PrepareBuilder(); }
}
public override Builder Clear() {
result = DefaultInstance;
resultIsReadOnly = true;
return this;
}
public override Builder Clone() {
if (resultIsReadOnly) {
return new Builder(result);
} else {
return new Builder().MergeFrom(result);
}
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::Google.ProtocolBuffers.TestProtos.TestUnpackedExtensions.Descriptor; }
}
public override TestUnpackedExtensions DefaultInstanceForType {
get { return global::Google.ProtocolBuffers.TestProtos.TestUnpackedExtensions.DefaultInstance; }
}
public override TestUnpackedExtensions BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is TestUnpackedExtensions) {
return MergeFrom((TestUnpackedExtensions) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(TestUnpackedExtensions other) {
if (other == global::Google.ProtocolBuffers.TestProtos.TestUnpackedExtensions.DefaultInstance) return this;
PrepareBuilder();
this.MergeExtensionFields(other);
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(_testUnpackedExtensionsFieldNames, field_name, global::System.StringComparer.Ordinal);
if(field_ordinal >= 0)
tag = _testUnpackedExtensionsFieldTags[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;
}
}
}
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
}
static TestUnpackedExtensions() {
object.ReferenceEquals(global::Google.ProtocolBuffers.TestProtos.UnitTestExtrasProtoFile.Descriptor, null);
}
}
#endregion
}
#endregion Designer generated code
| |
// 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.Linq;
using System.Xml.Linq;
using CoreXml.Test.XLinq;
using Microsoft.Test.ModuleCore;
namespace XLinqTests
{
//[TestCase(Name = "Constructors with params - XElement - array", Param = InputParamStyle.Array)]
//[TestCase(Name = "Constructors with params - XElement - node + array", Param = InputParamStyle.SingleAndArray)]
//[TestCase(Name = "Constructors with params - XElement - IEnumerable", Param = InputParamStyle.IEnumerable)]
public class ParamsObjectsCreationElem : XLinqTestCase
{
// Type is CoreXml.Test.XLinq.FunctionalTests+TreeManipulationTests+ParamsObjectsCreationElem
// Test Case
// XElement
// - from node without parent, from nodes with parent
// - elements
// - attributes
// - PI, Comments
// - self reference
// - nulls inside
// - the same object multiple times
// - Document
// - array/IEnumerable of allowed types
// - array/IEnumerable including not allowed types
// - element state after invalid operations
// - text as plaint text & text as XText node
// - concatenation of the text nodes
// sanity for creation of a complete tree using params constructor
#region Enums
public enum InputParamStyle
{
Array,
SingleAndArray,
IEnumerable
};
#endregion
#region Public Methods and Operators
public override void AddChildren()
{
AddChild(new TestVariation(XElementValidCreate) { Attribute = new VariationAttribute("XElement - multiple nodes, not connected") { Params = new object[] { false, 4 }, Priority = 1 } });
AddChild(new TestVariation(XElementValidCreate) { Attribute = new VariationAttribute("XElement - single node, not connected") { Params = new object[] { false, 1 }, Priority = 0 } });
AddChild(new TestVariation(XElementValidCreate) { Attribute = new VariationAttribute("XElement - single node, connected") { Params = new object[] { true, 1 }, Priority = 0 } });
AddChild(new TestVariation(XElementValidCreate) { Attribute = new VariationAttribute("(BVT)XElement - multiple nodes, connected") { Params = new object[] { true, 2 }, Priority = 0 } });
AddChild(new TestVariation(XElementValidCreate) { Attribute = new VariationAttribute("(BVT)XElement - multiple nodes, not connected") { Params = new object[] { false, 2 }, Priority = 0 } });
AddChild(new TestVariation(XElementValidCreate) { Attribute = new VariationAttribute("XElement - multiple nodes, connected") { Params = new object[] { true, 4 }, Priority = 1 } });
AddChild(new TestVariation(XElementDuppAttr) { Attribute = new VariationAttribute("XElement - Not allowed - duplicate attributes") { Priority = 2 } });
AddChild(new TestVariation(XElementNotAllowedXDoc) { Attribute = new VariationAttribute("XElement - Not allowed - XDocument") { Priority = 2 } });
AddChild(new TestVariation(XElementNotAllowedXDocType) { Attribute = new VariationAttribute("XElement - Not allowed - XDocumentType") { Param = 3, Priority = 2 } });
AddChild(new TestVariation(XElementEmptyArray) { Attribute = new VariationAttribute("XElement - nulls") { Priority = 3 } });
AddChild(new TestVariation(BuildFromQuery) { Attribute = new VariationAttribute("XElement - build from Query result") { Priority = 2 } });
AddChild(new TestVariation(IsEmptyProp1) { Attribute = new VariationAttribute("IsEmpty property Manipulation I.") { Priority = 0 } });
AddChild(new TestVariation(IsEmptyProp2) { Attribute = new VariationAttribute("IsEmpty property Manipulation II.") { Priority = 0 } });
}
//[Variation(Priority = 0, Desc = "(BVT)XElement - multiple nodes, connected", Params = new object[] { true, 2 })]
//[Variation(Priority = 0, Desc = "(BVT)XElement - multiple nodes, not connected", Params = new object[] { false, 2 })]
//[Variation(Priority = 1, Desc = "XElement - multiple nodes, connected", Params = new object[] { true, 4 })]
//[Variation(Priority = 1, Desc = "XElement - multiple nodes, not connected", Params = new object[] { false, 4 })]
//[Variation(Priority = 0, Desc = "XElement - single node, connected", Params = new object[] { true, 1 })]
//[Variation(Priority = 0, Desc = "XElement - single node, not connected", Params = new object[] { false, 1 })]
//[Variation(Priority = 2, Desc = "XElement - build from Query result")]
public void BuildFromQuery()
{
var mode = (InputParamStyle)Param;
XElement e1 = XElement.Parse(@"<A><B id='a1'/><B id='a2'/><B id='a4'/></A>");
XElement e2 = XElement.Parse(@"<root><a1 a='a'/><a2/><a3 b='b'/><a4 c='c'/><a5/><a6/><a7/><a8/></root>");
IEnumerable<XElement> nodes = from data1 in e1.Elements() join data2 in e2.Elements() on data1.Attribute("id").Value equals data2.Name.LocalName select data2;
IEnumerable<XAttribute> attributes = from data1 in e1.Elements() join data2 in e2.Elements() on data1.Attribute("id").Value equals data2.Name.LocalName select data2.FirstAttribute;
IEnumerable<ExpectedValue> expectedContent = ExpectedContent(nodes).ProcessNodes().ToList();
IEnumerable<ExpectedValue> expectedAttributes = ExpectedContent(attributes).Where(n => n.Data is XAttribute).ToList();
XElement e = CreateElement(mode, nodes.OfType<object>().Concat(attributes.OfType<object>()));
TestLog.Compare(expectedContent.EqualAll(e.Nodes(), XNode.EqualityComparer), "Content");
TestLog.Compare(expectedAttributes.EqualAllAttributes(e.Attributes(), Helpers.MyAttributeComparer), "Attributes");
}
//[Variation(Priority = 0, Desc = "IsEmpty property Manipulation I.")]
public void IsEmptyProp1()
{
var e = new XElement("e");
TestLog.Compare(e.IsEmpty, "Initial - empty");
TestLog.Compare(e.Value, "", "value 0");
e.RemoveNodes();
TestLog.Compare(e.IsEmpty, "Initial - after RemoveNodes 1");
TestLog.Compare(e.Value, "", "value 1");
e.Add("");
TestLog.Compare(!e.IsEmpty, "Initial - after Add");
TestLog.Compare(e.Value, "", "value 2");
e.RemoveNodes();
TestLog.Compare(e.IsEmpty, "Initial - after RemoveNodes 2");
TestLog.Compare(e.Value, "", "value 3");
}
//[Variation(Priority = 0, Desc = "IsEmpty property Manipulation II.")]
public void IsEmptyProp2()
{
var e = new XElement("e", "");
TestLog.Compare(!e.IsEmpty, "Initial - empty");
TestLog.Compare(e.Value, "", "value 0");
e.Add("");
TestLog.Compare(!e.IsEmpty, "Initial - after Add");
TestLog.Compare(e.Value, "", "value 1");
e.RemoveNodes();
TestLog.Compare(e.IsEmpty, "Initial - after RemoveNodes 1");
TestLog.Compare(e.Value, "", "value 2");
e.Add("");
TestLog.Compare(!e.IsEmpty, "Initial - after Add");
TestLog.Compare(e.Value, "", "value 3");
}
public void XElementDuppAttr()
{
var mode = (InputParamStyle)Param;
object[] paras = { new XAttribute("id", "a1"), new XAttribute("other", "ooo"), new XAttribute("id", "a2"), null, "", "text", new XElement("aa"), new XProcessingInstruction("PI", "click"), new XComment("comment") };
try
{
XElement e = CreateElement(mode, paras);
TestLog.Compare(false, "Exception expected");
}
catch (InvalidOperationException)
{
}
}
public void XElementEmptyArray()
{
var mode = (InputParamStyle)Param;
object[] nulls = { new object[] { }, new object[] { null, null }, null, "", new object[] { null, new object[] { null, null }, null }, new object[] { null, new object[] { null, null }, new List<object> { null, null, null } } };
foreach (object paras in nulls)
{
XElement elem = CreateElement(mode, paras);
TestLog.Compare(elem != null, "elem != null");
TestLog.Compare(elem.FirstNode == null, "elem.FirstNode==null");
elem.Verify();
}
}
public void XElementNotAllowedXDoc()
{
var mode = (InputParamStyle)Param;
object[] paras = { new XAttribute("id", "a1"), null, "text", new XDocument(), new XElement("aa"), new XProcessingInstruction("PI", "click"), new XComment("comment") };
try
{
XElement e = CreateElement(mode, paras);
TestLog.Compare(false, "Exception expected");
}
catch (ArgumentException)
{
}
}
//[Variation(Priority = 2, Desc = "XElement - Not allowed - XDocumentType", Param = 3)]
public void XElementNotAllowedXDocType()
{
var mode = (InputParamStyle)Param;
object[] paras = { new XAttribute("id", "a1"), new XDocumentType("doctype", "", "", ""), "text", null, new XElement("aa"), new XProcessingInstruction("PI", "click"), new XComment("comment") };
try
{
XElement e = CreateElement(mode, paras);
TestLog.Compare(false, "Exception expected");
}
catch (ArgumentException)
{
}
}
public void XElementValidCreate()
{
var mode = (InputParamStyle)Param;
var isConnected = (bool)Variation.Params[0];
var CombinationLength = (int)Variation.Params[1];
object[] nodes = { new XElement("A"), new XElement("A", new XAttribute("a1", "a1")), new object[] { new XElement("B"), "", null, new XElement("C"), new XAttribute("xx", "yy") }, new XElement("{NS1}A"), new XAttribute("id", "a1"), new XAttribute("ie", "ie"), new XAttribute("{NS1}id", "b2"), "", new XAttribute(XNamespace.Xmlns + "NS1", "http://ns1"),
new XProcessingInstruction("Pi", "data"), new XProcessingInstruction("P2", ""), null, new XComment("comment"), new XText("text1"), new XCData("textCDATA"), "textPlain1", "textPlain2" };
XElement dummy = null;
if (isConnected)
{
dummy = new XElement("dummy", nodes);
}
foreach (var data in nodes.NonRecursiveVariations(CombinationLength))
{
IEnumerable<ExpectedValue> expectedContent = ExpectedContent(data.Flatten()).ProcessNodes().ToList();
IEnumerable<ExpectedValue> expectedAttributes = ExpectedContent(data.Flatten()).Where(n => n.Data is XAttribute).ToList();
XElement e = CreateElement(mode, data);
TestLog.Compare(expectedContent.EqualAll(e.Nodes(), XNode.EqualityComparer), "Content");
TestLog.Compare(expectedAttributes.EqualAllAttributes(e.Attributes(), Helpers.MyAttributeComparer), "Attributes");
e.Verify();
}
}
#endregion
#region Methods
private XElement CreateElement(InputParamStyle mode, object[] data)
{
XElement e = null;
switch (mode)
{
case InputParamStyle.Array:
e = new XElement(nameof(data), data);
break;
case InputParamStyle.SingleAndArray:
if (data.Length < 2)
{
goto case InputParamStyle.Array;
}
var copy = new object[data.Length - 1];
Array.Copy(data, 1, copy, 0, data.Length - 1);
e = new XElement(nameof(data), data[0], copy);
break;
case InputParamStyle.IEnumerable:
e = new XElement(nameof(data), data);
break;
default:
TestLog.Compare(false, "test failed");
break;
}
return e;
}
private XElement CreateElement(InputParamStyle mode, object data)
{
return new XElement(nameof(data), data);
}
private IEnumerable<ExpectedValue> ExpectedContent<T>(IEnumerable<T> data) where T : class
{
return data.Select(n => new ExpectedValue((n is XNode) && (!(n is XText)) && (n as XNode).Parent == null, n));
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Cuyahoga.Core.Domain;
using Cuyahoga.Core.Service;
using Cuyahoga.Web.UI;
using Cuyahoga.Web.Util;
using Cuyahoga.Web.Admin.UI;
namespace Cuyahoga.Web.Admin
{
/// <summary>
/// Summary description for SectionAttach.
/// </summary>
public class SectionAttachNode : AdminBasePage
{
private Section _activeSection;
private Site _selectedSite;
private Node _selectedNode;
protected System.Web.UI.WebControls.Label lblSection;
protected System.Web.UI.WebControls.Label lblModuleType;
protected System.Web.UI.WebControls.Button btnSave;
protected System.Web.UI.WebControls.ListBox lbxAvailableNodes;
protected System.Web.UI.WebControls.DropDownList ddlSites;
protected System.Web.UI.WebControls.DropDownList ddlPlaceholder;
protected System.Web.UI.WebControls.HyperLink hplLookup;
protected System.Web.UI.WebControls.Button btnBack;
private void Page_Load(object sender, System.EventArgs e)
{
this.Title = "Attach section";
if (Context.Request.QueryString["SectionId"] != null)
{
// Get section data
this._activeSection = (Section)base.CoreRepository.GetObjectById(typeof(Section),
Int32.Parse(Context.Request.QueryString["SectionId"]));
}
if (! this.IsPostBack)
{
BindSectionControls();
BindSites();
}
else
{
if (this.ddlSites.SelectedIndex > -1)
{
this._selectedSite = (Site)base.CoreRepository.GetObjectById(typeof(Site)
, Int32.Parse(this.ddlSites.SelectedValue));
}
if (this.lbxAvailableNodes.SelectedIndex > -1)
{
this._selectedNode = (Node)base.CoreRepository.GetObjectById(typeof(Node)
, Int32.Parse(this.lbxAvailableNodes.SelectedValue));
}
}
}
private void BindSectionControls()
{
if (this._activeSection != null)
{
this.lblSection.Text = this._activeSection.Title;
this.lblModuleType.Text = this._activeSection.ModuleType.Name;
}
}
private void BindSites()
{
IList sites = base.CoreRepository.GetAll(typeof(Site));
foreach (Site site in sites)
{
if (this._selectedSite == null)
{
this._selectedSite = site;
}
ListItem li = new ListItem(site.Name + " (" + site.SiteUrl + ")", site.Id.ToString());
this.ddlSites.Items.Add(li);
}
BindNodes();
}
private void BindNodes()
{
if (this._selectedSite != null)
{
this.lbxAvailableNodes.Visible = true;
this.lbxAvailableNodes.Items.Clear();
IList rootNodes = base.CoreRepository.GetRootNodes(this._selectedSite);
AddAvailableNodes(rootNodes);
}
this.btnSave.Enabled = false;
this.ddlPlaceholder.Visible = false;
this.hplLookup.Visible = false;
}
private void BindPlaceholders()
{
if (this._selectedNode != null)
{
if (this._selectedNode.Template != null)
{
try
{
this.ddlPlaceholder.Visible = true;
// Read template control and get the containers (placeholders)
string templatePath = Util.UrlHelper.GetApplicationPath() + this._selectedNode.Template.Path;
BaseTemplate template = (BaseTemplate)this.LoadControl(templatePath);
this.ddlPlaceholder.DataSource = template.Containers;
this.ddlPlaceholder.DataValueField = "Key";
this.ddlPlaceholder.DataTextField = "Key";
this.ddlPlaceholder.DataBind();
// Create url for lookup
this.hplLookup.Visible = true;
this.hplLookup.NavigateUrl = "javascript:;";
this.hplLookup.Attributes.Add("onclick"
, String.Format("window.open(\"TemplatePreview.aspx?TemplateId={0}&Control={1}\", \"Preview\", \"width=760 height=400\")"
, this._selectedNode.Template.Id
, this.ddlPlaceholder.ClientID)
);
this.btnSave.Enabled = true;
}
catch (Exception ex)
{
ShowError(ex.Message);
}
}
else
{
this.ddlPlaceholder.Visible = false;
this.btnSave.Enabled = false;
this.hplLookup.Visible = false;
}
}
}
private void AddAvailableNodes(IList nodes)
{
foreach (Node node in nodes)
{
int indentSpaces = node.Level * 5;
string itemIndentSpaces = String.Empty;
for (int i = 0; i < indentSpaces; i++)
{
itemIndentSpaces += " ";
}
ListItem li = new ListItem(Context.Server.HtmlDecode(itemIndentSpaces) + node.Title, node.Id.ToString());
this.lbxAvailableNodes.Items.Add(li);
if (node.ChildNodes.Count > 0)
{
AddAvailableNodes(node.ChildNodes);
}
}
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.ddlSites.SelectedIndexChanged += new System.EventHandler(this.ddlSites_SelectedIndexChanged);
this.lbxAvailableNodes.SelectedIndexChanged += new System.EventHandler(this.lbxAvailableNodes_SelectedIndexChanged);
this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
this.btnBack.Click += new System.EventHandler(this.btnBack_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void btnBack_Click(object sender, System.EventArgs e)
{
Context.Response.Redirect("~/Admin/Sections.aspx");
}
private void ddlSites_SelectedIndexChanged(object sender, System.EventArgs e)
{
BindNodes();
}
private void lbxAvailableNodes_SelectedIndexChanged(object sender, System.EventArgs e)
{
BindPlaceholders();
}
private void btnSave_Click(object sender, System.EventArgs e)
{
this._activeSection.Node = this._selectedNode;
this._activeSection.PlaceholderId = this.ddlPlaceholder.SelectedValue;
this._selectedNode.Sections.Add(this._activeSection);
this._activeSection.CalculateNewPosition();
try
{
base.CoreRepository.UpdateObject(this._activeSection);
// Update the full text index to make sure that the content can be found.
SearchHelper.UpdateIndexFromSection(this._activeSection);
Context.Response.Redirect("~/Admin/NodeEdit.aspx?NodeId=" + this._selectedNode.Id.ToString());
}
catch (Exception ex)
{
ShowError(ex.Message);
}
}
}
}
| |
using System;
using UnityEngine;
/// <summary>
/// This class defines a data container for visualization data.
/// </summary>
public class VisDataContainer
{
#region Public Member Variables
/// <summary>
/// This indicates the average value.
/// </summary>
public float average = 0.0f;
/// <summary>
/// This indicates the previous average value.
/// </summary>
public float previousAverage = 0.0f;
/// <summary>
/// This indicates the difference of the average value.
/// </summary>
public float averageDifference = 0.0f;
/// <summary>
/// This indicates the median value.
/// </summary>
public float median = 0.0f;
/// <summary>
/// This indicates the previous median value.
/// </summary>
public float previousMedian = 0.0f;
/// <summary>
/// This indicates the difference of the median value.
/// </summary>
public float medianDifference = 0.0f;
/// <summary>
/// This indicates the sum value.
/// </summary>
public float sum = 0.0f;
/// <summary>
/// This indicates the previous sum value.
/// </summary>
public float previousSum = 0.0f;
/// <summary>
/// This indicates the difference of the sum value.
/// </summary>
public float sumDifference = 0.0f;
/// <summary>
/// This indicates the minimum value.
/// </summary>
public float minimum = 0.0f;
/// <summary>
/// This indicates the previous minimum value.
/// </summary>
public float previousMinimum = 0.0f;
/// <summary>
/// This indicates the difference of the minimum value.
/// </summary>
public float minimumDifference = 0.0f;
/// <summary>
/// This indicates the maximum value.
/// </summary>
public float maximum = 0.0f;
/// <summary>
/// This indicates the previous maximum value.
/// </summary>
public float previousMaximum = 0.0f;
/// <summary>
/// This indicates the difference of the maximum value.
/// </summary>
public float maximumDifference = 0.0f;
#endregion
#region Accessor Functions
/// <summary>
/// This gets the value based on type.
/// </summary>
/// <param name="valueType">
/// This type of value to get.
/// </param>
/// <returns>
/// The value that was requested.
/// </returns>
public float GetValue(VisDataValueType valueType)
{
switch (valueType)
{
default:
case VisDataValueType.Average:
return average;
case VisDataValueType.Median:
return median;
case VisDataValueType.Sum:
return sum;
case VisDataValueType.Minimum:
return minimum;
case VisDataValueType.Maximum:
return maximum;
}
}
/// <summary>
/// This gets the previous value based on type.
/// </summary>
/// <param name="valueType">
/// This type of previous value to get.
/// </param>
/// <returns>
/// The previous value that was requested.
/// </returns>
public float GetPreviousValue(VisDataValueType valueType)
{
switch (valueType)
{
default:
case VisDataValueType.Average:
return previousAverage;
case VisDataValueType.Median:
return previousMedian;
case VisDataValueType.Sum:
return previousSum;
case VisDataValueType.Minimum:
return previousMinimum;
case VisDataValueType.Maximum:
return previousMaximum;
}
}
/// <summary>
/// This gets the value difference based on type.
/// </summary>
/// <param name="valueType">
/// This type of value difference to get.
/// </param>
/// <returns>
/// The value difference that was requested.
/// </returns>
public float GetValueDifference(VisDataValueType valueType)
{
switch (valueType)
{
default:
case VisDataValueType.Average:
return averageDifference;
case VisDataValueType.Median:
return medianDifference;
case VisDataValueType.Sum:
return sumDifference;
case VisDataValueType.Minimum:
return minimumDifference;
case VisDataValueType.Maximum:
return maximumDifference;
}
}
#endregion
#region Helper Functions
/// <summary>
/// This updates the previous value of this data container by setting the current value to the previous.
/// </summary>
public void UpdatePreviousValues()
{
//update previous values
previousAverage = average;
previousMedian = median;
previousSum = sum;
previousMinimum = minimum;
previousMaximum = maximum;
}
/// <summary>
/// This resets all current values back to their default values.
/// </summary>
public void ResetCurrentValues()
{
//reset current values
average = 0.0f;
median = 0.0f;
sum = 0.0f;
minimum = 10000.0f;
maximum = -10000.0f;
}
/// <summary>
/// This applies a boost and cutoff to all current values.
/// </summary>
/// <param name="boost">
/// The boost to apply.
/// </param>
/// <param name="cutoff">
/// The cutoff to apply.
/// </param>
public void ApplyBoostAndCutoff(float boost, float cutoff)
{
average = Mathf.Clamp(average * boost, average < 0.0f ? -cutoff : 0.0f, average < 0.0f ? 0.0f : cutoff);
median = Mathf.Clamp(median * boost, median < 0.0f ? -cutoff : 0.0f, median < 0.0f ? 0.0f : cutoff);
sum = Mathf.Clamp(sum * boost, boost < 0.0f ? -cutoff : 0.0f, boost < 0.0f ? 0.0f : cutoff);
minimum = Mathf.Clamp(minimum * boost, minimum < 0.0f ? -cutoff : 0.0f, minimum < 0.0f ? 0.0f : cutoff);
maximum = Mathf.Clamp(maximum * boost, maximum < 0.0f ? -cutoff : 0.0f, maximum < 0.0f ? 0.0f : cutoff);
}
/// <summary>
/// This updates all value differences by subtracting the current by the previous of each value type.
/// </summary>
public void UpdateValueDifferences()
{
//update differences
averageDifference = average - previousAverage;
medianDifference = median - previousMedian;
sumDifference = sum - previousSum;
minimumDifference = minimum - previousMinimum;
maximumDifference = maximum - previousMaximum;
}
#endregion
}
| |
using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.ComponentModel;
using gov.va.medora.mdws.dto;
/// <summary>
/// Summary description for ApolloService
/// </summary>
namespace gov.va.medora.mdws
{
/// <summary>
/// Summary description for ApolloService
/// </summary>
[WebService(Namespace = "http://mdws.medora.va.gov/ApolloService")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
public partial class ApolloService : BaseService
{
public ApolloService() {}
[WebMethod(EnableSession = true, Description = "Get all VHA sites")]
public RegionArray getVHA()
{
return (RegionArray)MySession.execute("SitesLib", "getVHA", new object[] { });
}
[WebMethod(EnableSession = true, Description = "Connect to a single VistA system.")]
public DataSourceArray connect(string sitelist)
{
return (DataSourceArray)MySession.execute("ConnectionLib", "connectToLoginSite", new object[] { sitelist });
}
[WebMethod(EnableSession = true, Description = "Log onto a single VistA system.")]
public UserTO login(string username, string pwd, string context)
{
return (UserTO)MySession.execute("AccountLib", "login", new object[] { username, pwd, context });
}
[WebMethod(EnableSession = true, Description = "Disconnect from single Vista system.")]
public TaggedTextArray disconnect()
{
return (TaggedTextArray)MySession.execute("ConnectionLib", "disconnectAll", new object[] { });
}
[WebMethod(EnableSession = true, Description = "Disconnect from remote Vista systems.")]
public TaggedTextArray disconnectRemoteSites()
{
return (TaggedTextArray)MySession.execute("ConnectionLib", "disconnectRemoteSites", new object[] { });
}
[WebMethod(EnableSession = true, Description = "Use when switching patient lookup sites.")]
public TaggedTextArray visit(string pwd, string sitelist, string userSitecode, string userName, string DUZ, string SSN, string context)
{
return (TaggedTextArray)MySession.execute("ConnectionLib", "visit", new object[] { pwd, sitelist, userSitecode, userName, DUZ, SSN, context });
}
[WebMethod(EnableSession = true, Description = "Visit site 200 from DoD app.")]
public TaggedTextArray visit200(string pwd)
{
return (TaggedTextArray)MySession.execute("ConnectionLib", "visitSite200", new object[] { });
}
[WebMethod(EnableSession = true, Description = "Call when launching from CPRS Tools menu: connects, authenticates, selects patient.")]
public PersonsTO cprsLaunch(string pwd, string sitecode, string DUZ, string DFN)
{
return (PersonsTO)MySession.execute("ConnectionLib", "cprsLaunch", new object[] { pwd, sitecode, DUZ, DFN });
}
[WebMethod(EnableSession = true, Description = "Match patients at logged in site.")]
public TaggedPatientArrays match(string target)
{
return (TaggedPatientArrays)MySession.execute("PatientLib", "match", new object[] { target });
}
[WebMethod(EnableSession = true, Description = "Select a patient at logged in site.")]
public PatientTO select(string DFN)
{
return (PatientTO)MySession.execute("PatientLib", "select", new object[] { DFN });
}
[WebMethod(EnableSession = true, Description = "Setup patient's remote sites for querying.")]
public SiteArray setupMultiSiteQuery(string appPwd)
{
//SiteArray result = new SiteArray();
//Object rtn = MySession.execute("ConnectionLib", "setupMultiSourcePatientQuery", new object[] { appPwd, "" });
//if (rtn.GetType().IsAssignableFrom(typeof(System.Exception)))
//{
// result.fault = new FaultTO(((Exception)rtn).Message);
//}
//return (SiteArray)result;
return (SiteArray)MySession.execute("ConnectionLib", "setupMultiSourcePatientQuery", new object[] { appPwd, "" });
}
[WebMethod(EnableSession = true, Description = "Get patient confidentiality from all connected sites.")]
public TaggedTextArray getConfidentiality()
{
return (TaggedTextArray)MySession.execute("PatientLib", "getConfidentiality", new object[] { });
}
[WebMethod(EnableSession = true, Description = "Get patient confidentiality from all connected sites.")]
public TaggedTextArray issueConfidentialityBulletin()
{
return (TaggedTextArray)MySession.execute("PatientLib", "issueConfidentialityBulletin", new object[] { });
}
[WebMethod(EnableSession = true, Description = "Get latest vitals from all connected VistAs")]
public TaggedVitalSignArrays getLatestVitalSigns()
{
return (TaggedVitalSignArrays)MySession.execute("ClinicalLib", "getLatestVitalSigns", new object[] { });
}
[WebMethod(EnableSession = true, Description = "Get patient's vital signs.")]
public TaggedVitalSignSetArrays getVitalSigns(string fromDate, string toDate)
{
return (TaggedVitalSignSetArrays)MySession.execute("ClinicalLib", "getVitalSigns", new object[] { fromDate, toDate });
}
[WebMethod(EnableSession = true, Description = "Get allergies from all connected VistAs")]
public TaggedAllergyArrays getAllergies(string fromDate, string toDate, int nrex)
{
return (TaggedAllergyArrays)MySession.execute("ClinicalLib", "getAllergies", new object[] { });
}
[WebMethod(EnableSession = true, Description = "Get radiology reports from all connected VistAs")]
public TaggedRadiologyReportArrays getRadiologyReports(string fromDate, string toDate, int nrpts)
{
return (TaggedRadiologyReportArrays)MySession.execute("ClinicalLib", "getRadiologyReports", new object[] { fromDate, toDate, nrpts });
}
[WebMethod(EnableSession = true, Description = "Get surgery reports from all connected VistAs")]
public TaggedSurgeryReportArrays getSurgeryReports()
{
return (TaggedSurgeryReportArrays)MySession.execute("ClinicalLib", "getSurgeryReports", new object[] { });
}
[WebMethod(EnableSession = true, Description = "Get text for a certain surgery report")]
public TextTO getSurgeryReportText(string siteId, string rptId)
{
return (TextTO)MySession.execute("ClinicalLib", "getSurgeryReportText", new object[] { siteId, rptId });
}
[WebMethod(EnableSession = true, Description = "Get problem list from all connected VistAs")]
public TaggedProblemArrays getProblemList(string type, int nrex)
{
return (TaggedProblemArrays)MySession.execute("ClinicalLib", "getProblemList", new object[] { type });
}
[WebMethod(EnableSession = true, Description = "Get outpatient medications from all connected VistAs")]
public TaggedMedicationArrays getOutpatientMeds(string fromDate, string toDate, int nrex)
{
return (TaggedMedicationArrays)MySession.execute("MedsLib", "getOutpatientMeds", new object[] { });
}
[WebMethod(EnableSession = true, Description = "Get IV medications from all connected VistAs")]
public TaggedMedicationArrays getIvMeds(string fromDate, string toDate, int nrex)
{
return (TaggedMedicationArrays)MySession.execute("MedsLib", "getIvMeds", new object[] { });
}
[WebMethod(EnableSession = true, Description = "Get unit dose medications from all connected VistAs")]
public TaggedMedicationArrays getUnitDoseMeds(string fromDate, string toDate, int nrex)
{
return (TaggedMedicationArrays)MySession.execute("MedsLib", "getUnitDoseMeds", new object[] { });
}
[WebMethod(EnableSession = true, Description = "Get non-VA medications from all connected VistAs")]
public TaggedMedicationArrays getNonVaMeds(string fromDate, string toDate, int nrex)
{
return (TaggedMedicationArrays)MySession.execute("MedsLib", "getOtherMeds", new object[] { });
}
[WebMethod(EnableSession = true, Description = "Get all medications from all connected VistAs")]
public TaggedMedicationArrays getAllMeds(string fromDate, string toDate, int nrex)
{
return (TaggedMedicationArrays)MySession.execute("MedsLib", "getAllMeds", new object[] { });
}
//[WebMethod(EnableSession = true, Description = "Get VA medications from all connected VistAs")]
//public TaggedMedicationArrays getVaMeds()
//{
// return (TaggedMedicationArrays)MySession.execute("MedsLib", "getVaMeds", new object[] { });
//}
[WebMethod(EnableSession = true, Description = "Get medication detail from a single connected VistA.")]
public TextTO getVaMedicationDetail(string siteId, string medId)
{
return (TextTO)MySession.execute("MedsLib", "getMedicationDetail", new object[] { siteId, medId });
}
[WebMethod(EnableSession = true, Description = "Get signed note metadata from all connected VistAs")]
public TaggedNoteArrays getSignedNotes(string fromDate, string toDate, int nNotes)
{
return (TaggedNoteArrays)MySession.execute("NoteLib", "getSignedNotes", new object[] { fromDate, toDate, nNotes });
}
[WebMethod(EnableSession = true, Description = "Get unsigned note metadata from all connected VistAs")]
public TaggedNoteArrays getUnsignedNotes(string fromDate, string toDate, int nNotes)
{
return (TaggedNoteArrays)MySession.execute("NoteLib", "getUnsignedNotes", new object[] { fromDate, toDate, nNotes });
}
[WebMethod(EnableSession = true, Description = "Get uncosigned note metadata from all connected VistAs")]
public TaggedNoteArrays getUncosignedNotes(string fromDate, string toDate, int nNotes)
{
return (TaggedNoteArrays)MySession.execute("NoteLib", "getUncosignedNotes", new object[] { fromDate, toDate, nNotes });
}
[WebMethod(EnableSession = true, Description = "Get a note from a single connected VistA.")]
public TextTO getNote(string siteId, string noteId)
{
return (TextTO)MySession.execute("NoteLib", "getNote", new object[] { siteId, noteId });
}
[WebMethod(EnableSession = true, Description = "Get notes with text from all connected VistAs.")]
public TaggedNoteArrays getNotesWithText(string fromDate, string toDate, int nNotes)
{
return (TaggedNoteArrays)MySession.execute("NoteLib", "getNotesWithText", new object[] { fromDate, toDate, nNotes });
}
[WebMethod(EnableSession = true, Description = "Get discharge summaries from all connected VistAs.")]
public TaggedNoteArrays getDischargeSummaries(string fromDate, string toDate, int nNotes)
{
return (TaggedNoteArrays)MySession.execute("NoteLib", "getDischargeSummaries", new object[] { fromDate, toDate, nNotes });
}
[WebMethod(EnableSession = true, Description = "Get patient's current consults.")]
public TaggedConsultArrays getConsultsForPatient()
{
return (TaggedConsultArrays)MySession.execute("OrdersLib", "getConsultsForPatient", new object[] { });
}
[WebMethod(EnableSession = true, Description = "Get patient's appointments.")]
public TaggedAppointmentArrays getAppointments()
{
return (TaggedAppointmentArrays)MySession.execute("EncounterLib", "getAppointments", new object[] { });
}
[WebMethod(EnableSession = true, Description = "Get note for appointment.")]
public TextTO getAppointmentText(string siteId, string apptId)
{
return (TextTO)MySession.execute("EncounterLib", "getAppointmentText", new object[] { siteId, apptId });
}
[WebMethod(EnableSession = true, Description = "Get patient's clinical warnings.")]
public TaggedTextArray getClinicalWarnings(string fromDate, string toDate, int nrpts)
{
return (TaggedTextArray)MySession.execute("NoteLib", "getClinicalWarnings", new object[] { fromDate, toDate, nrpts });
}
[WebMethod(EnableSession = true, Description = "Get patient's advance directives.")]
public TaggedTextArray getAdvanceDirectives(string fromDate, string toDate, int nrpts)
{
return (TaggedTextArray)MySession.execute("NoteLib", "getAdvanceDirectives", new object[] { fromDate, toDate, nrpts });
}
[WebMethod(EnableSession = true, Description = "Get patient's crisis notes.")]
public TaggedTextArray getCrisisNotes(string fromDate, string toDate, int nrpts)
{
return (TaggedTextArray)MySession.execute("NoteLib", "getCrisisNotes", new object[] { fromDate, toDate, nrpts });
}
[WebMethod(EnableSession = true, Description = "Get patient's immunizations.")]
public TaggedTextArray getImmunizations(string fromDate, string toDate, int nrpts)
{
return (TaggedTextArray)MySession.execute("MedsLib", "getImmunizations", new object[] { fromDate, toDate, nrpts });
}
[WebMethod(EnableSession = true, Description = "Get patient's outpatient prescription profile.")]
public TaggedTextArray getOutpatientRxProfile()
{
return (TaggedTextArray)MySession.execute("MedsLib", "getOutpatientRxProfile", new object[] { });
}
[WebMethod(EnableSession = true, Description = "Get patient's meds administation history.")]
public TaggedTextArray getMedsAdminHx(string fromDate, string toDate, int nrpts)
{
return (TaggedTextArray)MySession.execute("MedsLib", "getMedsAdminHx", new object[] { fromDate, toDate, nrpts });
}
[WebMethod(EnableSession = true, Description = "Get patient's meds administation log.")]
public TaggedTextArray getMedsAdminLog(string fromDate, string toDate, int nrpts)
{
return (TaggedTextArray)MySession.execute("MedsLib", "getMedsAdminLog", new object[] { fromDate, toDate, nrpts });
}
[WebMethod(EnableSession = true, Description = "Get patient's chem/hem lab results.")]
public TaggedChemHemRptArrays getChemHemReports(string fromDate, string toDate, int nrpts)
{
return (TaggedChemHemRptArrays)MySession.execute("LabsLib", "getChemHemReports", new object[] { fromDate, toDate, nrpts });
}
[WebMethod(EnableSession = true, Description = "Get patient's Cytology lab results.")]
public TaggedCytologyRptArrays getCytologyReports(string fromDate, string toDate, int nrpts)
{
return (TaggedCytologyRptArrays)MySession.execute("LabsLib", "getCytologyReports", new object[] { fromDate, toDate, nrpts });
}
[WebMethod(EnableSession = true, Description = "Get patient's microbiology lab results.")]
public TaggedMicrobiologyRptArrays getMicrobiologyReports(string fromDate, string toDate, int nrpts)
{
return (TaggedMicrobiologyRptArrays)MySession.execute("LabsLib", "getMicrobiologyReports", new object[] { fromDate, toDate, nrpts });
}
[WebMethod(EnableSession = true, Description = "Get patient's surgical pathology lab results.")]
public TaggedSurgicalPathologyRptArrays getSurgicalPathologyReports(string fromDate, string toDate, int nrpts)
{
return (TaggedSurgicalPathologyRptArrays)MySession.execute("LabsLib", "getSurgicalPathologyReports", new object[] { fromDate, toDate, nrpts });
}
[WebMethod(EnableSession = true, Description = "Get patient's blood availability reports.")]
public TaggedTextArray getBloodAvailabilityReports(string fromDate, string toDate, int nrpts)
{
return (TaggedTextArray)MySession.execute("LabsLib", "getBloodAvailabilityReports", new object[] { fromDate, toDate, nrpts });
}
[WebMethod(EnableSession = true, Description = "Get patient's blood transfusion reports.")]
public TaggedTextArray getBloodTransfusionReports(string fromDate, string toDate, int nrpts)
{
return (TaggedTextArray)MySession.execute("LabsLib", "getBloodTransfusionReports", new object[] { fromDate, toDate, nrpts });
}
[WebMethod(EnableSession = true, Description = "Get patient's blood bank reports.")]
public TaggedTextArray getBloodBankReports()
{
return (TaggedTextArray)MySession.execute("LabsLib", "getBloodBankReports", new object[] { });
}
[WebMethod(EnableSession = true, Description = "Get patient's electron microscopy reports.")]
public TaggedTextArray getElectronMicroscopyReports(string fromDate, string toDate, int nrpts)
{
return (TaggedTextArray)MySession.execute("LabsLib", "getElectronMicroscopyReports", new object[] { fromDate, toDate, nrpts });
}
[WebMethod(EnableSession = true, Description = "Get patient's cytopathology reports.")]
public TaggedTextArray getCytopathologyReports()
{
return (TaggedTextArray)MySession.execute("LabsLib", "getCytopathologyReports", new object[] { });
}
[WebMethod(EnableSession = true, Description = "Get patient's autopsy reports.")]
public TaggedTextArray getAutopsyReports()
{
return (TaggedTextArray)MySession.execute("LabsLib", "getAutopsyReports", new object[] { });
}
[WebMethod(EnableSession = true, Description = "Get discharge summaries from all connected VistAs.")]
public TaggedTextArray getOutpatientEncounterReports(string fromDate, string toDate, int nrpts)
{
return (TaggedTextArray)MySession.execute("EncounterLib", "getOutpatientEncounterReports", new object[] { fromDate, toDate, nrpts });
}
[WebMethod(EnableSession = true, Description = "Get discharge summaries from all connected VistAs.")]
public TaggedTextArray getAdmissionsReports(string fromDate, string toDate, int nrpts)
{
return (TaggedTextArray)MySession.execute("EncounterLib", "getAdmissionsReports", new object[] { fromDate, toDate, nrpts });
}
[WebMethod(EnableSession = true, Description = "Get discharge summaries from all connected VistAs.")]
public TaggedTextArray getExpandedAdtReports(string fromDate, string toDate, int nrpts)
{
return (TaggedTextArray)MySession.execute("EncounterLib", "getExpandedAdtReports", new object[] { fromDate, toDate, nrpts });
}
[WebMethod(EnableSession = true, Description = "Get discharge summaries from all connected VistAs.")]
public TaggedTextArray getDischargeDiagnosisReports(string fromDate, string toDate, int nrpts)
{
return (TaggedTextArray)MySession.execute("EncounterLib", "getDischargeDiagnosisReports", new object[] { fromDate, toDate, nrpts });
}
[WebMethod(EnableSession = true, Description = "Get discharge summaries from all connected VistAs.")]
public TaggedTextArray getDischargesReports(string fromDate, string toDate, int nrpts)
{
return (TaggedTextArray)MySession.execute("EncounterLib", "getDischargesReports", new object[] { fromDate, toDate, nrpts });
}
[WebMethod(EnableSession = true, Description = "Get discharge summaries from all connected VistAs.")]
public TaggedTextArray getTransfersReports(string fromDate, string toDate, int nrpts)
{
return (TaggedTextArray)MySession.execute("EncounterLib","getTransfersReports", new object[]{fromDate, toDate, nrpts});
}
[WebMethod(EnableSession = true, Description = "Get discharge summaries from all connected VistAs.")]
public TaggedTextArray getFutureClinicVisitsReports(string fromDate, string toDate, int nrpts)
{
return (TaggedTextArray)MySession.execute("EncounterLib","getFutureClinicVisitsReports", new object[]{fromDate, toDate, nrpts});
}
[WebMethod(EnableSession = true, Description = "Get discharge summaries from all connected VistAs.")]
public TaggedTextArray getPastClinicVisitsReports(string fromDate, string toDate, int nrpts)
{
return (TaggedTextArray)MySession.execute("EncounterLib","getPastClinicVisitsReports", new object[]{fromDate, toDate, nrpts});
}
[WebMethod(EnableSession = true, Description = "Get discharge summaries from all connected VistAs.")]
public TaggedTextArray getTreatingSpecialtyReports(string fromDate, string toDate, int nrpts)
{
return (TaggedTextArray)MySession.execute("EncounterLib","getTreatingSpecialtyReports", new object[]{fromDate, toDate, nrpts});
}
[WebMethod(EnableSession = true, Description = "Get discharge summaries from all connected VistAs.")]
public TaggedTextArray getCompAndPenReports(string fromDate, string toDate, int nrpts)
{
return (TaggedTextArray)MySession.execute("EncounterLib","getCompAndPenReports", new object[]{fromDate, toDate, nrpts});
}
[WebMethod(EnableSession = true, Description = "Get discharge summaries from all connected VistAs.")]
public TaggedTextArray getCareTeamReports()
{
return (TaggedTextArray)MySession.execute("EncounterLib", "getCareTeamReports", new object[] { });
}
[WebMethod(EnableSession = true, Description = "Get discharge summaries from all connected VistAs.")]
public TaggedIcdRptArrays getIcdProceduresReports(string fromDate, string toDate, int nrpts)
{
return (TaggedIcdRptArrays)MySession.execute("EncounterLib", "getIcdProceduresReports", new object[] { fromDate, toDate, nrpts });
}
[WebMethod(EnableSession = true, Description = "Get discharge summaries from all connected VistAs.")]
public TaggedIcdRptArrays getIcdSurgeryReports(string fromDate, string toDate, int nrpts)
{
return (TaggedIcdRptArrays)MySession.execute("EncounterLib", "getIcdSurgeryReports", new object[] { fromDate, toDate, nrpts });
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.Management.Automation;
using System.Management.Automation.Host;
using System.Management.Automation.Internal;
using System.Text;
using Microsoft.PowerShell.Commands.Internal.Format;
using Dbg = System.Management.Automation.Diagnostics;
namespace Microsoft.PowerShell
{
/// <summary>
/// ProgressNode is an augmentation of the ProgressRecord type that adds extra fields for the purposes of tracking
/// outstanding activities received by the host, and rendering them in the console.
/// </summary>
internal
class
ProgressNode : ProgressRecord
{
/// <summary>
/// Indicates the various layouts for rendering a particular node.
/// </summary>
internal
enum
RenderStyle
{
Invisible = 0,
Minimal = 1,
Compact = 2,
/// <summary>
/// Allocate only one line for displaying the StatusDescription or the CurrentOperation,
/// truncate the rest if the StatusDescription or CurrentOperation doesn't fit in one line.
/// </summary>
Full = 3,
/// <summary>
/// The node will be displayed the same as Full, plus, the whole StatusDescription and CurrentOperation will be displayed (in multiple lines if needed).
/// </summary>
FullPlus = 4,
/// <summary>
/// The node will be displayed using ANSI escape sequences.
/// </summary>
Ansi = 5,
}
/// <summary>
/// Constructs an instance from a ProgressRecord.
/// </summary>
internal
ProgressNode(long sourceId, ProgressRecord record)
: base(record.ActivityId, record.Activity, record.StatusDescription)
{
Dbg.Assert(record.RecordType == ProgressRecordType.Processing, "should only create node for Processing records");
this.ParentActivityId = record.ParentActivityId;
this.CurrentOperation = record.CurrentOperation;
this.PercentComplete = Math.Min(record.PercentComplete, 100);
this.SecondsRemaining = record.SecondsRemaining;
this.RecordType = record.RecordType;
this.Style = IsMinimalProgressRenderingEnabled()
? RenderStyle.Ansi
: this.Style = RenderStyle.FullPlus;
this.SourceId = sourceId;
}
/// <summary>
/// Renders a single progress node as strings of text according to that node's style. The text is appended to the
/// supplied list of strings.
/// </summary>
/// <param name="strCollection">
/// List of strings to which the node's rendering will be appended.
/// </param>
/// <param name="indentation">
/// The indentation level (in BufferCells) at which the node should be rendered.
/// </param>
/// <param name="maxWidth">
/// The maximum number of BufferCells that the rendering is allowed to consume.
/// </param>
/// <param name="rawUI">
/// The PSHostRawUserInterface used to gauge string widths in the rendering.
/// </param>
internal
void
Render(ArrayList strCollection, int indentation, int maxWidth, PSHostRawUserInterface rawUI)
{
Dbg.Assert(strCollection != null, "strCollection should not be null");
Dbg.Assert(indentation >= 0, "indentation is negative");
Dbg.Assert(this.RecordType != ProgressRecordType.Completed, "should never render completed records");
switch (Style)
{
case RenderStyle.FullPlus:
RenderFull(strCollection, indentation, maxWidth, rawUI, isFullPlus: true);
break;
case RenderStyle.Full:
RenderFull(strCollection, indentation, maxWidth, rawUI, isFullPlus: false);
break;
case RenderStyle.Compact:
RenderCompact(strCollection, indentation, maxWidth, rawUI);
break;
case RenderStyle.Minimal:
RenderMinimal(strCollection, indentation, maxWidth, rawUI);
break;
case RenderStyle.Ansi:
RenderAnsi(strCollection, indentation, maxWidth);
break;
case RenderStyle.Invisible:
// do nothing
break;
default:
Dbg.Assert(false, "unrecognized RenderStyle value");
break;
}
}
/// <summary>
/// Renders a node in the "Full" style.
/// </summary>
/// <param name="strCollection">
/// List of strings to which the node's rendering will be appended.
/// </param>
/// <param name="indentation">
/// The indentation level (in BufferCells) at which the node should be rendered.
/// </param>
/// <param name="maxWidth">
/// The maximum number of BufferCells that the rendering is allowed to consume.
/// </param>
/// <param name="rawUI">
/// The PSHostRawUserInterface used to gauge string widths in the rendering.
/// </param>
/// <param name="isFullPlus">
/// Indicate if the full StatusDescription and CurrentOperation should be displayed.
/// </param>
private
void
RenderFull(ArrayList strCollection, int indentation, int maxWidth, PSHostRawUserInterface rawUI, bool isFullPlus)
{
string indent = StringUtil.Padding(indentation);
// First line: the activity
strCollection.Add(
StringUtil.TruncateToBufferCellWidth(
rawUI, StringUtil.Format(" {0}{1} ", indent, this.Activity), maxWidth));
indentation += 3;
indent = StringUtil.Padding(indentation);
// Second line: the status description
RenderFullDescription(this.StatusDescription, indent, maxWidth, rawUI, strCollection, isFullPlus);
// Third line: the percentage thermometer. The size of this is proportional to the width we're allowed
// to consume. -2 for the whitespace, -2 again for the brackets around thermo, -5 to not be too big
if (PercentComplete >= 0)
{
int thermoWidth = Math.Max(3, maxWidth - indentation - 2 - 2 - 5);
int mercuryWidth = 0;
mercuryWidth = PercentComplete * thermoWidth / 100;
if (PercentComplete < 100 && mercuryWidth == thermoWidth)
{
// back off a tad unless we're totally complete to prevent the appearance of completion before
// the fact.
--mercuryWidth;
}
strCollection.Add(
StringUtil.TruncateToBufferCellWidth(
rawUI,
StringUtil.Format(
" {0}[{1}{2}] ",
indent,
new string('o', mercuryWidth),
StringUtil.Padding(thermoWidth - mercuryWidth)),
maxWidth));
}
// Fourth line: the seconds remaining
if (SecondsRemaining >= 0)
{
TimeSpan span = new TimeSpan(0, 0, this.SecondsRemaining);
strCollection.Add(
StringUtil.TruncateToBufferCellWidth(
rawUI,
" "
+ StringUtil.Format(
ProgressNodeStrings.SecondsRemaining,
indent,
span)
+ " ",
maxWidth));
}
// Fifth and Sixth lines: The current operation
if (!string.IsNullOrEmpty(CurrentOperation))
{
strCollection.Add(" ");
RenderFullDescription(this.CurrentOperation, indent, maxWidth, rawUI, strCollection, isFullPlus);
}
}
private static void RenderFullDescription(string description, string indent, int maxWidth, PSHostRawUserInterface rawUi, ArrayList strCollection, bool isFullPlus)
{
string oldDescription = StringUtil.Format(" {0}{1} ", indent, description);
string newDescription;
do
{
newDescription = StringUtil.TruncateToBufferCellWidth(rawUi, oldDescription, maxWidth);
strCollection.Add(newDescription);
if (oldDescription.Length == newDescription.Length)
{
break;
}
else
{
oldDescription = StringUtil.Format(" {0}{1}", indent, oldDescription.Substring(newDescription.Length));
}
} while (isFullPlus);
}
/// <summary>
/// Renders a node in the "Compact" style.
/// </summary>
/// <param name="strCollection">
/// List of strings to which the node's rendering will be appended.
/// </param>
/// <param name="indentation">
/// The indentation level (in BufferCells) at which the node should be rendered.
/// </param>
/// <param name="maxWidth">
/// The maximum number of BufferCells that the rendering is allowed to consume.
/// </param>
/// <param name="rawUI">
/// The PSHostRawUserInterface used to gauge string widths in the rendering.
/// </param>
private
void
RenderCompact(ArrayList strCollection, int indentation, int maxWidth, PSHostRawUserInterface rawUI)
{
string indent = StringUtil.Padding(indentation);
// First line: the activity
strCollection.Add(
StringUtil.TruncateToBufferCellWidth(
rawUI,
StringUtil.Format(" {0}{1} ", indent, this.Activity), maxWidth));
indentation += 3;
indent = StringUtil.Padding(indentation);
// Second line: the status description with percentage and time remaining, if applicable.
string percent = string.Empty;
if (PercentComplete >= 0)
{
percent = StringUtil.Format("{0}% ", PercentComplete);
}
string secRemain = string.Empty;
if (SecondsRemaining >= 0)
{
TimeSpan span = new TimeSpan(0, 0, SecondsRemaining);
secRemain = span.ToString() + " ";
}
strCollection.Add(
StringUtil.TruncateToBufferCellWidth(
rawUI,
StringUtil.Format(
" {0}{1}{2}{3} ",
indent,
percent,
secRemain,
StatusDescription),
maxWidth));
// Third line: The current operation
if (!string.IsNullOrEmpty(CurrentOperation))
{
strCollection.Add(
StringUtil.TruncateToBufferCellWidth(
rawUI,
StringUtil.Format(" {0}{1} ", indent, this.CurrentOperation), maxWidth));
}
}
/// <summary>
/// Renders a node in the "Minimal" style.
/// </summary>
/// <param name="strCollection">
/// List of strings to which the node's rendering will be appended.
/// </param>
/// <param name="indentation">
/// The indentation level (in BufferCells) at which the node should be rendered.
/// </param>
/// <param name="maxWidth">
/// The maximum number of BufferCells that the rendering is allowed to consume.
/// </param>
/// <param name="rawUI">
/// The PSHostRawUserInterface used to gauge string widths in the rendering.
/// </param>
private
void
RenderMinimal(ArrayList strCollection, int indentation, int maxWidth, PSHostRawUserInterface rawUI)
{
string indent = StringUtil.Padding(indentation);
// First line: Everything mushed into one line
string percent = string.Empty;
if (PercentComplete >= 0)
{
percent = StringUtil.Format("{0}% ", PercentComplete);
}
string secRemain = string.Empty;
if (SecondsRemaining >= 0)
{
TimeSpan span = new TimeSpan(0, 0, SecondsRemaining);
secRemain = span.ToString() + " ";
}
strCollection.Add(
StringUtil.TruncateToBufferCellWidth(
rawUI,
StringUtil.Format(
" {0}{1} {2}{3}{4} ",
indent,
Activity,
percent,
secRemain,
StatusDescription),
maxWidth));
}
internal static bool IsMinimalProgressRenderingEnabled()
{
return PSStyle.Instance.Progress.View == ProgressView.Minimal;
}
/// <summary>
/// Renders a node in the "ANSI" style.
/// </summary>
/// <param name="strCollection">
/// List of strings to which the node's rendering will be appended.
/// </param>
/// <param name="indentation">
/// The indentation level in chars at which the node should be rendered.
/// </param>
/// <param name="maxWidth">
/// The maximum number of chars that the rendering is allowed to consume.
/// </param>
private
void
RenderAnsi(ArrayList strCollection, int indentation, int maxWidth)
{
string indent = StringUtil.Padding(indentation);
string secRemain = string.Empty;
if (SecondsRemaining >= 0)
{
secRemain = SecondsRemaining.ToString() + "s";
}
int secRemainLength = secRemain.Length + 1;
// limit progress bar to 120 chars as no need to render full width
if (PSStyle.Instance.Progress.MaxWidth > 0 && maxWidth > PSStyle.Instance.Progress.MaxWidth)
{
maxWidth = PSStyle.Instance.Progress.MaxWidth;
}
// if the activity is really long, only use up to half the width
string activity;
if (Activity.Length > maxWidth / 2)
{
activity = Activity.Substring(0, maxWidth / 2) + PSObjectHelper.Ellipsis;
}
else
{
activity = Activity;
}
// 4 is for the extra space and square brackets below and one extra space
int barWidth = maxWidth - activity.Length - indentation - 4;
var sb = new StringBuilder();
int padding = maxWidth + PSStyle.Instance.Progress.Style.Length + PSStyle.Instance.Reverse.Length + PSStyle.Instance.ReverseOff.Length;
sb.Append(PSStyle.Instance.Reverse);
int maxStatusLength = barWidth - secRemainLength - 1;
if (maxStatusLength > 0 && StatusDescription.Length > barWidth - secRemainLength)
{
sb.Append(StatusDescription.AsSpan(0, barWidth - secRemainLength - 1));
sb.Append(PSObjectHelper.Ellipsis);
}
else
{
sb.Append(StatusDescription);
}
int emptyPadLength = barWidth + PSStyle.Instance.Reverse.Length - sb.Length - secRemainLength;
if (emptyPadLength > 0)
{
sb.Append(string.Empty.PadRight(emptyPadLength));
}
sb.Append(secRemain);
if (PercentComplete > 0 && PercentComplete < 100 && barWidth > 0)
{
int barLength = PercentComplete * barWidth / 100;
if (barLength >= barWidth)
{
barLength = barWidth - 1;
}
if (barLength < sb.Length)
{
sb.Insert(barLength + PSStyle.Instance.Reverse.Length, PSStyle.Instance.ReverseOff);
}
}
else
{
sb.Append(PSStyle.Instance.ReverseOff);
}
strCollection.Add(
StringUtil.Format(
"{0}{1}{2} [{3}]{4}",
indent,
PSStyle.Instance.Progress.Style,
activity,
sb.ToString(),
PSStyle.Instance.Reset)
.PadRight(padding));
}
/// <summary>
/// The nodes that have this node as their parent.
/// </summary>
internal
ArrayList
Children;
/// <summary>
/// The "age" of the node. A node's age is incremented by PendingProgress.Update each time a new ProgressRecord is
/// received by the host. A node's age is reset when a corresponding ProgressRecord is received. Thus, the age of
/// a node reflects the number of ProgressRecord that have been received since the node was last updated.
///
/// The age is used by PendingProgress.Render to determine which nodes should be rendered on the display, and how. As the
/// display has finite size, it may be possible to have many more outstanding progress activities than will fit in that
/// space. The rendering of nodes can be progressively "compressed" into a more terse format, or not rendered at all in
/// order to fit as many nodes as possible in the available space. The oldest nodes are compressed or skipped first.
/// </summary>
internal
int
Age;
/// <summary>
/// The style in which this node should be rendered.
/// </summary>
internal
RenderStyle
Style = RenderStyle.FullPlus;
/// <summary>
/// Identifies the source of the progress record.
/// </summary>
internal
long
SourceId;
/// <summary>
/// The number of vertical BufferCells that are required to render the node in its current style.
/// </summary>
/// <value></value>
internal int LinesRequiredMethod(PSHostRawUserInterface rawUi, int maxWidth)
{
Dbg.Assert(this.RecordType != ProgressRecordType.Completed, "should never render completed records");
switch (Style)
{
case RenderStyle.FullPlus:
return LinesRequiredInFullStyleMethod(rawUi, maxWidth, isFullPlus: true);
case RenderStyle.Full:
return LinesRequiredInFullStyleMethod(rawUi, maxWidth, isFullPlus: false);
case RenderStyle.Compact:
return LinesRequiredInCompactStyle;
case RenderStyle.Minimal:
return 1;
case RenderStyle.Invisible:
return 0;
case RenderStyle.Ansi:
return 1;
default:
Dbg.Assert(false, "Unknown RenderStyle value");
break;
}
return 0;
}
/// <summary>
/// The number of vertical BufferCells that are required to render the node in the Full style.
/// </summary>
/// <value></value>
private int LinesRequiredInFullStyleMethod(PSHostRawUserInterface rawUi, int maxWidth, bool isFullPlus)
{
// Since the fields of this instance could have been changed, we compute this on-the-fly.
// NTRAID#Windows OS Bugs-1062104-2004/12/15-sburns we assume 1 line for each field. If we ever need to
// word-wrap text fields, then this calculation will need updating.
// Start with 1 for the Activity
int lines = 1;
// Use 5 spaces as the heuristic indent. 5 spaces stand for the indent for the CurrentOperation of the first-level child node
var indent = StringUtil.Padding(5);
var temp = new ArrayList();
if (isFullPlus)
{
temp.Clear();
RenderFullDescription(StatusDescription, indent, maxWidth, rawUi, temp, isFullPlus: true);
lines += temp.Count;
}
else
{
// 1 for the Status
lines++;
}
if (PercentComplete >= 0)
{
++lines;
}
if (SecondsRemaining >= 0)
{
++lines;
}
if (!string.IsNullOrEmpty(CurrentOperation))
{
if (isFullPlus)
{
lines += 1;
temp.Clear();
RenderFullDescription(CurrentOperation, indent, maxWidth, rawUi, temp, isFullPlus: true);
lines += temp.Count;
}
else
{
lines += 2;
}
}
return lines;
}
/// <summary>
/// The number of vertical BufferCells that are required to render the node in the Compact style.
/// </summary>
/// <value></value>
private
int
LinesRequiredInCompactStyle
{
get
{
// Since the fields of this instance could have been changed, we compute this on-the-fly.
// NTRAID#Windows OS Bugs-1062104-2004/12/15-sburns we assume 1 line for each field. If we ever need to
// word-wrap text fields, then this calculation will need updating.
// Start with 1 for the Activity, and 1 for the Status.
int lines = 2;
if (!string.IsNullOrEmpty(CurrentOperation))
{
++lines;
}
return lines;
}
}
}
} // namespace
| |
// 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.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Reflection.Runtime.General;
using System.Reflection.Runtime.MethodInfos;
using Internal.Reflection.Core.Execution;
using Internal.Reflection.Tracing;
using Internal.Reflection.Augments;
using IRuntimeImplementedType = Internal.Reflection.Core.NonPortable.IRuntimeImplementedType;
using StructLayoutAttribute = System.Runtime.InteropServices.StructLayoutAttribute;
namespace System.Reflection.Runtime.TypeInfos
{
//
// Abstract base class for all TypeInfo's implemented by the runtime.
//
// This base class performs several services:
//
// - Provides default implementations whenever possible. Some of these
// return the "common" error result for narrowly applicable properties (such as those
// that apply only to generic parameters.)
//
// - Inverts the DeclaredMembers/DeclaredX relationship (DeclaredMembers is auto-implemented, others
// are overriden as abstract. This ordering makes more sense when reading from metadata.)
//
// - Overrides many "NotImplemented" members in TypeInfo with abstracts so failure to implement
// shows up as build error.
//
[Serializable]
[DebuggerDisplay("{_debugName}")]
internal abstract partial class RuntimeTypeInfo : TypeInfo, ISerializable, ITraceableTypeMember, ICloneable, IRuntimeImplementedType
{
protected RuntimeTypeInfo()
{
}
public abstract override bool IsTypeDefinition { get; }
public abstract override bool IsGenericTypeDefinition { get; }
protected abstract override bool HasElementTypeImpl();
protected abstract override bool IsArrayImpl();
public abstract override bool IsSZArray { get; }
public abstract override bool IsVariableBoundArray { get; }
protected abstract override bool IsByRefImpl();
protected abstract override bool IsPointerImpl();
public abstract override bool IsGenericParameter { get; }
public abstract override bool IsConstructedGenericType { get; }
public abstract override Assembly Assembly { get; }
public sealed override string AssemblyQualifiedName
{
get
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.TypeInfo_AssemblyQualifiedName(this);
#endif
string fullName = FullName;
if (fullName == null) // Some Types (such as generic parameters) return null for FullName by design.
return null;
string assemblyName = InternalFullNameOfAssembly;
return fullName + ", " + assemblyName;
}
}
public sealed override Type AsType()
{
return this;
}
public sealed override Type BaseType
{
get
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.TypeInfo_BaseType(this);
#endif
// If this has a RuntimeTypeHandle, let the underlying runtime engine have the first crack. If it refuses, fall back to metadata.
RuntimeTypeHandle typeHandle = InternalTypeHandleIfAvailable;
if (!typeHandle.IsNull())
{
RuntimeTypeHandle baseTypeHandle;
if (ReflectionCoreExecution.ExecutionEnvironment.TryGetBaseType(typeHandle, out baseTypeHandle))
return Type.GetTypeFromHandle(baseTypeHandle);
}
Type baseType = BaseTypeWithoutTheGenericParameterQuirk;
if (baseType != null && baseType.IsGenericParameter)
{
// Desktop quirk: a generic parameter whose constraint is another generic parameter reports its BaseType as System.Object
// unless that other generic parameter has a "class" constraint.
GenericParameterAttributes genericParameterAttributes = baseType.GenericParameterAttributes;
if (0 == (genericParameterAttributes & GenericParameterAttributes.ReferenceTypeConstraint))
baseType = CommonRuntimeTypes.Object;
}
return baseType;
}
}
public abstract override bool ContainsGenericParameters { get; }
//
// Left unsealed so that RuntimeNamedTypeInfo and RuntimeConstructedGenericTypeInfo and RuntimeGenericParameterTypeInfo can override.
//
public override IEnumerable<CustomAttributeData> CustomAttributes
{
get
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.TypeInfo_CustomAttributes(this);
#endif
Debug.Assert(IsArray || IsByRef || IsPointer);
return Empty<CustomAttributeData>.Enumerable;
}
}
//
// Left unsealed as generic parameter types must override.
//
public override MethodBase DeclaringMethod
{
get
{
Debug.Assert(!IsGenericParameter);
throw new InvalidOperationException(SR.Arg_NotGenericParameter);
}
}
//
// Equals()/GetHashCode()
//
// RuntimeTypeInfo objects are interned to preserve the app-compat rule that Type objects (which are the same as TypeInfo objects)
// can be compared using reference equality.
//
// We use weak pointers to intern the objects. This means we can use instance equality to implement Equals() but we cannot use
// the instance hashcode to implement GetHashCode() (otherwise, the hash code will not be stable if the TypeInfo is released and recreated.)
// Thus, we override and seal Equals() here but defer to a flavor-specific hash code implementation.
//
public sealed override bool Equals(object obj)
{
return object.ReferenceEquals(this, obj);
}
public sealed override bool Equals(Type o)
{
return object.ReferenceEquals(this, o);
}
public sealed override int GetHashCode()
{
return InternalGetHashCode();
}
public abstract override string FullName { get; }
//
// Left unsealed as generic parameter types must override.
//
public override GenericParameterAttributes GenericParameterAttributes
{
get
{
Debug.Assert(!IsGenericParameter);
throw new InvalidOperationException(SR.Arg_NotGenericParameter);
}
}
//
// Left unsealed as generic parameter types must override this.
//
public override int GenericParameterPosition
{
get
{
Debug.Assert(!IsGenericParameter);
throw new InvalidOperationException(SR.Arg_NotGenericParameter);
}
}
public sealed override Type[] GenericTypeArguments
{
get
{
return InternalRuntimeGenericTypeArguments.CloneTypeArray();
}
}
public sealed override MemberInfo[] GetDefaultMembers()
{
string defaultMemberName = GetDefaultMemberName();
return defaultMemberName != null ? GetMember(defaultMemberName) : Array.Empty<MemberInfo>();
}
public sealed override InterfaceMapping GetInterfaceMap(Type interfaceType)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_InterfaceMap);
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException(nameof(info));
UnitySerializationHolder.GetUnitySerializationInfo(info, this);
}
//
// Implements the correct GUID behavior for all "constructed" types (i.e. returning an all-zero GUID.) Left unsealed
// so that RuntimeNamedTypeInfo can override.
//
public override Guid GUID
{
get
{
return Guid.Empty;
}
}
public sealed override IEnumerable<Type> ImplementedInterfaces
{
get
{
LowLevelListWithIList<Type> result = new LowLevelListWithIList<Type>();
bool done = false;
// If this has a RuntimeTypeHandle, let the underlying runtime engine have the first crack. If it refuses, fall back to metadata.
RuntimeTypeHandle typeHandle = InternalTypeHandleIfAvailable;
if (!typeHandle.IsNull())
{
IEnumerable<RuntimeTypeHandle> implementedInterfaces = ReflectionCoreExecution.ExecutionEnvironment.TryGetImplementedInterfaces(typeHandle);
if (implementedInterfaces != null)
{
done = true;
foreach (RuntimeTypeHandle th in implementedInterfaces)
{
result.Add(Type.GetTypeFromHandle(th));
}
}
}
if (!done)
{
TypeContext typeContext = this.TypeContext;
Type baseType = this.BaseTypeWithoutTheGenericParameterQuirk;
if (baseType != null)
result.AddRange(baseType.GetInterfaces());
foreach (QTypeDefRefOrSpec directlyImplementedInterface in this.TypeRefDefOrSpecsForDirectlyImplementedInterfaces)
{
Type ifc = directlyImplementedInterface.Resolve(typeContext);
if (result.Contains(ifc))
continue;
result.Add(ifc);
foreach (Type indirectIfc in ifc.GetInterfaces())
{
if (result.Contains(indirectIfc))
continue;
result.Add(indirectIfc);
}
}
}
return result.AsNothingButIEnumerable();
}
}
public sealed override bool IsAssignableFrom(TypeInfo typeInfo) => IsAssignableFrom((Type)typeInfo);
public sealed override bool IsAssignableFrom(Type c)
{
if (c == null)
return false;
if (object.ReferenceEquals(c, this))
return true;
c = c.UnderlyingSystemType;
Type typeInfo = c;
RuntimeTypeInfo toTypeInfo = this;
if (typeInfo == null || !typeInfo.IsRuntimeImplemented())
return false; // Desktop compat: If typeInfo is null, or implemented by a different Reflection implementation, return "false."
RuntimeTypeInfo fromTypeInfo = typeInfo.CastToRuntimeTypeInfo();
if (toTypeInfo.Equals(fromTypeInfo))
return true;
RuntimeTypeHandle toTypeHandle = toTypeInfo.InternalTypeHandleIfAvailable;
RuntimeTypeHandle fromTypeHandle = fromTypeInfo.InternalTypeHandleIfAvailable;
bool haveTypeHandles = !(toTypeHandle.IsNull() || fromTypeHandle.IsNull());
if (haveTypeHandles)
{
// If both types have type handles, let MRT handle this. It's not dependent on metadata.
if (ReflectionCoreExecution.ExecutionEnvironment.IsAssignableFrom(toTypeHandle, fromTypeHandle))
return true;
// Runtime IsAssignableFrom does not handle casts from generic type definitions: always returns false. For those, we fall through to the
// managed implementation. For everyone else, return "false".
//
// Runtime IsAssignableFrom does not handle pointer -> UIntPtr cast.
if (!(fromTypeInfo.IsGenericTypeDefinition || fromTypeInfo.IsPointer))
return false;
}
// If we got here, the types are open, or reduced away, or otherwise lacking in type handles. Perform the IsAssignability check in managed code.
return Assignability.IsAssignableFrom(this, typeInfo);
}
public sealed override bool IsEnum
{
get
{
return 0 != (Classification & TypeClassification.IsEnum);
}
}
public sealed override MemberTypes MemberType
{
get
{
if (IsPublic || IsNotPublic)
return MemberTypes.TypeInfo;
else
return MemberTypes.NestedType;
}
}
//
// Left unsealed as there are so many subclasses. Need to be overriden by EcmaFormatRuntimeNamedTypeInfo and RuntimeConstructedGenericTypeInfo
//
public abstract override int MetadataToken
{
get;
}
public sealed override Module Module
{
get
{
return Assembly.ManifestModule;
}
}
public abstract override string Namespace { get; }
public sealed override Type[] GenericTypeParameters
{
get
{
return RuntimeGenericTypeParameters.CloneTypeArray();
}
}
//
// Left unsealed as array types must override this.
//
public override int GetArrayRank()
{
Debug.Assert(!IsArray);
throw new ArgumentException(SR.Argument_HasToBeArrayClass);
}
public sealed override Type GetElementType()
{
return InternalRuntimeElementType;
}
//
// Left unsealed as generic parameter types must override.
//
public override Type[] GetGenericParameterConstraints()
{
Debug.Assert(!IsGenericParameter);
throw new InvalidOperationException(SR.Arg_NotGenericParameter);
}
//
// Left unsealed as IsGenericType types must override this.
//
public override Type GetGenericTypeDefinition()
{
Debug.Assert(!IsGenericType);
throw new InvalidOperationException(SR.InvalidOperation_NotGenericType);
}
public sealed override Type MakeArrayType()
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.TypeInfo_MakeArrayType(this);
#endif
// Do not implement this as a call to MakeArrayType(1) - they are not interchangable. MakeArrayType() returns a
// vector type ("SZArray") while MakeArrayType(1) returns a multidim array of rank 1. These are distinct types
// in the ECMA model and in CLR Reflection.
return this.GetArrayType();
}
public sealed override Type MakeArrayType(int rank)
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.TypeInfo_MakeArrayType(this, rank);
#endif
if (rank <= 0)
throw new IndexOutOfRangeException();
return this.GetMultiDimArrayType(rank);
}
public sealed override Type MakeByRefType()
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.TypeInfo_MakeByRefType(this);
#endif
return this.GetByRefType();
}
public sealed override Type MakeGenericType(params Type[] typeArguments)
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.TypeInfo_MakeGenericType(this, typeArguments);
#endif
if (typeArguments == null)
throw new ArgumentNullException(nameof(typeArguments));
if (!IsGenericTypeDefinition)
throw new InvalidOperationException(SR.Format(SR.Arg_NotGenericTypeDefinition, this));
// We intentionally don't validate the number of arguments or their suitability to the generic type's constraints.
// In a pay-for-play world, this can cause needless MissingMetadataExceptions. There is no harm in creating
// the Type object for an inconsistent generic type - no EEType will ever match it so any attempt to "invoke" it
// will throw an exception.
RuntimeTypeInfo[] runtimeTypeArguments = new RuntimeTypeInfo[typeArguments.Length];
for (int i = 0; i < typeArguments.Length; i++)
{
RuntimeTypeInfo runtimeTypeArgument = typeArguments[i] as RuntimeTypeInfo;
if (runtimeTypeArgument == null)
{
if (typeArguments[i] == null)
throw new ArgumentNullException();
else
throw new PlatformNotSupportedException(SR.PlatformNotSupported_MakeGenericType); // "PlatformNotSupported" because on desktop, passing in a foreign type is allowed and creates a RefEmit.TypeBuilder
}
// Desktop compatibility: Treat generic type definitions as a constructed generic type using the generic parameters as type arguments.
if (runtimeTypeArgument.IsGenericTypeDefinition)
runtimeTypeArgument = runtimeTypeArgument.GetConstructedGenericType(runtimeTypeArgument.RuntimeGenericTypeParameters);
runtimeTypeArguments[i] = runtimeTypeArgument;
}
return this.GetConstructedGenericType(runtimeTypeArguments);
}
public sealed override Type MakePointerType()
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.TypeInfo_MakePointerType(this);
#endif
return this.GetPointerType();
}
public sealed override Type DeclaringType
{
get
{
return this.InternalDeclaringType;
}
}
public sealed override string Name
{
get
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.TypeInfo_Name(this);
#endif
Type rootCauseForFailure = null;
string name = InternalGetNameIfAvailable(ref rootCauseForFailure);
if (name == null)
throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(rootCauseForFailure);
return name;
}
}
public sealed override Type ReflectedType
{
get
{
// Desktop compat: For types, ReflectedType == DeclaringType. Nested types are always looked up as BindingFlags.DeclaredOnly was passed.
// For non-nested types, the concept of a ReflectedType doesn't even make sense.
return DeclaringType;
}
}
public abstract override StructLayoutAttribute StructLayoutAttribute { get; }
public abstract override string ToString();
public sealed override RuntimeTypeHandle TypeHandle
{
get
{
RuntimeTypeHandle typeHandle = InternalTypeHandleIfAvailable;
if (!typeHandle.IsNull())
return typeHandle;
// If a constructed type doesn't have an type handle, it's either because the reducer tossed it (in which case,
// we would thrown a MissingMetadataException when attempting to construct the type) or because one of
// component types contains open type parameters. Since we eliminated the first case, it must be the second.
// Throwing PlatformNotSupported since the desktop does, in fact, create type handles for open types.
if (HasElementType || IsConstructedGenericType || IsGenericParameter)
throw new PlatformNotSupportedException(SR.PlatformNotSupported_NoTypeHandleForOpenTypes);
// If got here, this is a "plain old type" that has metadata but no type handle. We can get here if the only
// representation of the type is in the native metadata and there's no EEType at the runtime side.
// If you squint hard, this is a missing metadata situation - the metadata is missing on the runtime side - and
// the action for the user to take is the same: go mess with RD.XML.
throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this);
}
}
public sealed override Type UnderlyingSystemType
{
get
{
return this;
}
}
protected abstract override TypeAttributes GetAttributeFlagsImpl();
protected sealed override TypeCode GetTypeCodeImpl()
{
return ReflectionAugments.GetRuntimeTypeCode(this);
}
protected abstract int InternalGetHashCode();
protected sealed override bool IsCOMObjectImpl()
{
return ReflectionCoreExecution.ExecutionEnvironment.IsCOMObject(this);
}
protected sealed override bool IsPrimitiveImpl()
{
return 0 != (Classification & TypeClassification.IsPrimitive);
}
protected sealed override bool IsValueTypeImpl()
{
return 0 != (Classification & TypeClassification.IsValueType);
}
String ITraceableTypeMember.MemberName
{
get
{
string name = InternalNameIfAvailable;
return name ?? string.Empty;
}
}
Type ITraceableTypeMember.ContainingType
{
get
{
return this.InternalDeclaringType;
}
}
//
// Returns the anchoring typedef that declares the members that this type wants returned by the Declared*** properties.
// The Declared*** properties will project the anchoring typedef's members by overriding their DeclaringType property with "this"
// and substituting the value of this.TypeContext into any generic parameters.
//
// Default implementation returns null which causes the Declared*** properties to return no members.
//
// Note that this does not apply to DeclaredNestedTypes. Nested types and their containers have completely separate generic instantiation environments
// (despite what C# might lead you to think.) Constructed generic types return the exact same same nested types that its generic type definition does
// - i.e. their DeclaringTypes refer back to the generic type definition, not the constructed generic type.)
//
// Note also that we cannot use this anchoring concept for base types because of generic parameters. Generic parameters return
// a base class and interface list based on its constraints.
//
internal virtual RuntimeNamedTypeInfo AnchoringTypeDefinitionForDeclaredMembers
{
get
{
return null;
}
}
internal abstract Type InternalDeclaringType { get; }
//
// Return the full name of the "defining assembly" for the purpose of computing TypeInfo.AssemblyQualifiedName;
//
internal abstract string InternalFullNameOfAssembly { get; }
public abstract override string InternalGetNameIfAvailable(ref Type rootCauseForFailure);
//
// Left unsealed as HasElement types must override this.
//
internal virtual RuntimeTypeInfo InternalRuntimeElementType
{
get
{
Debug.Assert(!HasElementType);
return null;
}
}
//
// Left unsealed as constructed generic types must override this.
//
internal virtual RuntimeTypeInfo[] InternalRuntimeGenericTypeArguments
{
get
{
Debug.Assert(!IsConstructedGenericType);
return Array.Empty<RuntimeTypeInfo>();
}
}
internal abstract RuntimeTypeHandle InternalTypeHandleIfAvailable { get; }
internal bool IsDelegate
{
get
{
return 0 != (Classification & TypeClassification.IsDelegate);
}
}
//
// Returns true if it's possible to ask for a list of members and the base type without triggering a MissingMetadataException.
//
internal abstract bool CanBrowseWithoutMissingMetadataExceptions { get; }
//
// The non-public version of TypeInfo.GenericTypeParameters (does not array-copy.)
//
internal virtual RuntimeTypeInfo[] RuntimeGenericTypeParameters
{
get
{
Debug.Assert(!(this is RuntimeNamedTypeInfo));
return Array.Empty<RuntimeTypeInfo>();
}
}
//
// Normally returns empty: Overridden by array types to return constructors.
//
internal virtual IEnumerable<RuntimeConstructorInfo> SyntheticConstructors
{
get
{
return Empty<RuntimeConstructorInfo>.Enumerable;
}
}
//
// Normally returns empty: Overridden by array types to return the "Get" and "Set" methods.
//
internal virtual IEnumerable<RuntimeMethodInfo> SyntheticMethods
{
get
{
return Empty<RuntimeMethodInfo>.Enumerable;
}
}
//
// Returns the base type as a typeDef, Ref, or Spec. Default behavior is to QTypeDefRefOrSpec.Null, which causes BaseType to return null.
//
// If you override this method, there is no need to override BaseTypeWithoutTheGenericParameterQuirk.
//
internal virtual QTypeDefRefOrSpec TypeRefDefOrSpecForBaseType
{
get
{
return QTypeDefRefOrSpec.Null;
}
}
//
// Returns the *directly implemented* interfaces as typedefs, specs or refs. ImplementedInterfaces will take care of the transitive closure and
// insertion of the TypeContext.
//
internal virtual QTypeDefRefOrSpec[] TypeRefDefOrSpecsForDirectlyImplementedInterfaces
{
get
{
return Array.Empty<QTypeDefRefOrSpec>();
}
}
//
// Returns the generic parameter substitutions to use when enumerating declared members, base class and implemented interfaces.
//
internal virtual TypeContext TypeContext
{
get
{
return new TypeContext(null, null);
}
}
//
// Note: This can be (and is) called multiple times. We do not do this work in the constructor as calling ToString()
// in the constructor causes some serious recursion issues.
//
internal void EstablishDebugName()
{
bool populateDebugNames = DeveloperExperienceState.DeveloperExperienceModeEnabled;
#if DEBUG
populateDebugNames = true;
#endif
if (!populateDebugNames)
return;
if (_debugName == null)
{
_debugName = "Constructing..."; // Protect against any inadvertent reentrancy.
String debugName;
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
debugName = this.GetTraceString(); // If tracing on, call this.GetTraceString() which only gives you useful strings when metadata is available but doesn't pollute the ETW trace.
else
#endif
debugName = this.ToString();
if (debugName == null)
debugName = "";
_debugName = debugName;
}
return;
}
//
// This internal method implements BaseType without the following desktop quirk:
//
// class Foo<X,Y>
// where X:Y
// where Y:MyReferenceClass
//
// The desktop reports "X"'s base type as "System.Object" rather than "Y", even though it does
// report any interfaces that are in MyReferenceClass's interface list.
//
// This seriously messes up the implementation of RuntimeTypeInfo.ImplementedInterfaces which assumes
// that it can recover the transitive interface closure by combining the directly mentioned interfaces and
// the BaseType's own interface closure.
//
// To implement this with the least amount of code smell, we'll implement the idealized version of BaseType here
// and make the special-case adjustment in the public version of BaseType.
//
// If you override this method, there is no need to overrride TypeRefDefOrSpecForBaseType.
//
// This method is left unsealed so that RuntimeCLSIDTypeInfo can override.
//
internal virtual Type BaseTypeWithoutTheGenericParameterQuirk
{
get
{
QTypeDefRefOrSpec baseTypeDefRefOrSpec = TypeRefDefOrSpecForBaseType;
RuntimeTypeInfo baseType = null;
if (!baseTypeDefRefOrSpec.IsValid)
{
baseType = baseTypeDefRefOrSpec.Resolve(this.TypeContext);
}
return baseType;
}
}
private string GetDefaultMemberName()
{
Type defaultMemberAttributeType = typeof(DefaultMemberAttribute);
for (Type type = this; type != null; type = type.BaseType)
{
foreach (CustomAttributeData attribute in type.CustomAttributes)
{
if (attribute.AttributeType == defaultMemberAttributeType)
{
// NOTE: Neither indexing nor cast can fail here. Any attempt to use fewer than 1 argument
// or a non-string argument would correctly trigger MissingMethodException before
// we reach here as that would be an attempt to reference a non-existent DefaultMemberAttribute
// constructor.
Debug.Assert(attribute.ConstructorArguments.Count == 1 && attribute.ConstructorArguments[0].Value is string);
string memberName = (string)(attribute.ConstructorArguments[0].Value);
return memberName;
}
}
}
return null;
}
//
// Returns a latched set of flags indicating the value of IsValueType, IsEnum, etc.
//
private TypeClassification Classification
{
get
{
if (_lazyClassification == 0)
{
TypeClassification classification = TypeClassification.Computed;
Type baseType = this.BaseType;
if (baseType != null)
{
Type enumType = CommonRuntimeTypes.Enum;
Type valueType = CommonRuntimeTypes.ValueType;
if (baseType.Equals(enumType))
classification |= TypeClassification.IsEnum | TypeClassification.IsValueType;
if (baseType.Equals(CommonRuntimeTypes.MulticastDelegate))
classification |= TypeClassification.IsDelegate;
if (baseType.Equals(valueType) && !(this.Equals(enumType)))
{
classification |= TypeClassification.IsValueType;
foreach (Type primitiveType in ReflectionCoreExecution.ExecutionDomain.PrimitiveTypes)
{
if (this.Equals(primitiveType))
{
classification |= TypeClassification.IsPrimitive;
break;
}
}
}
}
_lazyClassification = classification;
}
return _lazyClassification;
}
}
[Flags]
private enum TypeClassification
{
Computed = 0x00000001, // Always set (to indicate that the lazy evaluation has occurred)
IsValueType = 0x00000002,
IsEnum = 0x00000004,
IsPrimitive = 0x00000008,
IsDelegate = 0x00000010,
}
object ICloneable.Clone()
{
return this;
}
private volatile TypeClassification _lazyClassification;
private String _debugName;
}
}
| |
/*
* CP57002.cs - ISCII code pages 57002-57011.
*
* Copyright (c) 2002 Southern Storm Software, Pty Ltd
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace I18N.Other
{
using System;
using System.Text;
using I18N.Common;
// This class provides an abstract base for the ISCII encodings,
// which all have a similar pattern. Code points 0x00-0x7F are
// the standard ASCII character set, and code points 0x80-0xFF
// are a shifted version of the Unicode character set, starting
// at a fixed offset.
public abstract class ISCIIEncoding : Encoding
{
// Internal state.
protected int shift;
protected String encodingName;
protected String webName;
// Constructor.
protected ISCIIEncoding(int codePage, int shift,
String encodingName, String webName)
: base(codePage)
{
this.shift = shift;
this.encodingName = encodingName;
this.webName = webName;
}
// Get the number of bytes needed to encode a character buffer.
public override int GetByteCount(char[] chars, int index, int count)
{
if(chars == null)
{
throw new ArgumentNullException("chars");
}
if(index < 0 || index > chars.Length)
{
throw new ArgumentOutOfRangeException
("index", Strings.GetString("ArgRange_Array"));
}
if(count < 0 || count > (chars.Length - index))
{
throw new ArgumentOutOfRangeException
("count", Strings.GetString("ArgRange_Array"));
}
return count;
}
// Convenience wrappers for "GetByteCount".
public override int GetByteCount(String s)
{
if(s == null)
{
throw new ArgumentNullException("s");
}
return s.Length;
}
// Get the bytes that result from encoding a character buffer.
public override int GetBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
if(chars == null)
{
throw new ArgumentNullException("chars");
}
if(bytes == null)
{
throw new ArgumentNullException("bytes");
}
if(charIndex < 0 || charIndex > chars.Length)
{
throw new ArgumentOutOfRangeException
("charIndex", Strings.GetString("ArgRange_Array"));
}
if(charCount < 0 || charCount > (chars.Length - charIndex))
{
throw new ArgumentOutOfRangeException
("charCount", Strings.GetString("ArgRange_Array"));
}
if(byteIndex < 0 || byteIndex > bytes.Length)
{
throw new ArgumentOutOfRangeException
("byteIndex", Strings.GetString("ArgRange_Array"));
}
if((bytes.Length - byteIndex) < charCount)
{
throw new ArgumentException
(Strings.GetString("Arg_InsufficientSpace"), "bytes");
}
// Convert the characters into bytes.
char ch;
int posn = byteIndex;
char first = (char)shift;
char last = (char)(shift + 0x7F);
while(charCount-- > 0)
{
ch = chars[charIndex++];
if(ch < (char)0x0080)
{
// Regular ASCII subset.
bytes[posn++] = (byte)ch;
}
else if(ch >= first && ch <= last)
{
// ISCII range that we need to shift.
bytes[posn++] = (byte)(ch - first + 0x80);
}
else if(ch >= '\uFF01' && ch <= '\uFF5E')
{
// ASCII full-width characters.
bytes[posn++] = (byte)(ch - 0xFEE0);
}
else
{
bytes[posn++] = (byte)'?';
}
}
// Return the final length of the output.
return posn - byteIndex;
}
// Convenience wrappers for "GetBytes".
public override int GetBytes(String s, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
// Validate the parameters.
if(s == null)
{
throw new ArgumentNullException("s");
}
if(bytes == null)
{
throw new ArgumentNullException("bytes");
}
if(charIndex < 0 || charIndex > s.Length)
{
throw new ArgumentOutOfRangeException
("charIndex",
Strings.GetString("ArgRange_StringIndex"));
}
if(charCount < 0 || charCount > (s.Length - charIndex))
{
throw new ArgumentOutOfRangeException
("charCount",
Strings.GetString("ArgRange_StringRange"));
}
if(byteIndex < 0 || byteIndex > bytes.Length)
{
throw new ArgumentOutOfRangeException
("byteIndex",
Strings.GetString("ArgRange_Array"));
}
if((bytes.Length - byteIndex) < charCount)
{
throw new ArgumentException
(Strings.GetString("Arg_InsufficientSpace"), "bytes");
}
// Convert the characters into bytes.
char ch;
int posn = byteIndex;
char first = (char)shift;
char last = (char)(shift + 0x7F);
while(charCount-- > 0)
{
ch = s[charIndex++];
if(ch < (char)0x0080)
{
// Regular ASCII subset.
bytes[posn++] = (byte)ch;
}
else if(ch >= first && ch <= last)
{
// ISCII range that we need to shift.
bytes[posn++] = (byte)(ch - first + 0x80);
}
else if(ch >= '\uFF01' && ch <= '\uFF5E')
{
// ASCII full-width characters.
bytes[posn++] = (byte)(ch - 0xFEE0);
}
else
{
bytes[posn++] = (byte)'?';
}
}
// Return the final length of the output.
return posn - byteIndex;
}
// Get the number of characters needed to decode a byte buffer.
public override int GetCharCount(byte[] bytes, int index, int count)
{
if(bytes == null)
{
throw new ArgumentNullException("bytes");
}
if(index < 0 || index > bytes.Length)
{
throw new ArgumentOutOfRangeException
("index", Strings.GetString("ArgRange_Array"));
}
if(count < 0 || count > (bytes.Length - index))
{
throw new ArgumentOutOfRangeException
("count", Strings.GetString("ArgRange_Array"));
}
return count;
}
// Get the characters that result from decoding a byte buffer.
public override int GetChars(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex)
{
// Validate the parameters.
if(bytes == null)
{
throw new ArgumentNullException("bytes");
}
if(chars == null)
{
throw new ArgumentNullException("chars");
}
if(byteIndex < 0 || byteIndex > bytes.Length)
{
throw new ArgumentOutOfRangeException
("byteIndex", Strings.GetString("ArgRange_Array"));
}
if(byteCount < 0 || byteCount > (bytes.Length - byteIndex))
{
throw new ArgumentOutOfRangeException
("byteCount", Strings.GetString("ArgRange_Array"));
}
if(charIndex < 0 || charIndex > chars.Length)
{
throw new ArgumentOutOfRangeException
("charIndex", Strings.GetString("ArgRange_Array"));
}
if((chars.Length - charIndex) < byteCount)
{
throw new ArgumentException
(Strings.GetString("Arg_InsufficientSpace"), "chars");
}
// Convert the bytes into characters.
int count = byteCount;
int byteval;
int shift = this.shift - 0x80;
while(count-- > 0)
{
byteval = (int)(bytes[byteIndex++]);
if(byteval < 0x80)
{
// Ordinary ASCII character.
chars[charIndex++] = (char)byteval;
}
else
{
// Shift the ISCII character into the Unicode page.
chars[charIndex++] = (char)(byteval + shift);
}
}
return byteCount;
}
// Get the maximum number of bytes needed to encode a
// specified number of characters.
public override int GetMaxByteCount(int charCount)
{
if(charCount < 0)
{
throw new ArgumentOutOfRangeException
("charCount",
Strings.GetString("ArgRange_NonNegative"));
}
return charCount;
}
// Get the maximum number of characters needed to decode a
// specified number of bytes.
public override int GetMaxCharCount(int byteCount)
{
if(byteCount < 0)
{
throw new ArgumentOutOfRangeException
("byteCount",
Strings.GetString("ArgRange_NonNegative"));
}
return byteCount;
}
#if !ECMA_COMPAT
// Get the mail body name for this encoding.
public override String BodyName
{
get
{
return webName;
}
}
// Get the human-readable name for this encoding.
public override String EncodingName
{
get
{
return encodingName;
}
}
// Get the mail agent header name for this encoding.
public override String HeaderName
{
get
{
return webName;
}
}
// Get the IANA-preferred Web name for this encoding.
public override String WebName
{
get
{
return webName;
}
}
#endif // !ECMA_COMPAT
}; // class ISCIIEncoding
// Define the ISCII code pages as subclasses of "ISCIIEncoding".
public class CP57002 : ISCIIEncoding
{
public CP57002() : base(57002, 0x0900, "ISCII Devanagari", "x-iscii-de") {}
}; // class CP57002
public class CP57003 : ISCIIEncoding
{
public CP57003() : base(57003, 0x0980, "ISCII Bengali", "x-iscii-be") {}
}; // class CP57003
public class CP57004 : ISCIIEncoding
{
public CP57004() : base(57004, 0x0B80, "ISCII Tamil", "x-iscii-ta") {}
}; // class CP57004
public class CP57005 : ISCIIEncoding
{
public CP57005() : base(57005, 0x0B80, "ISCII Telugu", "x-iscii-te") {}
}; // class CP57005
public class CP57006 : ISCIIEncoding
{
// Note: Unicode has a "Sinhala" page, but no "Assamese" page.
// Until I hear otherwise, I will assume that they are the same
// thing with different names - Rhys Weatherley, 16 April 2002.
public CP57006() : base(57006, 0x0D80, "ISCII Assamese", "x-iscii-as") {}
}; // class CP57006
public class CP57007 : ISCIIEncoding
{
public CP57007() : base(57007, 0x0B00, "ISCII Oriya", "x-iscii-or") {}
}; // class CP57007
public class CP57008 : ISCIIEncoding
{
public CP57008() : base(57008, 0x0C80, "ISCII Kannada", "x-iscii-ka") {}
}; // class CP57008
public class CP57009 : ISCIIEncoding
{
public CP57009() : base(57009, 0x0D00, "ISCII Malayalam", "x-iscii-ma") {}
}; // class CP57009
public class CP57010 : ISCIIEncoding
{
public CP57010() : base(57010, 0x0A80, "ISCII Gujarati", "x-iscii-gu") {}
}; // class CP57010
public class CP57011 : ISCIIEncoding
{
// Note: Unicode has a "Gurmukhi" page, but no "Punjabi" page.
// Other ISCII-related information on the Internet seems to
// indicate that they are the same. Until I hear otherwise,
// I will assume that they are the same thing with different
// names - Rhys Weatherley, 16 April 2002.
public CP57011() : base(57011, 0x0A00, "ISCII Punjabi", "x-iscii-pa") {}
}; // class CP57011
// Define the web encoding name aliases for the above code pages.
public class ENCx_iscii_de : CP57002
{
public ENCx_iscii_de() : base() {}
}; // class ENCx_iscii_de
public class ENCx_iscii_be : CP57003
{
public ENCx_iscii_be() : base() {}
}; // class ENCx_iscii_be
public class ENCx_iscii_ta : CP57004
{
public ENCx_iscii_ta() : base() {}
}; // class ENCx_iscii_ta
public class ENCx_iscii_te : CP57005
{
public ENCx_iscii_te() : base() {}
}; // class ENCx_iscii_te
public class ENCx_iscii_as : CP57006
{
public ENCx_iscii_as() : base() {}
}; // class ENCx_iscii_as
public class ENCx_iscii_or : CP57007
{
public ENCx_iscii_or() : base() {}
}; // class ENCx_iscii_or
public class ENCx_iscii_ka : CP57008
{
public ENCx_iscii_ka() : base() {}
}; // class ENCx_iscii_ka
public class ENCx_iscii_ma : CP57009
{
public ENCx_iscii_ma() : base() {}
}; // class ENCx_iscii_ma
public class ENCx_iscii_gu : CP57010
{
public ENCx_iscii_gu() : base() {}
}; // class ENCx_iscii_gu
public class ENCx_iscii_pa : CP57011
{
public ENCx_iscii_pa() : base() {}
}; // class ENCx_iscii_pa
}; // namespace I18N.Other
| |
// 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.IO;
using Xunit;
namespace System.Net.NetworkInformation.Tests
{
public class StatisticsParsingTests : FileCleanupTestBase
{
[Fact]
public void Icmpv4Parsing()
{
string fileName = GetTestFilePath();
FileUtil.NormalizeLineEndings("NetworkFiles/snmp", fileName);
Icmpv4StatisticsTable table = StringParsingHelpers.ParseIcmpv4FromSnmpFile(fileName);
Assert.Equal(1, table.InMsgs);
Assert.Equal(2, table.InErrors);
Assert.Equal(3, table.InCsumErrors);
Assert.Equal(4, table.InDestUnreachs);
Assert.Equal(5, table.InTimeExcds);
Assert.Equal(6, table.InParmProbs);
Assert.Equal(7, table.InSrcQuenchs);
Assert.Equal(8, table.InRedirects);
Assert.Equal(9, table.InEchos);
Assert.Equal(10, table.InEchoReps);
Assert.Equal(20, table.InTimestamps);
Assert.Equal(30, table.InTimeStampReps);
Assert.Equal(40, table.InAddrMasks);
Assert.Equal(50, table.InAddrMaskReps);
Assert.Equal(60, table.OutMsgs);
Assert.Equal(70, table.OutErrors);
Assert.Equal(80, table.OutDestUnreachs);
Assert.Equal(90, table.OutTimeExcds);
Assert.Equal(100, table.OutParmProbs);
Assert.Equal(255, table.OutSrcQuenchs);
Assert.Equal(1024, table.OutRedirects);
Assert.Equal(256, table.OutEchos);
Assert.Equal(9001, table.OutEchoReps);
Assert.Equal(42, table.OutTimestamps);
Assert.Equal(4100414, table.OutTimestampReps);
Assert.Equal(2147483647, table.OutAddrMasks);
Assert.Equal(0, table.OutAddrMaskReps);
}
[Fact]
public void Icmpv6Parsing()
{
string fileName = GetTestFilePath();
FileUtil.NormalizeLineEndings("NetworkFiles/snmp6", fileName);
Icmpv6StatisticsTable table = StringParsingHelpers.ParseIcmpv6FromSnmp6File(fileName);
Assert.Equal(1, table.InMsgs);
Assert.Equal(2, table.InErrors);
Assert.Equal(3, table.OutMsgs);
Assert.Equal(4, table.OutErrors);
Assert.Equal(6, table.InDestUnreachs);
Assert.Equal(7, table.InPktTooBigs);
Assert.Equal(8, table.InTimeExcds);
Assert.Equal(9, table.InParmProblems);
Assert.Equal(10, table.InEchos);
Assert.Equal(11, table.InEchoReplies);
Assert.Equal(12, table.InGroupMembQueries);
Assert.Equal(13, table.InGroupMembResponses);
Assert.Equal(14, table.InGroupMembReductions);
Assert.Equal(15, table.InRouterSolicits);
Assert.Equal(16, table.InRouterAdvertisements);
Assert.Equal(17, table.InNeighborSolicits);
Assert.Equal(18, table.InNeighborAdvertisements);
Assert.Equal(19, table.InRedirects);
Assert.Equal(21, table.OutDestUnreachs);
Assert.Equal(22, table.OutPktTooBigs);
Assert.Equal(23, table.OutTimeExcds);
Assert.Equal(24, table.OutParmProblems);
Assert.Equal(25, table.OutEchos);
Assert.Equal(26, table.OutEchoReplies);
Assert.Equal(27, table.OutInGroupMembQueries);
Assert.Equal(28, table.OutGroupMembResponses);
Assert.Equal(29, table.OutGroupMembReductions);
Assert.Equal(30, table.OutRouterSolicits);
Assert.Equal(31, table.OutRouterAdvertisements);
Assert.Equal(32, table.OutNeighborSolicits);
Assert.Equal(33, table.OutNeighborAdvertisements);
Assert.Equal(34, table.OutRedirects);
}
[Fact]
public void TcpGlobalStatisticsParsing()
{
string fileName = GetTestFilePath();
FileUtil.NormalizeLineEndings("NetworkFiles/snmp", fileName);
TcpGlobalStatisticsTable table = StringParsingHelpers.ParseTcpGlobalStatisticsFromSnmpFile(fileName);
Assert.Equal(1, table.RtoAlgorithm);
Assert.Equal(200, table.RtoMin);
Assert.Equal(120000, table.RtoMax);
Assert.Equal(-1, table.MaxConn);
Assert.Equal(359, table.ActiveOpens);
Assert.Equal(28, table.PassiveOpens);
Assert.Equal(2, table.AttemptFails);
Assert.Equal(53, table.EstabResets);
Assert.Equal(4, table.CurrEstab);
Assert.Equal(21368, table.InSegs);
Assert.Equal(20642, table.OutSegs);
Assert.Equal(19, table.RetransSegs);
Assert.Equal(0, table.InErrs);
Assert.Equal(111, table.OutRsts);
Assert.Equal(0, table.InCsumErrors);
}
[Fact]
public void Udpv4GlobalStatisticsParsing()
{
string fileName = GetTestFilePath();
FileUtil.NormalizeLineEndings("NetworkFiles/snmp", fileName);
UdpGlobalStatisticsTable table = StringParsingHelpers.ParseUdpv4GlobalStatisticsFromSnmpFile(fileName);
Assert.Equal(7181, table.InDatagrams);
Assert.Equal(150, table.NoPorts);
Assert.Equal(0, table.InErrors);
Assert.Equal(4386, table.OutDatagrams);
Assert.Equal(0, table.RcvbufErrors);
Assert.Equal(0, table.SndbufErrors);
Assert.Equal(1, table.InCsumErrors);
}
[Fact]
public void Udpv6GlobalStatisticsParsing()
{
string fileName = GetTestFilePath();
FileUtil.NormalizeLineEndings("NetworkFiles/snmp6", fileName);
UdpGlobalStatisticsTable table = StringParsingHelpers.ParseUdpv6GlobalStatisticsFromSnmp6File(fileName);
Assert.Equal(19, table.InDatagrams);
Assert.Equal(0, table.NoPorts);
Assert.Equal(0, table.InErrors);
Assert.Equal(21, table.OutDatagrams);
Assert.Equal(99999, table.RcvbufErrors);
Assert.Equal(11011011, table.SndbufErrors);
Assert.Equal(0, table.InCsumErrors);
}
[Fact]
public void Ipv4GlobalStatisticsParsing()
{
string fileName = GetTestFilePath();
FileUtil.NormalizeLineEndings("NetworkFiles/snmp", fileName);
IPGlobalStatisticsTable table = StringParsingHelpers.ParseIPv4GlobalStatisticsFromSnmpFile(fileName);
Assert.Equal(false, table.Forwarding);
Assert.Equal(64, table.DefaultTtl);
Assert.Equal(28121, table.InReceives);
Assert.Equal(0, table.InHeaderErrors);
Assert.Equal(2, table.InAddressErrors);
Assert.Equal(0, table.ForwardedDatagrams);
Assert.Equal(0, table.InUnknownProtocols);
Assert.Equal(0, table.InDiscards);
Assert.Equal(28117, table.InDelivers);
Assert.Equal(24616, table.OutRequests);
Assert.Equal(48, table.OutDiscards);
Assert.Equal(0, table.OutNoRoutes);
Assert.Equal(0, table.ReassemblyTimeout);
Assert.Equal(0, table.ReassemblyRequireds);
Assert.Equal(1, table.ReassemblyOKs);
Assert.Equal(2, table.ReassemblyFails);
Assert.Equal(14, table.FragmentOKs);
Assert.Equal(0, table.FragmentFails);
Assert.Equal(92, table.FragmentCreates);
}
[Fact]
public void Ipv6GlobalStatisticsParsing()
{
string fileName = GetTestFilePath();
FileUtil.NormalizeLineEndings("NetworkFiles/snmp6", fileName);
IPGlobalStatisticsTable table = StringParsingHelpers.ParseIPv6GlobalStatisticsFromSnmp6File(fileName);
Assert.Equal(189, table.InReceives);
Assert.Equal(0, table.InHeaderErrors);
Assert.Equal(2000, table.InAddressErrors);
Assert.Equal(42, table.InUnknownProtocols);
Assert.Equal(0, table.InDiscards);
Assert.Equal(189, table.InDelivers);
Assert.Equal(55, table.ForwardedDatagrams);
Assert.Equal(199, table.OutRequests);
Assert.Equal(0, table.OutDiscards);
Assert.Equal(53, table.OutNoRoutes);
Assert.Equal(2121, table.ReassemblyTimeout);
Assert.Equal(1, table.ReassemblyRequireds);
Assert.Equal(2, table.ReassemblyOKs);
Assert.Equal(4, table.ReassemblyFails);
Assert.Equal(8, table.FragmentOKs);
Assert.Equal(16, table.FragmentFails);
Assert.Equal(32, table.FragmentCreates);
}
[Fact]
public void IpInterfaceStatisticsParsingFirst()
{
string fileName = GetTestFilePath();
FileUtil.NormalizeLineEndings("NetworkFiles/dev", fileName);
IPInterfaceStatisticsTable table = StringParsingHelpers.ParseInterfaceStatisticsTableFromFile(fileName, "wlan0");
Assert.Equal(26622u, table.BytesReceived);
Assert.Equal(394u, table.PacketsReceived);
Assert.Equal(2u, table.ErrorsReceived);
Assert.Equal(4u, table.IncomingPacketsDropped);
Assert.Equal(6u, table.FifoBufferErrorsReceived);
Assert.Equal(8u, table.PacketFramingErrorsReceived);
Assert.Equal(10u, table.CompressedPacketsReceived);
Assert.Equal(12u, table.MulticastFramesReceived);
Assert.Equal(27465u, table.BytesTransmitted);
Assert.Equal(208u, table.PacketsTransmitted);
Assert.Equal(1u, table.ErrorsTransmitted);
Assert.Equal(2u, table.OutgoingPacketsDropped);
Assert.Equal(3u, table.FifoBufferErrorsTransmitted);
Assert.Equal(4u, table.CollisionsDetected);
Assert.Equal(5u, table.CarrierLosses);
Assert.Equal(6u, table.CompressedPacketsTransmitted);
}
[Fact]
public void IpInterfaceStatisticsParsingLast()
{
string fileName = GetTestFilePath();
FileUtil.NormalizeLineEndings("NetworkFiles/dev", fileName);
IPInterfaceStatisticsTable table = StringParsingHelpers.ParseInterfaceStatisticsTableFromFile(fileName, "lo");
Assert.Equal(uint.MaxValue, table.BytesReceived);
Assert.Equal(302u, table.PacketsReceived);
Assert.Equal(0u, table.ErrorsReceived);
Assert.Equal(0u, table.IncomingPacketsDropped);
Assert.Equal(0u, table.FifoBufferErrorsReceived);
Assert.Equal(0u, table.PacketFramingErrorsReceived);
Assert.Equal(0u, table.CompressedPacketsReceived);
Assert.Equal(0u, table.MulticastFramesReceived);
Assert.Equal(30008u, table.BytesTransmitted);
Assert.Equal(302u, table.PacketsTransmitted);
Assert.Equal(0u, table.ErrorsTransmitted);
Assert.Equal(0u, table.OutgoingPacketsDropped);
Assert.Equal(0u, table.FifoBufferErrorsTransmitted);
Assert.Equal(0u, table.CollisionsDetected);
Assert.Equal(0u, table.CarrierLosses);
Assert.Equal(0u, table.CompressedPacketsTransmitted);
}
}
}
| |
using System;
using System.Collections;
using System.IO;
using Raksha.Asn1;
using Raksha.Asn1.Cms;
using Raksha.Asn1.X509;
using Raksha.Utilities;
namespace Raksha.Cms
{
/**
* Parsing class for an CMS Authenticated Data object from an input stream.
* <p>
* Note: that because we are in a streaming mode only one recipient can be tried and it is important
* that the methods on the parser are called in the appropriate order.
* </p>
* <p>
* Example of use - assuming the first recipient matches the private key we have.
* <pre>
* CMSAuthenticatedDataParser ad = new CMSAuthenticatedDataParser(inputStream);
*
* RecipientInformationStore recipients = ad.getRecipientInfos();
*
* Collection c = recipients.getRecipients();
* Iterator it = c.iterator();
*
* if (it.hasNext())
* {
* RecipientInformation recipient = (RecipientInformation)it.next();
*
* CMSTypedStream recData = recipient.getContentStream(privateKey, "BC");
*
* processDataStream(recData.getContentStream());
*
* if (!Arrays.equals(ad.getMac(), recipient.getMac())
* {
* System.err.println("Data corrupted!!!!");
* }
* }
* </pre>
* Note: this class does not introduce buffering - if you are processing large files you should create
* the parser with:
* <pre>
* CMSAuthenticatedDataParser ep = new CMSAuthenticatedDataParser(new BufferedInputStream(inputStream, bufSize));
* </pre>
* where bufSize is a suitably large buffer size.
* </p>
*/
public class CmsAuthenticatedDataParser
: CmsContentInfoParser
{
internal RecipientInformationStore _recipientInfoStore;
internal AuthenticatedDataParser authData;
private AlgorithmIdentifier macAlg;
private byte[] mac;
private Asn1.Cms.AttributeTable authAttrs;
private Asn1.Cms.AttributeTable unauthAttrs;
private bool authAttrNotRead;
private bool unauthAttrNotRead;
public CmsAuthenticatedDataParser(
byte[] envelopedData)
: this(new MemoryStream(envelopedData, false))
{
}
public CmsAuthenticatedDataParser(
Stream envelopedData)
: base(envelopedData)
{
this.authAttrNotRead = true;
this.authData = new AuthenticatedDataParser(
(Asn1SequenceParser)contentInfo.GetContent(Asn1Tags.Sequence));
// TODO Validate version?
//DerInteger version = this.authData.getVersion();
//
// read the recipients
//
Asn1Set recipientInfos = Asn1Set.GetInstance(authData.GetRecipientInfos().ToAsn1Object());
this.macAlg = authData.GetMacAlgorithm();
//
// read the authenticated content info
//
ContentInfoParser data = authData.GetEnapsulatedContentInfo();
ICmsReadable readable = new CmsProcessableInputStream(
((Asn1OctetStringParser)data.GetContent(Asn1Tags.OctetString)).GetOctetStream());
CmsSecureReadable secureReadable = new CmsEnvelopedHelper.CmsAuthenticatedSecureReadable(
this.macAlg, readable);
//
// build the RecipientInformationStore
//
this._recipientInfoStore = CmsEnvelopedHelper.BuildRecipientInformationStore(
recipientInfos, secureReadable);
}
public AlgorithmIdentifier MacAlgorithmID
{
get { return macAlg; }
}
/**
* return the object identifier for the mac algorithm.
*/
public string MacAlgOid
{
get { return macAlg.ObjectID.Id; }
}
/**
* return the ASN.1 encoded encryption algorithm parameters, or null if
* there aren't any.
*/
public Asn1Object MacAlgParams
{
get
{
Asn1Encodable ae = macAlg.Parameters;
return ae == null ? null : ae.ToAsn1Object();
}
}
/**
* return a store of the intended recipients for this message
*/
public RecipientInformationStore GetRecipientInfos()
{
return _recipientInfoStore;
}
public byte[] GetMac()
{
if (mac == null)
{
GetAuthAttrs();
mac = authData.GetMac().GetOctets();
}
return Arrays.Clone(mac);
}
/**
* return a table of the unauthenticated attributes indexed by
* the OID of the attribute.
* @exception java.io.IOException
*/
public Asn1.Cms.AttributeTable GetAuthAttrs()
{
if (authAttrs == null && authAttrNotRead)
{
Asn1SetParser s = authData.GetAuthAttrs();
authAttrNotRead = false;
if (s != null)
{
Asn1EncodableVector v = new Asn1EncodableVector();
IAsn1Convertible o;
while ((o = s.ReadObject()) != null)
{
Asn1SequenceParser seq = (Asn1SequenceParser)o;
v.Add(seq.ToAsn1Object());
}
authAttrs = new Asn1.Cms.AttributeTable(new DerSet(v));
}
}
return authAttrs;
}
/**
* return a table of the unauthenticated attributes indexed by
* the OID of the attribute.
* @exception java.io.IOException
*/
public Asn1.Cms.AttributeTable GetUnauthAttrs()
{
if (unauthAttrs == null && unauthAttrNotRead)
{
Asn1SetParser s = authData.GetUnauthAttrs();
unauthAttrNotRead = false;
if (s != null)
{
Asn1EncodableVector v = new Asn1EncodableVector();
IAsn1Convertible o;
while ((o = s.ReadObject()) != null)
{
Asn1SequenceParser seq = (Asn1SequenceParser)o;
v.Add(seq.ToAsn1Object());
}
unauthAttrs = new Asn1.Cms.AttributeTable(new DerSet(v));
}
}
return unauthAttrs;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Xml;
using Microsoft.Test.ModuleCore;
namespace CoreXml.Test.XLinq
{
public partial class FunctionalTests : TestModule
{
public partial class XNodeReaderTests : XLinqTestCase
{
public partial class TCAttributeAccess : BridgeHelpers
{
//[Variation("Attribute Access test using ordinal (Ascending Order)", Priority = 0)]
public void TestAttributeAccess1()
{
XmlReader DataReader = GetReader();
string[] astr = new string[10];
string n;
string qname;
PositionOnElement(DataReader, "ACT0");
int start = 1;
int end = DataReader.AttributeCount;
for (int i = start; i < end; i++)
{
astr[i - 1] = DataReader[i];
n = strAttr + (i - 1);
qname = "foo:" + n;
TestLog.Compare(DataReader[i], DataReader.GetAttribute(i), "Compare this with GetAttribute");
DataReader.MoveToAttribute(i);
TestLog.Compare(DataReader.Value, DataReader.GetAttribute(i), "Compare MoveToAttribute(i) with GetAttribute");
TestLog.Compare(DataReader[n, strNamespace], DataReader.GetAttribute(n, strNamespace), "Compare this(name,strNamespace) with GetAttribute(name,strNamespace)");
TestLog.Compare(DataReader[i], DataReader[n, strNamespace], "Compare this(i) with this(name,strNamespace)");
TestLog.Compare(DataReader.MoveToAttribute(n, strNamespace), true, "MoveToAttribute(name,strNamespace)");
TestLog.Compare(DataReader.Value, DataReader.GetAttribute(n, strNamespace), "Compare MoveToAttribute(name,strNamespace) with GetAttribute(name,strNamespace)");
TestLog.Compare(DataReader[i], DataReader[qname], "Compare this(i) with this(qname)");
TestLog.Compare(DataReader.MoveToAttribute(qname), true, "MoveToAttribute(qname)");
TestLog.Compare(DataReader.Value, DataReader.GetAttribute(qname), "Compare MoveToAttribute(qname) with GetAttribute(qname)");
}
PositionOnElement(DataReader, "ACT1");
for (int i = 0; i < DataReader.AttributeCount; i++)
{
TestLog.Compare(astr[i], DataReader.GetAttribute(i), "Compare value with GetAttribute");
TestLog.Compare(DataReader[i], DataReader.GetAttribute(i), "Compare this with GetAttribute");
DataReader.MoveToAttribute(i);
TestLog.Compare(DataReader.Value, DataReader.GetAttribute(i), "Compare MoveToAttribute(i) with GetAttribute");
n = strAttr + i;
TestLog.Compare(DataReader[n], DataReader.GetAttribute(n), "Compare this(name) with GetAttribute(name)");
TestLog.Compare(DataReader[i], DataReader[n], "Compare this(i) with this(name)");
TestLog.Compare(DataReader.MoveToAttribute(n), true, "MoveToAttribute(name)");
TestLog.Compare(DataReader.Value, DataReader.GetAttribute(n), "Compare MoveToAttribute(name) with GetAttribute(name)");
}
}
//[Variation("Attribute Access test using ordinal (Descending Order)")]
public void TestAttributeAccess2()
{
XmlReader DataReader = GetReader();
string[] astr = new string[10];
string n;
string qname;
PositionOnElement(DataReader, "ACT0");
int start = 1;
int end = DataReader.AttributeCount;
for (int i = end - 1; i >= start; i--)
{
astr[i - 1] = DataReader[i];
n = strAttr + (i - 1);
qname = "foo:" + n;
TestLog.Compare(DataReader[i], DataReader.GetAttribute(i), "Compare this with GetAttribute");
DataReader.MoveToAttribute(i);
TestLog.Compare(DataReader.Value, DataReader.GetAttribute(i), "Compare MoveToAttribute(i) with GetAttribute");
TestLog.Compare(DataReader[n, strNamespace], DataReader.GetAttribute(n, strNamespace), "Compare this(name,strNamespace) with GetAttribute(name,strNamespace)");
TestLog.Compare(DataReader[i], DataReader[n, strNamespace], "Compare this(i) with this(name,strNamespace)");
TestLog.Compare(DataReader.MoveToAttribute(n, strNamespace), true, "MoveToAttribute(name,strNamespace)");
TestLog.Compare(DataReader.Value, DataReader.GetAttribute(n, strNamespace), "Compare MoveToAttribute(name,strNamespace) with GetAttribute(name,strNamespace)");
TestLog.Compare(DataReader[qname], DataReader.GetAttribute(qname), "Compare this(qname) with GetAttribute(qname)");
TestLog.Compare(DataReader[i], DataReader[qname], "Compare this(i) with this(qname)");
TestLog.Compare(DataReader.MoveToAttribute(qname), true, "MoveToAttribute(qname)");
TestLog.Compare(DataReader.Value, DataReader.GetAttribute(qname), "Compare MoveToAttribute(qname) with GetAttribute(qname)");
}
PositionOnElement(DataReader, "ACT1");
for (int i = (DataReader.AttributeCount - 1); i > 0; i--)
{
n = strAttr + i;
TestLog.Compare(astr[i], DataReader.GetAttribute(i), "Compare value with GetAttribute");
TestLog.Compare(DataReader[i], DataReader.GetAttribute(i), "Compare this with GetAttribute");
DataReader.MoveToAttribute(i);
TestLog.Compare(DataReader.Value, DataReader.GetAttribute(i), "Compare MoveToAttribute(i) with GetAttribute");
TestLog.Compare(DataReader[n], DataReader.GetAttribute(n), "Compare this(name) with GetAttribute(name)");
TestLog.Compare(DataReader[i], DataReader[n], "Compare this(i) with this(name)");
TestLog.Compare(DataReader.MoveToAttribute(n), true, "MoveToAttribute(name)");
TestLog.Compare(DataReader.Value, DataReader.GetAttribute(n), "Compare MoveToAttribute(name) with GetAttribute(name)");
}
}
//[Variation("Attribute Access test using ordinal (Odd number)", Priority = 0)]
public void TestAttributeAccess3()
{
XmlReader DataReader = GetReader();
string[] astr = new string[10];
string n;
string qname;
PositionOnElement(DataReader, "ACT0");
int start = 1;
int end = DataReader.AttributeCount;
for (int i = start; i < end; i += 2)
{
astr[i - 1] = DataReader[i];
n = strAttr + (i - 1);
qname = "foo:" + n;
TestLog.Compare(DataReader[i], DataReader.GetAttribute(i), "Compare this with GetAttribute");
DataReader.MoveToAttribute(i);
TestLog.Compare(DataReader.Value, DataReader.GetAttribute(i), "Compare MoveToAttribute(i) with GetAttribute");
TestLog.Compare(DataReader[n, strNamespace], DataReader.GetAttribute(n, strNamespace), "Compare this(name,strNamespace) with GetAttribute(name,strNamespace)");
TestLog.Compare(DataReader[i], DataReader[n, strNamespace], "Compare this(i) with this(name,strNamespace)");
TestLog.Compare(DataReader.MoveToAttribute(n, strNamespace), true, "MoveToAttribute(name,strNamespace)");
TestLog.Compare(DataReader.Value, DataReader.GetAttribute(n, strNamespace), "Compare MoveToAttribute(name,strNamespace) with GetAttribute(name,strNamespace)");
TestLog.Compare(DataReader[qname], DataReader.GetAttribute(qname), "Compare this(qname) with GetAttribute(qname)");
TestLog.Compare(DataReader[i], DataReader[qname], "Compare this(i) with this(qname)");
TestLog.Compare(DataReader.MoveToAttribute(qname), true, "MoveToAttribute(qname)");
TestLog.Compare(DataReader.Value, DataReader.GetAttribute(qname), "Compare MoveToAttribute(qname) with GetAttribute(qname)");
}
PositionOnElement(DataReader, "ACT1");
for (int i = 0; i < DataReader.AttributeCount; i += 2)
{
TestLog.Compare(astr[i], DataReader.GetAttribute(i), "Compare value with GetAttribute");
TestLog.Compare(DataReader[i], DataReader.GetAttribute(i), "Compare this with GetAttribute");
DataReader.MoveToAttribute(i);
TestLog.Compare(DataReader.Value, DataReader.GetAttribute(i), "Compare MoveToAttribute(i) with GetAttribute");
n = strAttr + i;
TestLog.Compare(DataReader[n], DataReader.GetAttribute(n), "Compare this(name) with GetAttribute(name)");
TestLog.Compare(DataReader[i], DataReader[n], "Compare this(i) with this(name)");
TestLog.Compare(DataReader.MoveToAttribute(n), true, "MoveToAttribute(name)");
TestLog.Compare(DataReader.Value, DataReader.GetAttribute(n), "Compare MoveToAttribute(name) with GetAttribute(name)");
}
}
//[Variation("Attribute Access test using ordinal (Even number)")]
public void TestAttributeAccess4()
{
XmlReader DataReader = GetReader();
string[] astr = new string[10];
string n;
string qname;
PositionOnElement(DataReader, "ACT0");
int start = 1;
int end = DataReader.AttributeCount;
for (int i = start; i < end; i += 3)
{
astr[i - 1] = DataReader[i];
n = strAttr + (i - 1);
qname = "foo:" + n;
TestLog.Compare(DataReader[i], DataReader.GetAttribute(i), "Compare this with GetAttribute");
DataReader.MoveToAttribute(i);
TestLog.Compare(DataReader.Value, DataReader.GetAttribute(i), "Compare MoveToAttribute(i) with GetAttribute");
TestLog.Compare(DataReader[n, strNamespace], DataReader.GetAttribute(n, strNamespace), "Compare this(name,strNamespace) with GetAttribute(name,strNamespace)");
TestLog.Compare(DataReader[i], DataReader[n, strNamespace], "Compare this(i) with this(name,strNamespace)");
TestLog.Compare(DataReader.MoveToAttribute(n, strNamespace), true, "MoveToAttribute(name,strNamespace)");
TestLog.Compare(DataReader.Value, DataReader.GetAttribute(n, strNamespace), "Compare MoveToAttribute(name,strNamespace) with GetAttribute(name,strNamespace)");
TestLog.Compare(DataReader[qname], DataReader.GetAttribute(qname), "Compare this(qname) with GetAttribute(qname)");
TestLog.Compare(DataReader[i], DataReader[qname], "Compare this(i) with this(qname)");
TestLog.Compare(DataReader.MoveToAttribute(qname), true, "MoveToAttribute(qname)");
TestLog.Compare(DataReader.Value, DataReader.GetAttribute(qname), "Compare MoveToAttribute(qname) with GetAttribute(qname)");
}
PositionOnElement(DataReader, "ACT1");
for (int i = 0; i < DataReader.AttributeCount; i += 3)
{
TestLog.Compare(astr[i], DataReader.GetAttribute(i), "Compare value with GetAttribute");
TestLog.Compare(DataReader[i], DataReader.GetAttribute(i), "Compare this with GetAttribute");
DataReader.MoveToAttribute(i);
TestLog.Compare(DataReader.Value, DataReader.GetAttribute(i), "Compare MoveToAttribute(i) with GetAttribute");
n = strAttr + i;
TestLog.Compare(DataReader[n], DataReader.GetAttribute(n), "Compare this(name) with GetAttribute(name)");
TestLog.Compare(DataReader[i], DataReader[n], "Compare this(i) with this(name)");
TestLog.Compare(DataReader.MoveToAttribute(n), true, "MoveToAttribute(name)");
TestLog.Compare(DataReader.Value, DataReader.GetAttribute(n), "Compare MoveToAttribute(name) with GetAttribute(name)");
}
}
//[Variation("Attribute Access with namespace=null")]
public void TestAttributeAccess5()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT1");
TestLog.Compare(DataReader[strAttr + 1, null], null, "Item");
TestLog.Compare(DataReader.Name, "ACT1", "Reader changed position");
}
}
public partial class TCThisName : BridgeHelpers
{
//[Variation("This[Name] Verify with GetAttribute(Name)", Priority = 0)]
public void ThisWithName1()
{
string strName;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT1");
for (int i = 0; i < DataReader.AttributeCount; i++)
{
strName = strAttr + i;
TestLog.Compare(DataReader[strName], DataReader.GetAttribute(strName), "Ordinal (" + i + "): Compare GetAttribute(strName) and this[strName]");
}
}
//[Variation("This[Name, null] Verify with GetAttribute(Name)")]
public void ThisWithName2()
{
string strName;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT1");
for (int i = 0; i < DataReader.AttributeCount; i++)
{
strName = strAttr + i;
TestLog.Compare(DataReader[strName, null], null, "Ordinal (" + i + "): Should have returned null");
}
}
//[Variation("This[Name] Verify with GetAttribute(Name,null)")]
public void ThisWithName3()
{
string strName;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT1");
for (int i = 0; i < DataReader.AttributeCount; i++)
{
strName = strAttr + i;
TestLog.Compare(DataReader.GetAttribute(strName, null), null, "Ordinal (" + i + "): Should have returned null");
}
}
//[Variation("This[Name, NamespaceURI] Verify with GetAttribute(Name, NamespaceURI)", Priority = 0)]
public void ThisWithName4()
{
string strName;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT0");
for (int i = 1; i < DataReader.AttributeCount; i++)
{
strName = strAttr + i;
TestLog.Compare(DataReader[strName, strNamespace], DataReader.GetAttribute(strName, strNamespace), "Ordinal (" + i + "): Compare GetAttribute(strName,strNamespace) and this[strName,strNamespace]");
}
}
//[Variation("This[Name, null] Verify not the same as GetAttribute(Name, NamespaceURI)")]
public void ThisWithName5()
{
string strName;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT0");
for (int i = 1; i < DataReader.AttributeCount; i++)
{
strName = strAttr + (i - 1);
TestLog.Compare(DataReader[strName, null], null, "Ordinal (" + i + "): Should have returned null");
}
}
//[Variation("This[Name, NamespaceURI] Verify not the same as GetAttribute(Name, null)")]
public void ThisWithName6()
{
string strName;
XmlReader DataReader = GetReader();
for (int i = 1; i < DataReader.AttributeCount; i++)
{
strName = strAttr + (i - 1);
if (DataReader.GetAttribute(strName, null) == DataReader[strName, strNamespace])
throw new TestException(TestResult.Failed, Variation.Desc);
}
}
//[Variation("This[Name] Verify with MoveToAttribute(Name)", Priority = 0)]
public void ThisWithName7()
{
string strName;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT1");
for (int i = 0; i < DataReader.AttributeCount; i++)
{
strName = strAttr + i;
DataReader.MoveToAttribute(strName);
TestLog.Compare(DataReader.Value, DataReader[strName], "Ordinal (" + i + "): Compare GetAttribute(strName) and this[strName]");
}
}
//[Variation("This[Name, null] Verify with MoveToAttribute(Name)")]
public void ThisWithName8()
{
string strName;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT1");
for (int i = 0; i < DataReader.AttributeCount; i++)
{
strName = strAttr + i;
DataReader.MoveToAttribute(strName);
TestLog.Compare(DataReader[strName, null], null, "Ordinal (" + i + "): Should have returned null");
}
}
//[Variation("This[Name] Verify with MoveToAttribute(Name,null)")]
public void ThisWithName9()
{
string strName;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT1");
for (int i = 0; i < DataReader.AttributeCount; i++)
{
strName = strAttr + i;
TestLog.Compare(DataReader.MoveToAttribute(strName, null), false, "Ordinal (" + i + "): Reader should not have moved");
}
}
//[Variation("This[Name, NamespaceURI] Verify not the same as MoveToAttribute(Name, null)", Priority = 0)]
public void ThisWithName10()
{
string strName;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT0");
for (int i = 1; i < DataReader.AttributeCount; i++)
{
strName = strAttr + (i - 1);
TestLog.Compare(DataReader.MoveToAttribute(strName, null), false, "Ordinal (" + i + "): Reader should not have moved");
}
}
//[Variation("This[Name, null] Verify not the same as MoveToAttribute(Name, NamespaceURI)")]
public void ThisWithName11()
{
string strName;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT1");
for (int i = 0; i < DataReader.AttributeCount; i++)
{
strName = strAttr + i;
DataReader.MoveToAttribute(strName, strNamespace);
TestLog.Compare(DataReader[strName, null], null, "Ordinal (" + i + "): Should have retuned null");
}
}
//[Variation("This[Name, namespace] Verify not the same as MoveToAttribute(Name, namespace)")]
public void ThisWithName12()
{
string strName;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT0");
for (int i = 1; i < DataReader.AttributeCount; i++)
{
strName = strAttr + (i - 1);
DataReader.MoveToAttribute(strName, strNamespace);
TestLog.Compare(DataReader.Value, DataReader[strName, strNamespace], "Ordinal (" + i + "): Compare GetAttribute(strName) and this[strName]");
}
}
//[Variation("This(String.Empty)")]
public void ThisWithName13()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "EMPTY1");
TestLog.Compare(DataReader[String.Empty], null, "Should have returned null");
}
//[Variation("This[String.Empty,String.Empty]")]
public void ThisWithName14()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "EMPTY1");
TestLog.Compare(DataReader[String.Empty, String.Empty], null, "Should have returned null");
}
//[Variation("This[QName] Verify with GetAttribute(Name, NamespaceURI)", Priority = 0)]
public void ThisWithName15()
{
string strName;
string qname;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT0");
for (int i = 1; i < DataReader.AttributeCount; i++)
{
strName = strAttr + i;
qname = "foo:" + strName;
TestLog.Compare(DataReader[qname], DataReader.GetAttribute(strName, strNamespace), "Ordinal (" + i + "): Compare GetAttribute(strName,strNamespace) and this[qname]");
TestLog.Compare(DataReader[qname], DataReader.GetAttribute(qname), "Ordinal (" + i + "): Compare GetAttribute(qname) and this[qname]");
}
}
//[Variation("This[QName] invalid Qname")]
public void ThisWithName16()
{
string strName;
string qname;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT0");
int i = 1;
strName = strAttr + i;
qname = "foo1:" + strName;
TestLog.Compare(DataReader.MoveToAttribute(qname), false, "MoveToAttribute(invalid qname)");
TestLog.Compare(DataReader[qname], null, "Compare this[invalid qname] with null");
TestLog.Compare(DataReader.GetAttribute(qname), null, "Compare GetAttribute(invalid qname) with null");
}
}
public partial class TCMoveToAttributeReader : BridgeHelpers
{
//[Variation("MoveToAttribute(String.Empty)")]
public void MoveToAttributeWithName1()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "EMPTY1");
TestLog.Compare(DataReader.MoveToAttribute(String.Empty), false, "Should have returned false");
TestLog.Compare(DataReader.Value, String.Empty, "Compare MoveToAttribute with String.Empty");
}
//[Variation("MoveToAttribute(String.Empty,String.Empty)")]
public void MoveToAttributeWithName2()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "EMPTY1");
TestLog.Compare(DataReader.MoveToAttribute(String.Empty, String.Empty), false, "Compare the call to MoveToAttribute");
TestLog.Compare(DataReader.Value, String.Empty, "Compare MoveToAttribute(strName)");
}
}
//[TestCase(Name = "GetAttributeOrdinal", Desc = "GetAttributeOrdinal")]
public partial class TCGetAttributeOrdinal : BridgeHelpers
{
//[Variation("GetAttribute(i) Verify with This[i] - Double Quote", Priority = 0)]
public void GetAttributeWithGetAttrDoubleQ()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT0");
for (int i = 0; i < DataReader.AttributeCount; i++)
{
TestLog.Compare(DataReader[i], DataReader.GetAttribute(i), "Ordinal (" + i + "): Compare GetAttribute(i) and this[i]");
}
}
//[Variation("GetAttribute[i] Verify with This[i] - Single Quote")]
public void OrdinalWithGetAttrSingleQ()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT1");
for (int i = 0; i < DataReader.AttributeCount; i++)
{
TestLog.Compare(DataReader[i], DataReader.GetAttribute(i), "Ordinal (" + i + "): Compare GetAttribute(i) and this[i]");
}
}
//[Variation("GetAttribute(i) Verify with MoveToAttribute[i] - Double Quote", Priority = 0)]
public void GetAttributeWithMoveAttrDoubleQ()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT0");
for (int i = 0; i < DataReader.AttributeCount; i++)
{
string str = DataReader.GetAttribute(i);
DataReader.MoveToAttribute(i);
TestLog.Compare(DataReader.Value, DataReader.GetAttribute(i), "Ordinal (" + i + "): Compare MoveToAttribute[i] and this[i]");
TestLog.Compare(str, DataReader.Value, "Ordinal (" + i + "): Compare MoveToAttribute[i] and string");
}
}
//[Variation("GetAttribute(i) Verify with MoveToAttribute[i] - Single Quote")]
public void GetAttributeWithMoveAttrSingleQ()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT1");
for (int i = 0; i < DataReader.AttributeCount; i++)
{
string str = DataReader.GetAttribute(i);
DataReader.MoveToAttribute(i);
TestLog.Compare(DataReader.Value, DataReader[i], "Ordinal (" + i + "): Compare MoveToAttribute[i] and this[i]");
TestLog.Compare(str, DataReader.Value, "Ordinal (" + i + "): Compare MoveToAttribute[i] and string");
}
}
//[Variation("GetAttribute(i) NegativeOneOrdinal", Priority = 0)]
public void NegativeOneOrdinal()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT1");
string str = DataReader.GetAttribute(-1);
}
//[Variation("GetAttribute(i) FieldCountOrdinal")]
public void FieldCountOrdinal()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT0");
string str = DataReader.GetAttribute(DataReader.AttributeCount);
}
//[Variation("GetAttribute(i) OrdinalPlusOne", Priority = 0)]
public void OrdinalPlusOne()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT1");
string str = DataReader.GetAttribute(DataReader.AttributeCount + 1);
}
//[Variation("GetAttribute(i) OrdinalMinusOne")]
public void OrdinalMinusOne()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT1");
string str = DataReader.GetAttribute(-2);
}
}
//[TestCase(Name = "GetAttributeName", Desc = "GetAttributeName")]
public partial class TCGetAttributeName : BridgeHelpers
{
//[Variation("GetAttribute(Name) Verify with This[Name]", Priority = 0)]
public void GetAttributeWithName1()
{
string strName;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT1");
for (int i = 0; i < DataReader.AttributeCount; i++)
{
strName = strAttr + i;
TestLog.Compare(DataReader[strName], DataReader.GetAttribute(strName), "Ordinal (" + i + "): Compare GetAttribute(strName) and this[strName]");
}
}
//[Variation("GetAttribute(Name, null) Verify with This[Name]")]
public void GetAttributeWithName2()
{
string strName;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT1");
for (int i = 0; i < DataReader.AttributeCount; i++)
{
strName = strAttr + i;
TestLog.Compare(DataReader[strName], DataReader.GetAttribute(strName), "Ordinal (" + i + "): Compare GetAttribute(strName) and this[strName]");
}
}
//[Variation("GetAttribute(Name) Verify with This[Name,null]")]
public void GetAttributeWithName3()
{
string strName;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT1");
for (int i = 0; i < DataReader.AttributeCount; i++)
{
strName = strAttr + i;
TestLog.Compare(DataReader[strName], DataReader.GetAttribute(strName), "Ordinal (" + i + "): Compare GetAttribute(strName) and this[strName]");
}
}
//[Variation("GetAttribute(Name, NamespaceURI) Verify with This[Name, NamespaceURI]", Priority = 0)]
public void GetAttributeWithName4()
{
string strName;
string qname;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT0");
for (int i = 1; i < DataReader.AttributeCount; i++)
{
strName = strAttr + i;
qname = "foo:" + strName;
TestLog.Compare(DataReader[strName, strNamespace], DataReader.GetAttribute(strName, strNamespace), "Ordinal (" + i + "): Compare GetAttribute(strName,strNamespace) and this[strName,strNamespace]");
TestLog.Compare(DataReader[qname], DataReader.GetAttribute(strName, strNamespace), "Ordinal (" + i + "): Compare GetAttribute(strName,strNamespace) and this[strName,strNamespace]");
TestLog.Compare(DataReader[qname], DataReader.GetAttribute(qname), "Ordinal (" + i + "): Compare GetAttribute(qname) and this[qname]");
}
}
//[Variation("GetAttribute(Name, null) Verify not the same as This[Name, NamespaceURI]")]
public void GetAttributeWithName5()
{
string strName;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT0");
for (int i = 1; i < DataReader.AttributeCount; i++)
{
strName = strAttr + (i - 1);
if (DataReader.GetAttribute(strName) == DataReader[strName, strNamespace])
{
if (DataReader[strName, strNamespace] == String.Empty)
throw new TestException(TestResult.Failed, Variation.Desc);
}
}
}
//[Variation("GetAttribute(Name, NamespaceURI) Verify not the same as This[Name, null]")]
public void GetAttributeWithName6()
{
string strName;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT0");
for (int i = 1; i < DataReader.AttributeCount; i++)
{
strName = strAttr + (i - 1);
if (DataReader.GetAttribute(strName, strNamespace) == DataReader[strName])
throw new TestException(TestResult.Failed, Variation.Desc);
}
}
//[Variation("GetAttribute(Name) Verify with MoveToAttribute(Name)")]
public void GetAttributeWithName7()
{
string strName;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT1");
for (int i = 0; i < DataReader.AttributeCount; i++)
{
strName = strAttr + i;
DataReader.MoveToAttribute(strName);
TestLog.Compare(DataReader.Value, DataReader.GetAttribute(strName), "Ordinal (" + i + "): Compare GetAttribute(strName) and this[strName]");
}
}
//[Variation("GetAttribute(Name,null) Verify with MoveToAttribute(Name)", Priority = 1)]
public void GetAttributeWithName8()
{
string strName;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT1");
for (int i = 0; i < DataReader.AttributeCount; i++)
{
strName = strAttr + i;
DataReader.MoveToAttribute(strName);
TestLog.Compare(DataReader.GetAttribute(strName, null), null, "Ordinal (" + i + "): Did not return null");
}
}
//[Variation("GetAttribute(Name) Verify with MoveToAttribute(Name,null)", Priority = 1)]
public void GetAttributeWithName9()
{
string strName;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT1");
for (int i = 0; i < DataReader.AttributeCount; i++)
{
strName = strAttr + i;
TestLog.Compare(DataReader.MoveToAttribute(strName, null), false, "Ordinal (" + i + "): Incorrect move");
TestLog.Compare(DataReader.Value, String.Empty, "Ordinal (" + i + "): DataReader.Value should be empty string");
}
}
//[Variation("GetAttribute(Name, NamespaceURI) Verify not the same as MoveToAttribute(Name, null)")]
public void GetAttributeWithName10()
{
string strName;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT0");
for (int i = 1; i < DataReader.AttributeCount; i++)
{
strName = strAttr + (i - 1);
TestLog.Compare(DataReader.MoveToAttribute(strName, null), false, "Incorrect move");
TestLog.Compare(DataReader.Value, String.Empty, "Ordinal (" + i + "): DataReader.Value should be empty string");
}
}
//[Variation("GetAttribute(Name, null) Verify not the same as MoveToAttribute(Name, NamespaceURI)")]
public void GetAttributeWithName11()
{
string strName;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT1");
for (int i = 0; i < DataReader.AttributeCount; i++)
{
strName = strAttr + i;
DataReader.MoveToAttribute(strName, strNamespace);
TestLog.Compare(DataReader.GetAttribute(strName, null), null, "Should have returned null");
}
}
//[Variation("GetAttribute(Name, namespace) Verify not the same as MoveToAttribute(Name, namespace)")]
public void GetAttributeWithName12()
{
string strName;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT0");
for (int i = 1; i < DataReader.AttributeCount; i++)
{
strName = strAttr + (i - 1);
DataReader.MoveToAttribute(strName, strNamespace);
TestLog.Compare(DataReader.Value, DataReader.GetAttribute(strName, strNamespace), "Ordinal (" + i + "): Compare GetAttribute(strName) and this[strName]");
}
}
//[Variation("GetAttribute(String.Empty)")]
public void GetAttributeWithName13()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT1");
TestLog.Compare(DataReader.GetAttribute(String.Empty), null, "Should have returned null");
}
//[Variation("GetAttribute(String.Empty,String.Empty)")]
public void GetAttributeWithName14()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT0");
TestLog.Compare(DataReader.GetAttribute(String.Empty, String.Empty), null, "Compare GetAttribute(strName) and this[strName]");
}
}
//[TestCase(Name = "ThisOrdinal", Desc = "ThisOrdinal")]
public partial class TCThisOrdinal : BridgeHelpers
{
//[Variation("This[i] Verify with GetAttribute[i] - Double Quote", Priority = 0)]
public void OrdinalWithGetAttrDoubleQ()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT0");
for (int i = 0; i < DataReader.AttributeCount; i++)
{
TestLog.Compare(DataReader[i], DataReader.GetAttribute(i), "Ordinal (" + i + "): Compare GetAttribute[i] and this[i]");
}
}
//[Variation("This[i] Verify with GetAttribute[i] - Single Quote")]
public void OrdinalWithGetAttrSingleQ()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT1");
for (int i = 0; i < DataReader.AttributeCount; i++)
{
TestLog.Compare(DataReader[i], DataReader.GetAttribute(i), "Ordinal (" + i + "): Compare GetAttribute[i] and this[i]");
}
}
//[Variation("This[i] Verify with MoveToAttribute[i] - Double Quote", Priority = 0)]
public void OrdinalWithMoveAttrDoubleQ()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT0");
for (int i = 0; i < DataReader.AttributeCount; i++)
{
string str = DataReader[i];
DataReader.MoveToAttribute(i);
TestLog.Compare(DataReader.Value, DataReader[i], "Ordinal (" + i + "): Compare MoveToAttribute[i] and this[i]");
TestLog.Compare(str, DataReader.Value, "Ordinal (" + i + "): Compare MoveToAttribute[i] and string");
}
}
//[Variation("This[i] Verify with MoveToAttribute[i] - Single Quote")]
public void OrdinalWithMoveAttrSingleQ()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT1");
for (int i = 0; i < DataReader.AttributeCount; i++)
{
string str = DataReader[i];
DataReader.MoveToAttribute(i);
TestLog.Compare(DataReader.Value, DataReader[i], "Ordinal (" + i + "): Compare MoveToAttribute[i] and this[i]");
TestLog.Compare(str, DataReader.Value, "Ordinal (" + i + "): Compare MoveToAttribute[i] and string");
}
}
//[Variation("ThisOrdinal NegativeOneOrdinal", Priority = 0)]
public void NegativeOneOrdinal()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT1");
string str = DataReader[-1];
}
//[Variation("ThisOrdinal FieldCountOrdinal")]
public void FieldCountOrdinal()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT0");
string str = DataReader[DataReader.AttributeCount];
}
//[Variation("ThisOrdinal OrdinalPlusOne", Priority = 0)]
public void OrdinalPlusOne()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT1");
string str = DataReader[DataReader.AttributeCount + 1];
}
//[Variation("ThisOrdinal OrdinalMinusOne")]
public void OrdinalMinusOne()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT1");
string str = DataReader[-2];
}
}
//[TestCase(Name = "MoveToAttributeOrdinal", Desc = "MoveToAttributeOrdinal")]
public partial class TCMoveToAttributeOrdinal : BridgeHelpers
{
//[Variation("MoveToAttribute(i) Verify with This[i] - Double Quote", Priority = 0)]
public void MoveToAttributeWithGetAttrDoubleQ()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT0");
for (int i = 0; i < DataReader.AttributeCount; i++)
{
DataReader.MoveToAttribute(i);
TestLog.Compare(DataReader[i], DataReader.Value, "Ordinal (" + i + "): Compare GetAttribute(i) and this[i]");
}
}
//[Variation("MoveToAttribute(i) Verify with This[i] - Single Quote")]
public void MoveToAttributeWithGetAttrSingleQ()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT1");
for (int i = 0; i < DataReader.AttributeCount; i++)
{
DataReader.MoveToAttribute(i);
TestLog.Compare(DataReader[i], DataReader.Value, "Ordinal (" + i + "): Compare GetAttribute(i) and this[i]");
}
}
//[Variation("MoveToAttribute(i) Verify with GetAttribute(i) - Double Quote", Priority = 0)]
public void MoveToAttributeWithMoveAttrDoubleQ()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT0");
for (int i = 0; i < DataReader.AttributeCount; i++)
{
string str = DataReader.GetAttribute(i);
DataReader.MoveToAttribute(i);
TestLog.Compare(DataReader.Value, DataReader.GetAttribute(i), "Ordinal (" + i + "): Compare MoveToAttribute[i] and this[i]");
TestLog.Compare(str, DataReader.Value, "Ordinal (" + i + "): Compare MoveToAttribute[i] and string");
}
}
//[Variation("MoveToAttribute(i) Verify with GetAttribute[i] - Single Quote")]
public void MoveToAttributeWithMoveAttrSingleQ()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT1");
for (int i = 0; i < DataReader.AttributeCount; i++)
{
string str = DataReader.GetAttribute(i);
DataReader.MoveToAttribute(i);
TestLog.Compare(DataReader.Value, DataReader[i], "Ordinal (" + i + "): Compare MoveToAttribute[i] and this[i]");
TestLog.Compare(str, DataReader.Value, "Ordinal (" + i + "): Compare MoveToAttribute[i] and string");
}
}
//[Variation("MoveToAttribute(i) NegativeOneOrdinal", Priority = 0)]
public void NegativeOneOrdinal()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT1");
try
{
DataReader.MoveToAttribute(-1);
}
catch (ArgumentOutOfRangeException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("MoveToAttribute(i) FieldCountOrdinal")]
public void FieldCountOrdinal()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT0");
try
{
DataReader.MoveToAttribute(DataReader.AttributeCount);
}
catch (ArgumentOutOfRangeException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("MoveToAttribute(i) OrdinalPlusOne", Priority = 0)]
public void OrdinalPlusOne()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT1");
try
{
DataReader.MoveToAttribute(DataReader.AttributeCount + 1);
}
catch (ArgumentOutOfRangeException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("MoveToAttribute(i) OrdinalMinusOne")]
public void OrdinalMinusOne()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT1");
try
{
DataReader.MoveToAttribute(-2);
}
catch (ArgumentOutOfRangeException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
}
//[TestCase(Name = "MoveToFirstAtribute", Desc = "MoveToFirstAttribute")]
public partial class TCMoveToFirstAttribute : BridgeHelpers
{
//[Variation("MoveToFirstAttribute() When AttributeCount=0, <EMPTY1/> ", Priority = 0)]
public void MoveToFirstAttribute1()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "EMPTY1");
TestLog.Compare(DataReader.MoveToFirstAttribute(), false, Variation.Desc);
}
//[Variation("MoveToFirstAttribute() When AttributeCount=0, <NONEMPTY1>ABCDE</NONEMPTY1> ")]
public void MoveToFirstAttribute2()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "NONEMPTY1");
TestLog.Compare(DataReader.MoveToFirstAttribute(), false, Variation.Desc);
}
//[Variation("MoveToFirstAttribute() When iOrdinal=0, with namespace")]
public void MoveToFirstAttribute3()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT0");
string strFirst;
TestLog.Compare(DataReader.MoveToFirstAttribute(), true, Variation.Desc);
strFirst = DataReader.Value;
TestLog.Compare(strFirst, DataReader.GetAttribute(0), Variation.Desc);
}
//[Variation("MoveToFirstAttribute() When iOrdinal=0, without namespace")]
public void MoveToFirstAttribute4()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT1");
string strFirst;
TestLog.Compare(DataReader.MoveToFirstAttribute(), true, Variation.Desc);
strFirst = DataReader.Value;
TestLog.Compare(strFirst, DataReader.GetAttribute(0), Variation.Desc);
}
//[Variation("MoveToFirstAttribute() When iOrdinal=mIddle, with namespace")]
public void MoveToFirstAttribute5()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT0");
string strFirst;
DataReader.MoveToAttribute((int)((DataReader.AttributeCount) / 2));
TestLog.Compare(DataReader.MoveToFirstAttribute(), true, Variation.Desc);
strFirst = DataReader.Value;
TestLog.Compare(strFirst, DataReader.GetAttribute(0), Variation.Desc);
}
//[Variation("MoveToFirstAttribute() When iOrdinal=mIddle, without namespace")]
public void MoveToFirstAttribute6()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT1");
string strFirst;
DataReader.MoveToAttribute((int)((DataReader.AttributeCount) / 2));
TestLog.Compare(DataReader.MoveToFirstAttribute(), true, Variation.Desc);
strFirst = DataReader.Value;
TestLog.Compare(strFirst, DataReader.GetAttribute(0), Variation.Desc);
}
//[Variation("MoveToFirstAttribute() When iOrdinal=end, with namespace")]
public void MoveToFirstAttribute7()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT0");
string strFirst;
DataReader.MoveToAttribute((DataReader.AttributeCount) - 1);
TestLog.Compare(DataReader.MoveToFirstAttribute(), true, Variation.Desc);
strFirst = DataReader.Value;
TestLog.Compare(strFirst, DataReader.GetAttribute(0), Variation.Desc);
}
//[Variation("MoveToFirstAttribute() When iOrdinal=end, without namespace")]
public void MoveToFirstAttribute8()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT1");
string strFirst;
DataReader.MoveToAttribute((DataReader.AttributeCount) - 1);
TestLog.Compare(DataReader.MoveToFirstAttribute(), true, Variation.Desc);
strFirst = DataReader.Value;
TestLog.Compare(strFirst, DataReader.GetAttribute(0), Variation.Desc);
}
}
public partial class TCMoveToNextAttribute : BridgeHelpers
{
//[Variation("MoveToNextAttribute() When AttributeCount=0, <EMPTY1/> ", Priority = 0)]
public void MoveToNextAttribute1()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "EMPTY1");
TestLog.Compare(DataReader.MoveToNextAttribute(), false, Variation.Desc);
}
//[Variation("MoveToNextAttribute() When AttributeCount=0, <NONEMPTY1>ABCDE</NONEMPTY1> ")]
public void MoveToNextAttribute2()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "NONEMPTY1");
TestLog.Compare(DataReader.MoveToNextAttribute(), false, Variation.Desc);
}
//[Variation("MoveToNextAttribute() When iOrdinal=0, with namespace")]
public void MoveToNextAttribute3()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT0");
string strValue;
TestLog.Compare(DataReader.MoveToNextAttribute(), true, Variation.Desc);
strValue = DataReader.Value;
TestLog.Compare(strValue, DataReader.GetAttribute(0), Variation.Desc);
TestLog.Compare(DataReader.MoveToFirstAttribute(), true, Variation.Desc);
TestLog.Compare(DataReader.MoveToNextAttribute(), true, Variation.Desc);
strValue = DataReader.Value;
TestLog.Compare(strValue, DataReader.GetAttribute(1), Variation.Desc);
}
//[Variation("MoveToNextAttribute() When iOrdinal=0, without namespace")]
public void MoveToNextAttribute4()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT1");
string strValue;
TestLog.Compare(DataReader.MoveToNextAttribute(), true, Variation.Desc);
strValue = DataReader.Value;
TestLog.Compare(strValue, DataReader.GetAttribute(0), Variation.Desc);
TestLog.Compare(DataReader.MoveToFirstAttribute(), true, Variation.Desc);
TestLog.Compare(DataReader.MoveToNextAttribute(), true, Variation.Desc);
strValue = DataReader.Value;
TestLog.Compare(strValue, DataReader.GetAttribute(1), Variation.Desc);
}
//[Variation("MoveToFirstAttribute() When iOrdinal=mIddle, with namespace")]
public void MoveToFirstAttribute5()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT0");
string strValue0;
string strValue;
int iMid = (DataReader.AttributeCount) / 2;
DataReader.MoveToAttribute(iMid + 1);
strValue0 = DataReader.Value;
DataReader.MoveToAttribute(iMid);
TestLog.Compare(DataReader.MoveToNextAttribute(), true, Variation.Desc);
strValue = DataReader.Value;
TestLog.Compare(strValue0, strValue, Variation.Desc);
TestLog.Compare(strValue, DataReader.GetAttribute(iMid + 1), Variation.Desc);
}
//[Variation("MoveToFirstAttribute() When iOrdinal=mIddle, without namespace")]
public void MoveToFirstAttribute6()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT1");
string strValue0;
string strValue;
int iMid = (DataReader.AttributeCount) / 2;
DataReader.MoveToAttribute(iMid + 1);
strValue0 = DataReader.Value;
DataReader.MoveToAttribute(iMid);
TestLog.Compare(DataReader.MoveToNextAttribute(), true, Variation.Desc);
strValue = DataReader.Value;
TestLog.Compare(strValue0, strValue, Variation.Desc);
TestLog.Compare(strValue, DataReader.GetAttribute(iMid + 1), Variation.Desc);
}
//[Variation("MoveToFirstAttribute() When iOrdinal=end, with namespace")]
public void MoveToFirstAttribute7()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT0");
string strFirst;
DataReader.MoveToAttribute((DataReader.AttributeCount) - 1);
TestLog.Compare(DataReader.MoveToFirstAttribute(), true, Variation.Desc);
strFirst = DataReader.Value;
TestLog.Compare(strFirst, DataReader.GetAttribute(0), Variation.Desc);
}
//[Variation("MoveToFirstAttribute() When iOrdinal=end, without namespace")]
public void MoveToFirstAttribute8()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ACT1");
string strFirst;
DataReader.MoveToAttribute((DataReader.AttributeCount) - 1);
TestLog.Compare(DataReader.MoveToFirstAttribute(), true, Variation.Desc);
strFirst = DataReader.Value;
TestLog.Compare(strFirst, DataReader.GetAttribute(0), Variation.Desc);
}
}
public partial class TCAttributeTest : BridgeHelpers
{
//[Variation("Attribute Test On None")]
public void TestAttributeTestNodeType_None()
{
XmlReader DataReader = GetReader();
if (FindNodeType(DataReader, XmlNodeType.None))
{
TestLog.Compare(DataReader.AttributeCount, 0, "Checking AttributeCount");
TestLog.Compare(DataReader.HasAttributes, false, "Checking HasAttributes");
TestLog.Compare(DataReader.MoveToFirstAttribute(), false, "Checking MoveToFirstAttribute");
TestLog.Compare(DataReader.MoveToNextAttribute(), false, "Checking MoveToNextAttribute");
}
}
//[Variation("Attribute Test On Element", Priority = 0)]
public void TestAttributeTestNodeType_Element()
{
XmlReader DataReader = GetReader();
if (FindNodeType(DataReader, XmlNodeType.Element))
{
TestLog.Compare(DataReader.AttributeCount, 0, "Checking AttributeCoung");
TestLog.Compare(DataReader.HasAttributes, false, "Checking HasAttributes");
TestLog.Compare(DataReader.MoveToFirstAttribute(), false, "Checking MoveToFirstAttribute");
TestLog.Compare(DataReader.MoveToNextAttribute(), false, "Checking MoveToNextAttribute");
}
}
//[Variation("Attribute Test On Text", Priority = 0)]
public void TestAttributeTestNodeType_Text()
{
XmlReader DataReader = GetReader();
if (FindNodeType(DataReader, XmlNodeType.Text))
{
TestLog.Compare(DataReader.AttributeCount, 0, "Checking AttributeCoung");
TestLog.Compare(DataReader.HasAttributes, false, "Checking HasAttributes");
TestLog.Compare(DataReader.MoveToFirstAttribute(), false, "Checking MoveToFirstAttribute");
TestLog.Compare(DataReader.MoveToNextAttribute(), false, "Checking MoveToNextAttribute");
}
}
//[Variation("Attribute Test On CDATA")]
public void TestAttributeTestNodeType_CDATA()
{
XmlReader DataReader = GetReader();
if (FindNodeType(DataReader, XmlNodeType.CDATA))
{
TestLog.Compare(DataReader.AttributeCount, 0, "Checking AttributeCoung");
TestLog.Compare(DataReader.HasAttributes, false, "Checking HasAttributes");
TestLog.Compare(DataReader.MoveToFirstAttribute(), false, "Checking MoveToFirstAttribute");
TestLog.Compare(DataReader.MoveToNextAttribute(), false, "Checking MoveToNextAttribute");
}
}
//[Variation("Attribute Test On ProcessingInstruction")]
public void TestAttributeTestNodeType_ProcessingInstruction()
{
XmlReader DataReader = GetReader();
if (FindNodeType(DataReader, XmlNodeType.ProcessingInstruction))
{
TestLog.Compare(DataReader.AttributeCount, 0, "Checking AttributeCoung");
TestLog.Compare(DataReader.HasAttributes, false, "Checking HasAttributes");
TestLog.Compare(DataReader.MoveToFirstAttribute(), false, "Checking MoveToFirstAttribute");
TestLog.Compare(DataReader.MoveToNextAttribute(), false, "Checking MoveToNextAttribute");
}
}
//[Variation("AttributeTest On Comment")]
public void TestAttributeTestNodeType_Comment()
{
XmlReader DataReader = GetReader();
if (FindNodeType(DataReader, XmlNodeType.Comment))
{
TestLog.Compare(DataReader.AttributeCount, 0, "Checking AttributeCoung");
TestLog.Compare(DataReader.HasAttributes, false, "Checking HasAttributes");
TestLog.Compare(DataReader.MoveToFirstAttribute(), false, "Checking MoveToFirstAttribute");
TestLog.Compare(DataReader.MoveToNextAttribute(), false, "Checking MoveToNextAttribute");
}
}
//[Variation("AttributeTest On DocumentType", Priority = 0)]
public void TestAttributeTestNodeType_DocumentType()
{
XmlReader DataReader = GetReader();
if (FindNodeType(DataReader, XmlNodeType.DocumentType))
{
TestLog.Compare(DataReader.AttributeCount, 0, "Checking AttributeCount");
TestLog.Compare(DataReader.HasAttributes, false, "Checking HasAttributes");
TestLog.Compare(DataReader.MoveToFirstAttribute(), false, "Checking MoveToFirstAttribute");
TestLog.Compare(DataReader.MoveToNextAttribute(), false, "Checking MoveToNextAttribute");
}
}
//[Variation("AttributeTest On Whitespace")]
public void TestAttributeTestNodeType_Whitespace()
{
XmlReader DataReader = GetReader();
if (FindNodeType(DataReader, XmlNodeType.Whitespace))
{
TestLog.Compare(DataReader.AttributeCount, 0, "Checking AttributeCoung");
TestLog.Compare(DataReader.HasAttributes, false, "Checking HasAttributes");
TestLog.Compare(DataReader.MoveToFirstAttribute(), false, "Checking MoveToFirstAttribute");
TestLog.Compare(DataReader.MoveToNextAttribute(), false, "Checking MoveToNextAttribute");
}
}
//[Variation("AttributeTest On EndElement")]
public void TestAttributeTestNodeType_EndElement()
{
XmlReader DataReader = GetReader();
if (FindNodeType(DataReader, XmlNodeType.EndElement))
{
TestLog.Compare(DataReader.AttributeCount, 0, "Checking AttributeCount");
TestLog.Compare(DataReader.HasAttributes, false, "Checking HasAttributes");
TestLog.Compare(DataReader.MoveToFirstAttribute(), false, "Checking MoveToFirstAttribute");
TestLog.Compare(DataReader.MoveToNextAttribute(), false, "Checking MoveToNextAttribute");
}
}
//[Variation("AttributeTest On XmlDeclaration", Priority = 0)]
public void TestAttributeTestNodeType_XmlDeclaration()
{
XmlReader DataReader = GetReader();
if (FindNodeType(DataReader, XmlNodeType.XmlDeclaration))
{
int nCount = 3;
TestLog.Compare(DataReader.AttributeCount, nCount, "Checking AttributeCount");
TestLog.Compare(DataReader.HasAttributes, true, "Checking HasAttributes");
TestLog.Compare(DataReader.MoveToFirstAttribute(), true, "Checking MoveToFirstAttribute");
bool bNext = true;
TestLog.Compare(DataReader.MoveToNextAttribute(), bNext, "Checking MoveToNextAttribute");
}
}
//[Variation("AttributeTest On EndEntity")]
public void TestAttributeTestNodeType_EndEntity()
{
XmlReader DataReader = GetReader();
if (FindNodeType(DataReader, XmlNodeType.EndEntity))
{
TestLog.Compare(DataReader.AttributeCount, 0, "Checking AttributeCount");
TestLog.Compare(DataReader.HasAttributes, false, "Checking HasAttributes");
TestLog.Compare(DataReader.MoveToFirstAttribute(), false, "Checking MoveToFirstAttribute");
TestLog.Compare(DataReader.MoveToNextAttribute(), false, "Checking MoveToNextAttribute");
}
}
}
//[TestCase(Name = "ReadURI", Desc = "Read URI")]
public partial class TATextReaderDocType : BridgeHelpers
{
//[Variation("Valid URI reference as SystemLiteral")]
public void TATextReaderDocType_1()
{
string strxml = "<?xml version='1.0' standalone='no'?><!DOCTYPE ROOT SYSTEM 'se2.dtd'[]><ROOT/>";
XmlReader r = GetReaderStr(strxml);
while (r.Read()) ;
}
void TestUriChar(char ch)
{
string filename = String.Format("f{0}.dtd", ch);
string strxml = String.Format("<!DOCTYPE ROOT SYSTEM '{0}' []><ROOT></ROOT>", filename);
XmlReader r = GetReaderStr(strxml);
while (r.Read()) ;
}
// XML 1.0 SE
//[Variation("URI reference with disallowed characters in SystemLiteral")]
public void TATextReaderDocType_4()
{
string strDisallowed = " {}^`";
for (int i = 0; i < strDisallowed.Length; i++)
TestUriChar(strDisallowed[i]);
}
}
public partial class TCXmlns : BridgeHelpers
{
private string _ST_ENS1 = "EMPTY_NAMESPACE1";
private string _ST_NS2 = "NAMESPACE2";
//[Variation("Name, LocalName, Prefix and Value with xmlns=ns attribute", Priority = 0)]
public void TXmlns1()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, _ST_ENS1);
DataReader.MoveToAttribute("xmlns");
TestLog.Compare(DataReader.LocalName, "xmlns", "ln");
TestLog.Compare(DataReader.Name, "xmlns", "n");
TestLog.Compare(DataReader.Prefix, String.Empty, "p");
TestLog.Compare(DataReader.Value, "14", "v");
}
//[Variation("Name, LocalName, Prefix and Value with xmlns:p=ns attribute")]
public void TXmlns2()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, _ST_NS2);
DataReader.MoveToAttribute(0);
TestLog.Compare(DataReader.LocalName, "bar", "ln");
TestLog.Compare(DataReader.Name, "xmlns:bar", "n");
TestLog.Compare(DataReader.Prefix, "xmlns", "p");
TestLog.Compare(DataReader.Value, "1", "v");
}
//[Variation("LookupNamespace with xmlns=ns attribute")]
public void TXmlns3()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, _ST_ENS1);
DataReader.MoveToAttribute(1);
TestLog.Compare(DataReader.LookupNamespace("xmlns"), "http://www.w3.org/2000/xmlns/", "ln");
}
//[Variation("MoveToAttribute access on xmlns attribute")]
public void TXmlns4()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, _ST_ENS1);
DataReader.MoveToAttribute(1);
TestLog.Compare(DataReader.LocalName, "xmlns", "ln");
TestLog.Compare(DataReader.Name, "xmlns", "n");
TestLog.Compare(DataReader.Prefix, String.Empty, "p");
TestLog.Compare(DataReader.Value, "14", "v");
DataReader.MoveToElement();
TestLog.Compare(DataReader.MoveToAttribute("xmlns"), true, "mta(str)");
TestLog.Compare(DataReader.LocalName, "xmlns", "ln");
TestLog.Compare(DataReader.Name, "xmlns", "n");
TestLog.Compare(DataReader.Prefix, String.Empty, "p");
TestLog.Compare(DataReader.Value, "14", "v");
DataReader.MoveToElement();
TestLog.Compare(DataReader.MoveToAttribute("xmlns"), true, "mta(str, str)");
TestLog.Compare(DataReader.LocalName, "xmlns", "ln");
TestLog.Compare(DataReader.Name, "xmlns", "n");
TestLog.Compare(DataReader.Prefix, String.Empty, "p");
TestLog.Compare(DataReader.Value, "14", "v");
DataReader.MoveToElement();
TestLog.Compare(DataReader.MoveToAttribute("xmlns", "14"), false, "mta inv");
}
//[Variation("GetAttribute access on xmlns attribute")]
public void TXmlns5()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, _ST_ENS1);
TestLog.Compare(DataReader.GetAttribute(1), "14", "ga(i)");
TestLog.Compare(DataReader.GetAttribute("xmlns"), "14", "ga(str)");
TestLog.Compare(DataReader.GetAttribute("xmlns"), "14", "ga(str, str)");
TestLog.Compare(DataReader.GetAttribute("xmlns", "14"), null, "ga inv");
}
//[Variation("this[xmlns] attribute access")]
public void TXmlns6()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, _ST_ENS1);
TestLog.Compare(DataReader[1], "14", "this[i]");
TestLog.Compare(DataReader["xmlns"], "14", "this[str]");
TestLog.Compare(DataReader["xmlns", "14"], null, "this inv");
}
}
public partial class TCXmlnsPrefix : BridgeHelpers
{
private string _ST_ENS1 = "EMPTY_NAMESPACE1";
private string _ST_NS2 = "NAMESPACE2";
private string _strXmlns = "http://www.w3.org/2000/xmlns/";
//[Variation("NamespaceURI of xmlns:a attribute", Priority = 0)]
public void TXmlnsPrefix1()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, _ST_NS2);
DataReader.MoveToAttribute(0);
TestLog.Compare(DataReader.NamespaceURI, _strXmlns, "nu");
}
//[Variation("NamespaceURI of element/attribute with xmlns attribute", Priority = 0)]
public void TXmlnsPrefix2()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, _ST_ENS1);
TestLog.Compare(DataReader.NamespaceURI, "14", "nue");
DataReader.MoveToAttribute("Attr0");
TestLog.Compare(DataReader.NamespaceURI, String.Empty, "nu");
DataReader.MoveToAttribute("xmlns");
TestLog.Compare(DataReader.NamespaceURI, _strXmlns, "nu");
}
//[Variation("LookupNamespace with xmlns prefix")]
public void TXmlnsPrefix3()
{
XmlReader DataReader = GetReader();
DataReader.Read();
TestLog.Compare(DataReader.LookupNamespace("xmlns"), null, "ln");
}
//[Variation("Define prefix for 'www.w3.org/2000/xmlns'", Priority = 0)]
public void TXmlnsPrefix4()
{
string strxml = "<ROOT xmlns:pxmlns='http://www.w3.org/2000/xmlns/'/>";
try
{
XmlReader DataReader = GetReaderStr(strxml);
DataReader.Read();
throw new TestException(TestResult.Failed, "");
}
catch (XmlException) { }
}
//[Variation("Redefine namespace attached to xmlns prefix")]
public void TXmlnsPrefix5()
{
string strxml = "<ROOT xmlns:xmlns='http://www.w3.org/2002/xmlns/'/>";
try
{
XmlReader DataReader = GetReaderStr(strxml);
DataReader.Read();
throw new TestException(TestResult.Failed, "");
}
catch (XmlException) { }
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using ExtensionLoader;
using OpenMetaverse;
using OpenMetaverse.Packets;
namespace Simian.Extensions
{
public class ParcelManager : IExtension<Simian>, IParcelProvider
{
Simian server;
Dictionary<int, Parcel> parcels = new Dictionary<int, Parcel>();
/// <summary>X,Y ordered 2D array of the parcelIDs for each sq. meter of a simulator</summary>
int[] parcelOverlay = new int[64 * 64];
public ParcelManager()
{
}
public void Start(Simian server)
{
this.server = server;
lock (parcels)
parcels.Clear();
// Create a default parcel
Parcel parcel = new Parcel(0);
parcel.Desc = "Simian Parcel";
parcel.Flags = Parcel.ParcelFlags.AllowAPrimitiveEntry | Parcel.ParcelFlags.AllowFly | Parcel.ParcelFlags.AllowGroupScripts |
Parcel.ParcelFlags.AllowLandmark | Parcel.ParcelFlags.AllowOtherScripts | Parcel.ParcelFlags.AllowTerraform |
Parcel.ParcelFlags.AllowVoiceChat | Parcel.ParcelFlags.CreateGroupObjects | Parcel.ParcelFlags.CreateObjects |
Parcel.ParcelFlags.UseBanList;
parcel.Landing = Parcel.LandingType.Direct;
parcel.MaxPrims = 20000;
parcel.Name = "Simian";
parcel.Status = Parcel.ParcelStatus.Leased;
parcel.UserLocation = (parcel.AABBMin + parcel.AABBMax) * 0.5f;
parcel.Bitmap = new byte[512];
for (int i = 0; i < 512; i++)
parcel.Bitmap[i] = Byte.MaxValue;
// The parcelOverlay defaults to all zeroes, and the LocalID of this parcel is zero,
// so we don't need to modify parcelOverlay before calling this
UpdateParcelSize(ref parcel);
// Add the default parcel to the list
parcels[parcel.LocalID] = parcel;
server.UDP.RegisterPacketCallback(PacketType.ParcelPropertiesRequest, ParcelPropertiesRequestHandler);
server.UDP.RegisterPacketCallback(PacketType.ParcelPropertiesUpdate, ParcelPropertiesUpdateHandler);
}
public void Stop()
{
}
public void SendParcelOverlay(Agent agent)
{
const int LAND_BLOCKS_PER_PACKET = 1024;
byte[] byteArray = new byte[LAND_BLOCKS_PER_PACKET];
int byteArrayCount = 0;
int sequenceID = 0;
for (int y = 0; y < 64; y++)
{
for (int x = 0; x < 64; x++)
{
byte tempByte = 0; // The flags for the current 4x4m parcel square
Parcel parcel;
if (parcels.TryGetValue(parcelOverlay[y * 64 + x], out parcel))
{
// Set the ownership/sale flag
if (parcel.OwnerID == agent.AgentID)
tempByte = (byte)ParcelOverlayType.OwnedBySelf;
else if (parcel.AuctionID != 0)
tempByte = (byte)ParcelOverlayType.Auction;
else if (parcel.SalePrice > 0 && (parcel.AuthBuyerID == UUID.Zero || parcel.AuthBuyerID == agent.AgentID))
tempByte = (byte)ParcelOverlayType.ForSale;
else if (parcel.GroupID != UUID.Zero)
tempByte = (byte)ParcelOverlayType.OwnedByGroup;
else if (parcel.OwnerID != UUID.Zero)
tempByte = (byte)ParcelOverlayType.OwnedByOther;
else
tempByte = (byte)ParcelOverlayType.Public;
// Set the border flags
if (x == 0)
tempByte |= (byte)ParcelOverlayType.BorderWest;
else if (parcelOverlay[y * 64 + (x - 1)] != parcel.LocalID)
// Parcel to the west is different from the current parcel
tempByte |= (byte)ParcelOverlayType.BorderWest;
if (y == 0)
tempByte |= (byte)ParcelOverlayType.BorderSouth;
else if (parcelOverlay[(y - 1) * 64 + x] != parcel.LocalID)
// Parcel to the south is different from the current parcel
tempByte |= (byte)ParcelOverlayType.BorderSouth;
byteArray[byteArrayCount] = tempByte;
++byteArrayCount;
if (byteArrayCount >= LAND_BLOCKS_PER_PACKET)
{
// Send a ParcelOverlay packet
ParcelOverlayPacket overlay = new ParcelOverlayPacket();
overlay.ParcelData.SequenceID = sequenceID;
overlay.ParcelData.Data = byteArray;
server.UDP.SendPacket(agent.AgentID, overlay, PacketCategory.State);
byteArrayCount = 0;
++sequenceID;
}
}
else
{
Logger.Log("Parcel overlay references missing parcel " + parcelOverlay[y * 64 + x],
Helpers.LogLevel.Warning);
}
}
}
}
void UpdateParcelSize(ref Parcel parcel)
{
int minX = 64;
int minY = 64;
int maxX = 0;
int maxY = 0;
int area = 0;
for (int y = 0; y < 64; y++)
{
for (int x = 0; x < 64; x++)
{
if (parcelOverlay[y * 64 + x] == parcel.LocalID)
{
int x4 = x * 4;
int y4 = y * 4;
if (minX > x4) minX = x4;
if (minY > y4) minY = y4;
if (maxX < x4) maxX = x4;
if (maxX < y4) maxY = y4;
area += 16;
}
}
}
parcel.AABBMin.X = minX;
parcel.AABBMin.Y = minY;
parcel.AABBMax.X = maxX;
parcel.AABBMax.Y = maxY;
parcel.Area = area;
}
void SendParcelProperties(int parcelID, int sequenceID, bool snapSelection, ParcelResult result,
Agent agent)
{
Parcel parcel;
if (parcels.TryGetValue(parcelID, out parcel))
{
ParcelPropertiesPacket properties = new ParcelPropertiesPacket();
properties.AgeVerificationBlock.RegionDenyAgeUnverified = false;
properties.ParcelData.AABBMax = parcel.AABBMax;
properties.ParcelData.AABBMin = parcel.AABBMin;
properties.ParcelData.Area = parcel.Area;
properties.ParcelData.AuctionID = parcel.AuctionID;
properties.ParcelData.AuthBuyerID = parcel.AuthBuyerID;
properties.ParcelData.Bitmap = parcel.Bitmap;
properties.ParcelData.Category = (byte)parcel.Category;
properties.ParcelData.ClaimDate = (int)Utils.DateTimeToUnixTime(parcel.ClaimDate);
properties.ParcelData.ClaimPrice = parcel.ClaimPrice;
properties.ParcelData.Desc = Utils.StringToBytes(parcel.Desc);
properties.ParcelData.GroupID = parcel.GroupID;
properties.ParcelData.GroupPrims = parcel.GroupPrims;
properties.ParcelData.IsGroupOwned = parcel.IsGroupOwned;
properties.ParcelData.LandingType = (byte)parcel.Landing;
properties.ParcelData.LocalID = parcel.LocalID;
properties.ParcelData.MaxPrims = parcel.MaxPrims;
properties.ParcelData.MediaAutoScale = parcel.Media.MediaAutoScale;
properties.ParcelData.MediaID = parcel.Media.MediaID;
properties.ParcelData.MediaURL = Utils.StringToBytes(parcel.Media.MediaURL);
properties.ParcelData.MusicURL = Utils.StringToBytes(parcel.MusicURL);
properties.ParcelData.Name = Utils.StringToBytes(parcel.Name);
properties.ParcelData.OtherCleanTime = parcel.OtherCleanTime;
properties.ParcelData.OtherCount = parcel.OtherCount;
properties.ParcelData.OtherPrims = parcel.OtherPrims;
properties.ParcelData.OwnerID = parcel.OwnerID;
properties.ParcelData.OwnerPrims = parcel.OwnerPrims;
properties.ParcelData.ParcelFlags = (uint)parcel.Flags;
properties.ParcelData.ParcelPrimBonus = parcel.ParcelPrimBonus;
properties.ParcelData.PassHours = parcel.PassHours;
properties.ParcelData.PassPrice = parcel.PassPrice;
properties.ParcelData.PublicCount = parcel.PublicCount;
properties.ParcelData.RegionDenyAnonymous = parcel.RegionDenyAnonymous;
properties.ParcelData.RegionDenyIdentified = false; // Deprecated
properties.ParcelData.RegionDenyTransacted = false; // Deprecated
properties.ParcelData.RegionPushOverride = parcel.RegionPushOverride;
properties.ParcelData.RentPrice = parcel.RentPrice;
properties.ParcelData.RequestResult = (int)result;
properties.ParcelData.SalePrice = parcel.SalePrice;
properties.ParcelData.SelectedPrims = 0; // TODO:
properties.ParcelData.SelfCount = parcel.SelfCount;
properties.ParcelData.SequenceID = sequenceID;
properties.ParcelData.SimWideMaxPrims = parcel.SimWideMaxPrims;
properties.ParcelData.SimWideTotalPrims = parcel.SimWideTotalPrims;
properties.ParcelData.SnapSelection = snapSelection;
properties.ParcelData.SnapshotID = parcel.SnapshotID;
properties.ParcelData.Status = (byte)parcel.Status;
properties.ParcelData.TotalPrims = parcel.TotalPrims;
properties.ParcelData.UserLocation = parcel.UserLocation;
properties.ParcelData.UserLookAt = parcel.UserLookAt;
// HACK: Make everyone think they are the owner of this parcel
properties.ParcelData.OwnerID = agent.AgentID;
server.UDP.SendPacket(agent.AgentID, properties, PacketCategory.Transaction);
}
else
{
Logger.Log("SendParcelProperties() called for unknown parcel " + parcelID, Helpers.LogLevel.Warning);
}
}
void ParcelPropertiesRequestHandler(Packet packet, Agent agent)
{
ParcelPropertiesRequestPacket request = (ParcelPropertiesRequestPacket)packet;
// TODO: Replace with HashSet when we switch to .NET 3.5
List<int> parcels = new List<int>();
// Convert the boundaries to integers
int north = (int)Math.Round(request.ParcelData.North) / 4;
int east = (int)Math.Round(request.ParcelData.East) / 4;
int south = (int)Math.Round(request.ParcelData.South) / 4;
int west = (int)Math.Round(request.ParcelData.West) / 4;
// Find all of the parcels within the given boundaries
int xLen = east - west;
int yLen = north - south;
for (int x = 0; x < xLen; x++)
{
for (int y = 0; y < yLen; y++)
{
if (west + x < 64 && south + y < 64)
{
int currentParcelID = parcelOverlay[(south + y) * 64 + (west + x)];
if (!parcels.Contains(currentParcelID))
parcels.Add(currentParcelID);
}
}
}
ParcelResult result = ParcelResult.NoData;
if (parcels.Count == 1)
result = ParcelResult.Single;
else if (parcels.Count > 1)
result = ParcelResult.Multiple;
for (int i = 0; i < parcels.Count; i++)
SendParcelProperties(parcels[i], request.ParcelData.SequenceID, request.ParcelData.SnapSelection, result, agent);
}
void ParcelPropertiesUpdateHandler(Packet packet, Agent agent)
{
ParcelPropertiesUpdatePacket update = (ParcelPropertiesUpdatePacket)packet;
Parcel parcel;
if (parcels.TryGetValue(update.ParcelData.LocalID, out parcel))
{
parcel.AuthBuyerID = update.ParcelData.AuthBuyerID;
parcel.Category = (Parcel.ParcelCategory)update.ParcelData.Category;
parcel.Desc = Utils.BytesToString(update.ParcelData.Desc);
parcel.Flags = (Parcel.ParcelFlags)update.ParcelData.ParcelFlags;
parcel.GroupID = update.ParcelData.GroupID;
parcel.Landing = (Parcel.LandingType)update.ParcelData.LandingType;
parcel.Media.MediaAutoScale = update.ParcelData.MediaAutoScale;
parcel.Media.MediaID = update.ParcelData.MediaID;
parcel.Media.MediaURL = Utils.BytesToString(update.ParcelData.MediaURL);
parcel.MusicURL = Utils.BytesToString(update.ParcelData.MusicURL);
parcel.Name = Utils.BytesToString(update.ParcelData.Name);
parcel.PassHours = update.ParcelData.PassHours;
parcel.PassPrice = update.ParcelData.PassPrice;
parcel.SalePrice = update.ParcelData.SalePrice;
parcel.SnapshotID = update.ParcelData.SnapshotID;
parcel.UserLocation = update.ParcelData.UserLocation;
parcel.UserLookAt = update.ParcelData.UserLookAt;
lock (parcels)
parcels[parcel.LocalID] = parcel;
if (update.ParcelData.Flags != 0)
SendParcelProperties(parcel.LocalID, 0, false, ParcelResult.Single, agent);
}
else
{
Logger.Log("Got a ParcelPropertiesUpdate for an unknown parcel " + update.ParcelData.LocalID,
Helpers.LogLevel.Warning);
}
}
}
}
| |
using System;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Threading;
using Moq;
using NUnit.Framework;
namespace Bud {
public class BuilderTest {
[Test]
public void TestExecute_places_output_into_OutputDir() {
using (var tmpDir = new TmpDir()) {
var fooTask = MockBuildTasks.GenerateFile("createFoo", "foo", "42").Object;
Builder.Execute(tmpDir.Path, tmpDir.CreateDir("out"), tmpDir.CreateDir(".bud"), fooTask);
FileAssert.AreEqual(tmpDir.CreateFile("42"), tmpDir.CreatePath("out", "foo"));
}
}
[Test]
public void TestExecute_executes_dependencies() {
using (var tmpDir = new TmpDir()) {
var fooTask = MockBuildTasks.GenerateFile("createFoo", "foo", "42").Object;
var barTask = MockBuildTasks.GenerateFile("createBar", "bar", "9001", fooTask).Object;
Builder.Execute(tmpDir.Path, tmpDir.CreateDir("out"), tmpDir.CreateDir(".bud"), barTask);
FileAssert.AreEqual(tmpDir.CreateFile("42"), tmpDir.CreatePath("out", "foo"));
FileAssert.AreEqual(tmpDir.CreateFile("9001"), tmpDir.CreatePath("out", "bar"));
}
}
[Test]
public void TestExecute_dependency_results_reference_build_tasks() {
using (var tmpDir = new TmpDir()) {
var fooTask = MockBuildTasks.NoOp("foo").Object;
var barTask = MockBuildTasks.NoOp("bar", fooTask)
.WithExecuteAction((sourceDir, outputDir, dependencyResults) => {
Assert.AreEqual(new []{fooTask},
dependencyResults.Select(result => result.BuildTask));
}).Object;
Builder.Execute(tmpDir.Path, tmpDir.CreateDir("out"), tmpDir.CreateDir(".bud"), barTask);
}
}
[Test]
public void TestExecute_executes_the_same_tasks_once() {
using (var tmpDir = new TmpDir()) {
var fooTaskMock = MockBuildTasks.GenerateFile("createFoo", "foo", "42");
Builder.Execute(tmpDir.Path, tmpDir.CreateDir("out"), tmpDir.CreateDir(".bud"), fooTaskMock.Object);
Builder.Execute(tmpDir.Path, tmpDir.CreateDir("out"), tmpDir.CreateDir(".bud"), fooTaskMock.Object);
VerifyExecutedOnce(fooTaskMock);
}
}
[Test]
public void TestExecute_throws_when_two_tasks_produce_file_with_same_name() {
using (var tmpDir = new TmpDir()) {
var foo1TaskMock = MockBuildTasks.GenerateFile("createFoo1", "foo", "1");
var foo2TaskMock = MockBuildTasks.GenerateFile("createFoo2", "foo", "2", foo1TaskMock.Object);
var exception = Assert.Throws<Exception>(() => {
Builder.Execute(tmpDir.Path, tmpDir.CreateDir("out"), tmpDir.CreateDir(".bud"), foo2TaskMock.Object);
});
Assert.That(exception.Message,
Contains.Substring("Tasks 'createFoo1' and 'createFoo2' are clashing. " +
"They produced the same file 'foo'."));
}
}
[Test]
public void TestExecute_rebuilds_task_when_signature_of_dependency_changes() {
using (var tmpDir = new TmpDir()) {
var fooTaskMock = MockBuildTasks.GenerateFile("createFoo", "foo", "42");
var barTaskMock = MockBuildTasks.GenerateFile("createBar", "bar", "9001", fooTaskMock.Object);
Builder.Execute(tmpDir.Path, tmpDir.CreateDir("out"), tmpDir.CreateDir(".bud"), barTaskMock.Object);
var changedFooTaskMock = MockBuildTasks.GenerateFile("createFoo", "foo", "changed");
var barTaskMock2 = MockBuildTasks.GenerateFile("createBar", "bar", "9001", changedFooTaskMock.Object);
Builder.Execute(tmpDir.Path, tmpDir.CreateDir("out"), tmpDir.CreateDir(".bud"), barTaskMock2.Object);
VerifyExecutedOnce(barTaskMock2);
}
}
[Test]
public void TestExecute_same_dependencies_are_executed_once() {
using (var tmpDir = new TmpDir()) {
var fooTaskMock = MockBuildTasks.GenerateFile("createFoo", "foo", "42");
var barTaskMock = MockBuildTasks.GenerateFile("createBar", "bar", "9001",
fooTaskMock.Object, fooTaskMock.Object);
Builder.Execute(tmpDir.Path, tmpDir.CreateDir("out"), tmpDir.CreateDir(".bud"), barTaskMock.Object);
VerifyExecutedOnce(fooTaskMock);
}
}
[Test]
public void TestExecute_executes_tasks_in_parallel() {
using (var tmpDir = new TmpDir()) {
var countdownLatch = new CountdownEvent(2);
var buildTask1Mock = MockBuildTasks.Action("latch1", () => {
countdownLatch.Signal();
countdownLatch.Wait();
});
var buildTask2Mock = MockBuildTasks.Action("latch2", () => {
countdownLatch.Signal();
countdownLatch.Wait();
});
Builder.Execute(tmpDir.Path, tmpDir.CreateDir("out"), tmpDir.CreateDir(".bud"), buildTask1Mock.Object,
buildTask2Mock.Object);
}
}
[Test]
public void TestExecute_throws_when_two_tasks_have_the_same_signature() {
using (var tmpDir = new TmpDir()) {
var task1Mock = MockBuildTasks.NoOp("task1").WithSignature("foo");
var task2Mock = MockBuildTasks.NoOp("task2", task1Mock.Object).WithSignature("foo");
var exception = Assert.Throws<BuildTaskClashException>(() => {
Builder.Execute(tmpDir.Path, tmpDir.CreateDir("out"), tmpDir.CreateDir(".bud"), task2Mock.Object);
});
Assert.That(exception.Message,
Contains.Substring("Tasks 'task1' and 'task2' are clashing. " +
"They have the same signature 'foo'."));
}
}
[Test]
public void TestExecute_passes_the_source_dir_to_tasks() {
using (var tmpDir = new TmpDir()) {
var sourceDir = tmpDir.CreateDir("src");
var outputDir = tmpDir.CreatePath("out");
var metaDir = tmpDir.CreatePath(".bud");
var sourceFile = tmpDir.CreateFile("42", "src", "foo");
var task1Mock = MockBuildTasks.CopySourceFile("task1", "foo", "bar");
Builder.Execute(sourceDir, outputDir, metaDir, task1Mock.Object);
FileAssert.AreEqual(sourceFile, Path.Combine(outputDir, "bar"));
}
}
[Test]
public void TestExecute_cleans_unfinished_directories_before_starting_the_build() {
using (var tmpDir = new TmpDir()) {
var partialTask = MockBuildTasks.NoOp("task1")
.WithExecuteAction((sourceDir, outputDir, deps) => {
File.WriteAllText(Path.Combine(outputDir, "foo"), "42");
throw new Exception("Test exception");
});
try {
Builder.Execute(tmpDir.Path, tmpDir.CreateDir("out"), tmpDir.CreateDir(".bud"), partialTask.Object);
} catch (Exception) {
// ignored
}
var fullTask = MockBuildTasks.NoOp("task1")
.WithExecuteAction((sourceDir, outputDir, deps) =>
File.WriteAllText(Path.Combine(outputDir, "bar"), "9001"));
Builder.Execute(tmpDir.Path, tmpDir.CreateDir("out"), tmpDir.CreateDir(".bud"), fullTask.Object);
FileAssert.AreEqual(tmpDir.CreateFile("9001"), tmpDir.CreatePath("out", "bar"));
FileAssert.DoesNotExist(tmpDir.CreatePath("out", "foo"));
}
}
[Test]
public void TestExecute_does_not_have_race_conditions() {
for (int i = 0; i < 5; i++) {
using (var tmpDir = new TmpDir()) {
var sourceDir = tmpDir.CreateDir("src");
var outputDir = tmpDir.CreatePath("out");
var metaDir = tmpDir.CreatePath(".bud");
var generatedFiles = Enumerable.Range(0, 10).Select(idx => $"file_{idx}").ToList();
var fileGenerators = generatedFiles.Select(file => MockBuildTasks.GenerateFile(file, file, file).Object);
Builder.Execute(sourceDir, outputDir, metaDir, fileGenerators);
foreach (var generatedFile in generatedFiles) {
FileAssert.AreEqual(tmpDir.CreateFile(generatedFile), Path.Combine(outputDir, generatedFile));
}
}
}
}
[Test]
public void TestExecute_name_clash_throws() {
using (var tmpDir = new TmpDir()) {
var fooTask1 = MockBuildTasks.NoOp("foo").WithSignature("1").Object;
var fooTask2 = MockBuildTasks.NoOp("foo").WithSignature("2").Object;
var exception = Assert.Throws<Exception>(() => Builder.Execute(tmpDir.Path, tmpDir.CreateDir("out"),
tmpDir.CreateDir(".bud"), fooTask1, fooTask2));
Assert.AreEqual("Detected multiple tasks with the name 'foo'. Tasks must have unique names.",
exception.Message);
}
}
[Test]
public void TestExecute_detects_cycles() {
using (var tmpDir = new TmpDir()) {
var fooTask1 = MockBuildTasks.NoOp("foo1").WithSignature("1");
var fooTask2 = MockBuildTasks.NoOp("foo2").WithSignature("2").WithDependencies(new []{fooTask1.Object});
fooTask1.WithDependencies(new[] {fooTask2.Object});
var exception = Assert.Throws<Exception>(() => Builder.Execute(tmpDir.Path, tmpDir.CreateDir("out"),
tmpDir.CreateDir(".bud"), fooTask1.Object,
fooTask2.Object));
Assert.AreEqual("Detected a dependency cycle: 'foo1 depends on foo2 depends on foo1'.",
exception.Message);
}
}
private static void VerifyExecutedOnce(Mock<IBuildTask> fooTaskMock)
=> fooTaskMock.Verify(f => f.Execute(It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<ImmutableArray<BuildTaskResult>>()),
Times.Once);
}
}
| |
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Data;
using System.Diagnostics;
using VCM.Common;
using VCM.Common.Log;
using System.Data.SqlClient;
using System.Globalization;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using Microsoft.Practices.EnterpriseLibrary.Common;
using System.Data.Common;
/// <summary>
/// Summary description for OpenF2New
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class OpenF2New : System.Web.Services.WebService
{
public OpenF2New()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
public static string _userState;
public static string _userDetail;
string IPAddress;
[WebMethod(EnableSession = true)]
public DataSet VCM_AutoURL_Validate_User_Info(string URLEncrypted, string IPAddress, int ApplicationCode)
{
DataSet dst = new DataSet();
try
{
dst = vcmProductNamespace.cDbHandler.VCM_AutoURL_Validate_User_Info(URLEncrypted, IPAddress, ApplicationCode);
}
catch (Exception ex)
{
LogUtility.Error("openf2New.cs", "VCM_AutoURL_Validate_User_Info", ex.Message, ex);
}
return dst;
}
[WebMethod(EnableSession = true)]
public string GetUtcSqlServerDate()
{
string returnDate = string.Empty;
Database dbHelper = null;
DbCommand cmd = null;
SqlDataReader sqlReader = null;
try
{
dbHelper = DatabaseFactory.CreateDatabase();
cmd = dbHelper.GetStoredProcCommand("GET_UTCSERVERDATE");
sqlReader = (SqlDataReader)dbHelper.ExecuteReader(cmd);
if (sqlReader.Read())
{
returnDate = Convert.ToString(sqlReader.GetValue(0));
}
sqlReader.Close();
}
catch (Exception ex)
{
LogUtility.Error("openf2New.cs", "GetUtcSqlServerDate", ex.Message, ex);
}
finally
{
cmd = null;
dbHelper = null;
sqlReader = null;
}
return returnDate;
}
[WebMethod(EnableSession = true)]
public long CheckUserStatus(string strEmailId, string strIpAddress)
{
long lReturnValue = -1;
Database dbHelper = null;
DbCommand cmd = null;
try
{
dbHelper = DatabaseFactory.CreateDatabase();
cmd = dbHelper.GetStoredProcCommand("Proc_Check_User_Status");
dbHelper.AddInParameter(cmd, "@p_UserLogin", DbType.String, strEmailId);
dbHelper.AddInParameter(cmd, "@p_IPAddress", DbType.String, strIpAddress);
lReturnValue = Convert.ToInt64(dbHelper.ExecuteScalar(cmd));
cmd = null;
dbHelper = null;
}
catch (Exception ex)
{
LogUtility.Error("openf2New.cs", "CheckUserStatus", ex.Message, ex);
}
finally
{
cmd = null;
dbHelper = null;
}
return lReturnValue;
}
[WebMethod(EnableSession = true)]
public int SetUserLoginActivatationFLag(long lUserID)
{
int intReturnValue = -1;
Database dbHelper = null;
DbCommand cmd = null;
try
{
dbHelper = DatabaseFactory.CreateDatabase();
cmd = dbHelper.GetSqlStringCommand("Update User_Login_DTL set Login_Activate_FLag='0' Where UserId=" + lUserID);
dbHelper.ExecuteNonQuery(cmd);
cmd = null;
dbHelper = null;
intReturnValue = 1;
}
catch (Exception ex)
{
LogUtility.Error("openf2New.cs", "SetUserLoginActivatationFLag", ex.Message, ex);
}
finally
{
cmd = null;
dbHelper = null;
}
return intReturnValue;
}
[WebMethod(EnableSession = true)]
public bool SetUserPasswordFlag(long lUserID, int iFlag, string strEmail)
{
bool bFlag = false;
Database dbHelper = null;
DbCommand cmd = null;
try
{
dbHelper = DatabaseFactory.CreateDatabase();
if (string.IsNullOrEmpty(strEmail))
{
cmd = dbHelper.GetSqlStringCommand("UPDATE user_login_dtl SET change_pwd_flag = " + iFlag + " WHERE userid=" + lUserID);
}
else
{
cmd = dbHelper.GetSqlStringCommand("Update User_Login_Dtl Set Change_Pwd_Flag = " + iFlag + " Where Login_ID ='" + strEmail + "'");
}
dbHelper.ExecuteNonQuery(cmd);
bFlag = true;
}
catch (Exception ex)
{
bFlag = false;
// throw;
LogUtility.Error("openf2New.cs", "SetUserLoginActivatationFLag", ex.Message, ex);
}
finally
{
cmd = null;
dbHelper = null;
}
return bFlag;
}
[WebMethod(EnableSession = true)]
public bool ChangePassword(Int64 lUserId, string oldPassword, string newPassword)
{
bool bFlag = false;
Database dbHelper = null;
DbCommand cmd = null;
try
{
dbHelper = DatabaseFactory.CreateDatabase(System.Configuration.ConfigurationManager.AppSettings["ConnectionString"].ToString());
cmd = dbHelper.GetStoredProcCommand("Proc_Web_Submit_User_Pwd_SecQueAns");
dbHelper.AddInParameter(cmd, "@p_UserID", DbType.Int64, lUserId);
dbHelper.AddInParameter(cmd, "@p_Password", DbType.String, sMD5(newPassword));
dbHelper.AddInParameter(cmd, "@p_Security_Question", DbType.String, DBNull.Value);
dbHelper.AddInParameter(cmd, "@p_Security_Answer", DbType.String, DBNull.Value);
dbHelper.ExecuteNonQuery(cmd);
bFlag = true;
}
catch (Exception ex)
{
bFlag = false;
// throw;
LogUtility.Error("openf2New.cs", "ChangePassword", ex.Message, ex);
}
finally
{
cmd = null;
dbHelper = null;
}
return bFlag;
}
[WebMethod(EnableSession = true)]
public string GetEmailIDFromUserID(long lUserId)
{
string strReturnValue = "0";
Database dbHelper = null;
DbCommand cmd = null;
SqlDataReader sqlReader = null;
try
{
dbHelper = DatabaseFactory.CreateDatabase();
cmd = dbHelper.GetStoredProcCommand("Proc_Get_LoginId_From_UserId");
dbHelper.AddInParameter(cmd, "@p_UserId", DbType.Int32, lUserId);
sqlReader = (SqlDataReader)dbHelper.ExecuteReader(cmd);
if (sqlReader.Read())
{
strReturnValue = Convert.ToString(sqlReader["LoginId"]);
}
sqlReader.Close();
}
catch (Exception ex)
{
// throw;
LogUtility.Error("openf2New.cs", "GetEmailIDFromUserID", ex.Message, ex);
}
finally
{
cmd = null;
dbHelper = null;
sqlReader = null;
}
return strReturnValue;
}
[WebMethod(EnableSession = true)]
public string GetUserCustomerDetails(long lUserId)
{
string strReturnValue = "0#0";
Database dbHelper = null;
DbCommand cmd = null;
SqlDataReader sqlReader = null;
try
{
dbHelper = DatabaseFactory.CreateDatabase();
cmd = dbHelper.GetStoredProcCommand("Proc_Get_AppStore_User_Customer_Dtl");
dbHelper.AddInParameter(cmd, "@p_UserId", DbType.Int64, lUserId);
sqlReader = (SqlDataReader)dbHelper.ExecuteReader(cmd);
if (sqlReader.Read())
{
strReturnValue = sqlReader["UserName"] + "#" + sqlReader["Mnemonic"];
}
sqlReader.Close();
}
catch (Exception ex)
{
// throw;
LogUtility.Error("openf2New.cs", "GetUserCustomerDetails", ex.Message, ex);
}
finally
{
cmd = null;
dbHelper = null;
sqlReader = null;
}
return strReturnValue;
}
[WebMethod(EnableSession = true)]
public string GetUserSecurityQuestion_And_Answer(string strEmail)
{
string strReturnValue = "0#0";
Database dbHelper = null;
DbCommand cmd = null;
SqlDataReader sqlReader = null;
try
{
dbHelper = DatabaseFactory.CreateDatabase(System.Configuration.ConfigurationManager.AppSettings["ConnectionString"].ToString());
cmd = dbHelper.GetSqlStringCommand("Select SecQuestion As PasswordQuestion, lower(SecAnswer) PasswordAnswer from userconfig where EmailId ='" + strEmail + "'");
sqlReader = (SqlDataReader)dbHelper.ExecuteReader(cmd);
if (sqlReader.Read())
{
strReturnValue = sqlReader["PasswordQuestion"] + "#" + sqlReader["PasswordAnswer"];
}
sqlReader.Close();
}
catch (Exception ex)
{
// throw;
LogUtility.Error("openf2New.cs", "GetUserSecurityQuestion_And_Answer", ex.Message, ex);
}
finally
{
cmd = null;
dbHelper = null;
sqlReader = null;
}
return strReturnValue;
}
[WebMethod(EnableSession = true)]
public long GetUserID(string strEmailId)
{
long lReturnValue = -1;
Database dbHelper = null;
DbCommand cmd = null;
try
{
dbHelper = DatabaseFactory.CreateDatabase();
cmd = dbHelper.GetStoredProcCommand("PROC_GET_USER_ID");
dbHelper.AddInParameter(cmd, "@p_Login_Id", DbType.String, strEmailId);
lReturnValue = Convert.ToInt64(dbHelper.ExecuteScalar(cmd));
cmd = null;
dbHelper = null;
}
catch (Exception ex)
{
// throw;
LogUtility.Error("openf2New.cs", "GetUserID", ex.Message, ex);
}
finally
{
cmd = null;
dbHelper = null;
}
return lReturnValue;
}
[WebMethod(EnableSession = true)]
public string GetCMEUserIdFromGuid(string pGuid)
{
string strReturnValue = "0#0";
Database dbHelper = null;
DbCommand cmd = null;
SqlDataReader sqlReader = null;
try
{
dbHelper = DatabaseFactory.CreateDatabase();
cmd = dbHelper.GetStoredProcCommand("Proc_Get_CME_UserID_From_GUID");
dbHelper.AddInParameter(cmd, "@p_GUID", DbType.String, pGuid);
sqlReader = (SqlDataReader)dbHelper.ExecuteReader(cmd);
if (sqlReader.Read())
{
strReturnValue = sqlReader["UserId"] + "#" + sqlReader["User_GUID"];
}
sqlReader.Close();
}
catch (Exception ex)
{
// throw;
LogUtility.Error("openf2New.cs", "GetCMEUserIdFromGuid", ex.Message, ex);
}
finally
{
cmd = null;
dbHelper = null;
sqlReader = null;
}
return strReturnValue;
}
[WebMethod(EnableSession = true)]
public int SaveCMEUserGuid(long pUserId, string pGUID)
{
int intReturnValue = -1;
Database dbHelper = null;
DbCommand cmd = null;
try
{
dbHelper = DatabaseFactory.CreateDatabase();
cmd = dbHelper.GetStoredProcCommand("Proc_Web_Submit_CME_User_GUID");
dbHelper.AddInParameter(cmd, "@p_UserId", DbType.Int64, pUserId);
dbHelper.AddInParameter(cmd, "@p_GUID", DbType.String, pGUID);
dbHelper.ExecuteNonQuery(cmd);
cmd = null;
dbHelper = null;
intReturnValue = 1;
}
catch (Exception ex)
{
// throw;
LogUtility.Error("openf2New.cs", "SaveCMEUserGuid", ex.Message, ex);
}
finally
{
cmd = null;
dbHelper = null;
}
return intReturnValue;
}
[WebMethod(EnableSession = true)]
private string sMD5(string str)
{
System.Security.Cryptography.MD5CryptoServiceProvider md5Prov = new System.Security.Cryptography.MD5CryptoServiceProvider();
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
byte[] md5 = md5Prov.ComputeHash(encoding.GetBytes(str));
string _result = "";
for (int i = 0; i < md5.Length; i++)
{
// _result += String.Format("{0:x}", md5[i]);
_result += ("0" + String.Format("{0:X}", md5[i])).Substring(Convert.ToInt32(md5[i]) <= 15 ? 0 : 1, 2);
}
return _result;
}
[WebMethod(EnableSession = true)]
public bool ValidateUser(string username, string password)
{
Database dbHelper = null;
DbCommand cmd = null;
SqlDataReader sqlReader = null;
int userLogin = 1;
try
{
dbHelper = DatabaseFactory.CreateDatabase(System.Configuration.ConfigurationManager.AppSettings["ConnectionString"].ToString());
cmd = dbHelper.GetStoredProcCommand("Proc_Web_User_Validate");
dbHelper.AddInParameter(cmd, "@p_LoginId", DbType.String, username);
dbHelper.AddInParameter(cmd, "@p_Password", DbType.String, sMD5(password));
sqlReader = (SqlDataReader)dbHelper.ExecuteReader(cmd);
if (sqlReader.Read())
{
if (sqlReader["MsgId"].ToString() == "1") // means user validate
{
//get all users details
_userState = sqlReader["UserId"].ToString() + "#" + sqlReader["EmailId"].ToString() + "#" + sqlReader["CustomerId"].ToString() + "#" + sqlReader["UserName"].ToString() + "#" + sqlReader["User_Type"].ToString();
_userState += "#" + sqlReader["Sec_Que_Change_Req_Falg"].ToString() + "#" + sqlReader["Password_Chagne_Req_Flag"].ToString() + "#" + sqlReader["LoginTypeId"].ToString() + "#" + sqlReader["LastActivityDate"].ToString();
userLogin = 1;
}
else
{
// user not validate
userLogin = Convert.ToInt16(sqlReader["MsgId"].ToString());
_userState = sqlReader["MsgId"].ToString() + "#" + sqlReader["UserId"].ToString() + "#" + sqlReader["EmailId"].ToString();
}
}
sqlReader.Close();
}
catch (Exception ex)
{
// throw;
LogUtility.Error("openf2New.cs", "ValidateUser", ex.Message, ex);
}
finally
{
cmd = null;
dbHelper = null;
sqlReader = null;
}
if (userLogin == 1)
return true;
else
return false;
}
[WebMethod(EnableSession = true)]
public string GetUserstate()
{
return _userState;
}
[WebMethod(EnableSession = true)]
public DataSet GetAutoURLGeoIPInfo(string IPAddress)
{
DataSet dsGeoIP = new DataSet();
try
{
dsGeoIP = vcmProductNamespace.cDbHandler.VCM_AutoURL_GeoIP_Info(IPAddress);
}
catch (Exception ex)
{
// throw;
LogUtility.Error("openf2New.cs", "GetAutoURLGeoIPInfo", ex.Message, ex);
}
return dsGeoIP;
}
[WebMethod(EnableSession = true)]
public DataSet BeastApps_SharedAutoURL_Validate(string pRefId)
{
DataSet dstResult = new DataSet();
try
{
dstResult = vcmProductNamespace.cDbHandler.BeastApps_SharedAutoURL_Validate(pRefId);
}
catch (Exception ex)
{
// throw;
LogUtility.Error("openf2New.cs", "BeastApps_SharedAutoURL_Validate", ex.Message, ex);
}
return dstResult;
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.IO;
using System.Management.Automation;
using System.Text;
using System.Globalization;
// interfaces for host interaction
namespace Microsoft.PowerShell.Commands.Internal.Format
{
/// <summary>
/// Base class providing support for string manipulation.
/// This class is a tear off class provided by the LineOutput class
///
/// Assumptions (in addition to the assumptions made for LineOutput):
/// - characters map to one or more character cells
///
/// NOTE: we provide a base class that is valid for devices that have a
/// 1:1 mapping between a UNICODE character and a display cell
/// </summary>
internal class DisplayCells
{
internal virtual int Length(string str)
{
return Length(str, 0);
}
internal virtual int Length(string str, int offset)
{
return str.Length - offset;
}
internal virtual int Length(char character) { return 1; }
internal virtual int GetHeadSplitLength(string str, int displayCells)
{
return GetHeadSplitLength(str, 0, displayCells);
}
internal virtual int GetHeadSplitLength(string str, int offset, int displayCells)
{
int len = str.Length - offset;
return (len < displayCells) ? len : displayCells;
}
internal virtual int GetTailSplitLength(string str, int displayCells)
{
return GetTailSplitLength(str, 0, displayCells);
}
internal virtual int GetTailSplitLength(string str, int offset, int displayCells)
{
int len = str.Length - offset;
return (len < displayCells) ? len : displayCells;
}
#region Helpers
/// <summary>
/// Given a string and a number of display cells, it computes how many
/// characters would fit starting from the beginning or end of the string
/// </summary>
/// <param name="str">string to be displayed</param>
/// <param name="offset">offset inside the string</param>
/// <param name="displayCells">number of display cells</param>
/// <param name="head">if true compute from the head (i.e. k++) else from the tail (i.e. k--)</param>
/// <returns>number of characters that would fit</returns>
protected int GetSplitLengthInternalHelper(string str, int offset, int displayCells, bool head)
{
int filledDisplayCellsCount = 0; // number of cells that are filled in
int charactersAdded = 0; // number of characters that fit
int currCharDisplayLen; // scratch variable
int k = (head) ? offset : str.Length - 1;
int kFinal = (head) ? str.Length - 1 : offset;
while (true)
{
if ((head && (k > kFinal)) || ((!head) && (k < kFinal)))
{
break;
}
// compute the cell number for the current character
currCharDisplayLen = this.Length(str[k]);
if (filledDisplayCellsCount + currCharDisplayLen > displayCells)
{
// if we added this character it would not fit, we cannot continue
break;
}
// keep adding, we fit
filledDisplayCellsCount += currCharDisplayLen;
charactersAdded++;
// check if we fit exactly
if (filledDisplayCellsCount == displayCells)
{
// exact fit, we cannot add more
break;
}
k = (head) ? (k + 1) : (k - 1);
}
return charactersAdded;
}
#endregion
}
/// <summary>
/// Specifies special stream write processing.
/// </summary>
internal enum WriteStreamType
{
None,
Error,
Warning,
Verbose,
Debug,
Information
}
/// <summary>
/// Base class providing information about the screen device capabilities
/// and used to write the output strings to the text output device.
/// Each device supported will have to derive from it.
/// Examples of supported devices are:
/// * Screen Layout: it layers on top of Console and RawConsole
/// * File: it layers on top of a TextWriter
/// * In Memory text stream: it layers on top of an in memory buffer
/// * Printer: it layers on top of a memory buffer then sent to a printer device
///
/// Assumptions:
/// - Fixed pitch font: layout done in terms of character cells
/// - character cell layout not affected by bold, reverse screen, color, etc.
/// - returned values might change from call to call if the specific underlying
/// implementation allows window resizing
/// </summary>
internal abstract class LineOutput
{
/// <summary>
/// whether the device requres full buffering of formatting
/// objects before any processing
/// </summary>
internal virtual bool RequiresBuffering { get { return false; } }
/// <summary>
/// delegate the implementor of ExecuteBufferPlayBack should
/// call to cause the playback to happen when ready to execute
/// </summary>
internal delegate void DoPlayBackCall();
/// <summary>
/// if RequiresBuffering = true, this call will be made to
/// start the playback
/// </summary>
internal virtual void ExecuteBufferPlayBack(DoPlayBackCall playback) { }
///
/// <summary>
/// The number of columns the current device has
/// </summary>
internal abstract int ColumnNumber { get; }
/// <summary>
/// The number of rows the current device has
/// </summary>
internal abstract int RowNumber { get; }
/// <summary>
/// Write a line to the output device.
/// </summary>
/// <param name="s">
/// string to be written to the device
/// </param>
internal abstract void WriteLine(string s);
internal WriteStreamType WriteStream
{
get;
set;
}
/// <summary>
/// handle the stop processing signal.
/// Set a flag that will be checked during operations
/// </summary>
internal void StopProcessing()
{
_isStopping = true;
}
private bool _isStopping;
internal void CheckStopProcessing()
{
if (!_isStopping)
return;
throw new PipelineStoppedException();
}
/// <summary>
/// return an instance of the display helper tear off
/// </summary>
/// <value></value>
internal virtual DisplayCells DisplayCells
{
get
{
CheckStopProcessing();
// just return the default singelton implementation
return _displayCellsDefault;
}
}
/// <summary>
/// singleton used for the default implementation.
/// NOTE: derived classes may chose to provide a different
/// implementation by overriding
/// </summary>
protected static DisplayCells _displayCellsDefault = new DisplayCells();
}
/// <summary>
/// helper class to provide line breaking (based on device width)
/// and embedded newline processing
/// It needs to be provided with two callabacks for line processing
/// </summary>
internal class WriteLineHelper
{
#region callbacks
/// <summary>
/// delegate definition
/// </summary>
/// <param name="s">string to write</param>
internal delegate void WriteCallback(string s);
/// <summary>
/// instance of the delegate previously defined
/// for line that has EXACTLY this.ncols characters
/// </summary>
private WriteCallback _writeCall = null;
/// <summary>
/// instance of the delegate previously defined
/// for generic line, less that this.ncols characters
/// </summary>
private WriteCallback _writeLineCall = null;
#endregion
private bool _lineWrap;
/// <summary>
/// construct an instance, given the two callbacks
/// NOTE: if the underlying device treats the two cases as the
/// same, the same delegate can be passed twice
/// </summary>
/// <param name="lineWrap">true if we require line wrapping</param>
/// <param name="wlc">delegate for WriteLine(), must ben non null</param>
/// <param name="wc">delegate for Write(), if null, use the first parameter</param>
/// <param name="displayCells">helper object for manipulating strings</param>
internal WriteLineHelper(bool lineWrap, WriteCallback wlc, WriteCallback wc, DisplayCells displayCells)
{
if (wlc == null)
throw PSTraceSource.NewArgumentNullException("wlc");
if (displayCells == null)
throw PSTraceSource.NewArgumentNullException("displayCells");
_displayCells = displayCells;
_writeLineCall = wlc;
_writeCall = wc ?? wlc;
_lineWrap = lineWrap;
}
/// <summary>
/// main entry point to process a line
/// </summary>
/// <param name="s">string to process</param>
/// <param name="cols">width of the device</param>
internal void WriteLine(string s, int cols)
{
WriteLineInternal(s, cols);
}
/// <summary>
/// internal helper, needed because it might make recursive calls to itself
/// </summary>
/// <param name="val">string to process</param>
/// <param name="cols">width of the device</param>
private void WriteLineInternal(string val, int cols)
{
if (string.IsNullOrEmpty(val))
{
_writeLineCall(val);
return;
}
// If the output is being redirected, then we don't break val
if (!_lineWrap)
{
_writeCall(val);
return;
}
// check for line breaks
string[] lines = StringManipulationHelper.SplitLines(val);
// process the substrings as separate lines
for (int k = 0; k < lines.Length; k++)
{
// compute the display length of the string
int displayLength = _displayCells.Length(lines[k]);
if (displayLength < cols)
{
// NOTE: this is the case where where System.Console.WriteLine() would work just fine
_writeLineCall(lines[k]);
continue;
}
if (displayLength == cols)
{
// NOTE: this is the corner case where System.Console.WriteLine() cannot be called
_writeCall(lines[k]);
continue;
}
// the string does not fit, so we have to wrap around on multiple lines
string s = lines[k];
while (true)
{
// the string is still too long to fit, write the first cols characters
// and go back for more wraparound
int splitLen = _displayCells.GetHeadSplitLength(s, cols);
WriteLineInternal(s.Substring(0, splitLen), cols);
// chop off the first fieldWidth characters, already printed
s = s.Substring(splitLen);
if (_displayCells.Length(s) <= cols)
{
// if we fit, print the tail of the string and we are done
WriteLineInternal(s, cols);
break;
}
}
}
}
private DisplayCells _displayCells;
}
/// <summary>
/// Implementation of the ILineOutput interface accepting an instance of a
/// TextWriter abstract class
/// </summary>
internal class TextWriterLineOutput : LineOutput
{
#region ILineOutput methods
/// <summary>
/// get the columns on the screen
/// for files, it is settable at creation time
/// </summary>
internal override int ColumnNumber
{
get
{
CheckStopProcessing();
return _columns;
}
}
/// <summary>
/// get the # of rows on the screen: for files
/// we return -1, meaning infinite
/// </summary>
internal override int RowNumber
{
get
{
CheckStopProcessing();
return -1;
}
}
/// <summary>
/// write a line by delegating to the writer underneath
/// </summary>
/// <param name="s"></param>
internal override void WriteLine(string s)
{
CheckStopProcessing();
if (_suppressNewline)
{
_writer.Write(s);
}
else
{
_writer.WriteLine(s);
}
}
#endregion
/// <summary>
/// initialization of the object. It must be called before
/// attempting any operation
/// </summary>
/// <param name="writer">TextWriter to write to</param>
/// <param name="columns">max columns widths for the text</param>
internal TextWriterLineOutput(TextWriter writer, int columns)
{
_writer = writer;
_columns = columns;
}
/// <summary>
/// initialization of the object. It must be called before
/// attempting any operation
/// </summary>
/// <param name="writer">TextWriter to write to</param>
/// <param name="columns">max columns widths for the text</param>
/// <param name="suppressNewline">false to add a newline to the end of the output string, true if not</param>
internal TextWriterLineOutput(TextWriter writer, int columns, bool suppressNewline)
: this(writer, columns)
{
_suppressNewline = suppressNewline;
}
private int _columns = 0;
private TextWriter _writer = null;
private bool _suppressNewline = false;
}
/// <summary>
/// TextWriter to generate data for the Monad pipeline in a streaming fashion:
/// the provided callback will be called each time a line is written
/// </summary>
internal class StreamingTextWriter : TextWriter
{
#region tracer
[TraceSource("StreamingTextWriter", "StreamingTextWriter")]
private static PSTraceSource s_tracer = PSTraceSource.GetTracer("StreamingTextWriter", "StreamingTextWriter");
#endregion tracer
/// <summary>
/// create an instance by passing a delegate
/// </summary>
/// <param name="writeCall">delegate to write to</param>
/// <param name="culture">culture for this TextWriter</param>
internal StreamingTextWriter(WriteLineCallback writeCall, CultureInfo culture)
: base(culture)
{
if (writeCall == null)
throw PSTraceSource.NewArgumentNullException("writeCall");
_writeCall = writeCall;
}
#region TextWriter overrides
public override Encoding Encoding { get { return new UnicodeEncoding(); } }
public override void WriteLine(string s)
{
_writeCall(s);
}
#if CORECLR // TextWriter.Write(char value) is abstract method in CORE CLR
public override void Write(char c)
{
_writeCall(char.ToString(c));
}
#endif
#endregion
/// <summary>
/// delegate definition
/// </summary>
/// <param name="s">string to write</param>
internal delegate void WriteLineCallback(string s);
/// <summary>
/// instance of the delegate previously defined
/// </summary>
private WriteLineCallback _writeCall = null;
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.txt file at the root of this distribution.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
#pragma warning disable VSTHRD010
using System;
using System.Windows.Forms.Design;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Windows.Threading;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Settings;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Shell.Settings;
using Microsoft.Win32;
using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
namespace Microsoft.VisualStudio.Project
{
/// <summary>
/// This class implements an MSBuild logger that output events to VS outputwindow and tasklist.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "IDE")]
public class IDEBuildLogger : Logger, IDisposable
{
#region fields
private const string GeneralCollection = @"General";
private const string BuildVerbosityProperty = "MSBuildLoggerVerbosity";
private int currentIndent;
private IVsOutputWindowPane outputWindowPane;
// private string errorString = SR.GetString(SR.Error, CultureInfo.CurrentUICulture);
//private string warningString = SR.GetString(SR.Warning, CultureInfo.CurrentUICulture);
private TaskProvider taskProvider;
private IVsHierarchy hierarchy;
private IServiceProvider serviceProvider;
private bool haveCachedVerbosity = false;
// Queues to manage Tasks and Error output plus message logging
private ConcurrentQueue<Func<ErrorTask>> taskQueue;
private ConcurrentQueue<OutputQueueEntry> outputQueue;
#endregion
#region properties
public IServiceProvider ServiceProvider
{
get { return this.serviceProvider; }
}
public string WarningString { get; set; } = SR.GetString(SR.Warning, CultureInfo.CurrentUICulture);
public string ErrorString { get; set; } = SR.GetString(SR.Error, CultureInfo.CurrentUICulture);
/// <summary>
/// When the build is not a "design time" (background or secondary) build this is True
/// </summary>
/// <remarks>
/// The only known way to detect an interactive build is to check this.outputWindowPane for null.
/// </remarks>
protected bool InteractiveBuild
{
get { return this.outputWindowPane != null; }
}
/// <summary>
/// Set to null to avoid writing to the output window
/// </summary>
internal IVsOutputWindowPane OutputWindowPane
{
get { return this.outputWindowPane; }
set { this.outputWindowPane = value; }
}
#endregion
#region ctors
/// <summary>
/// Constructor. Inititialize member data.
/// </summary>
public IDEBuildLogger(IVsOutputWindowPane output, TaskProvider taskProvider, IVsHierarchy hierarchy)
{
Utilities.ArgumentNotNull("taskProvider", taskProvider);
Utilities.ArgumentNotNull("hierarchy", hierarchy);
Trace.WriteLineIf(Thread.CurrentThread.GetApartmentState() != ApartmentState.STA, "WARNING: IDEBuildLogger constructor running on the wrong thread.");
IOleServiceProvider site;
Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(hierarchy.GetSite(out site));
this.taskProvider = taskProvider;
this.outputWindowPane = output;
this.hierarchy = hierarchy;
this.serviceProvider = new ServiceProvider(site);
}
#endregion
#region IDisposable
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
var sp = this.serviceProvider as ServiceProvider;
this.serviceProvider = null;
if (sp != null)
{
sp.Dispose();
}
}
}
#endregion
#region overridden methods
/// <summary>
/// Overridden from the Logger class.
/// </summary>
public override void Initialize(IEventSource eventSource)
{
Utilities.ArgumentNotNull("eventSource", eventSource);
this.taskQueue = new ConcurrentQueue<Func<ErrorTask>>();
this.outputQueue = new ConcurrentQueue<OutputQueueEntry>();
eventSource.BuildStarted += new BuildStartedEventHandler(BuildStartedHandler);
eventSource.BuildFinished += new BuildFinishedEventHandler(BuildFinishedHandler);
eventSource.ProjectStarted += new ProjectStartedEventHandler(ProjectStartedHandler);
eventSource.ProjectFinished += new ProjectFinishedEventHandler(ProjectFinishedHandler);
eventSource.TargetStarted += new TargetStartedEventHandler(TargetStartedHandler);
eventSource.TargetFinished += new TargetFinishedEventHandler(TargetFinishedHandler);
eventSource.TaskStarted += new TaskStartedEventHandler(TaskStartedHandler);
eventSource.TaskFinished += new TaskFinishedEventHandler(TaskFinishedHandler);
eventSource.CustomEventRaised += new CustomBuildEventHandler(CustomHandler);
eventSource.ErrorRaised += new BuildErrorEventHandler(ErrorRaisedHandler);
eventSource.WarningRaised += new BuildWarningEventHandler(WarningHandler);
eventSource.MessageRaised += new BuildMessageEventHandler(MessageHandler);
}
#endregion
#region event delegates
/// <summary>
/// This is the delegate for BuildStartedHandler events.
/// </summary>
protected virtual void BuildStartedHandler(object sender, BuildStartedEventArgs buildEvent)
{
// NOTE: This may run on a background thread!
ClearCachedVerbosity();
ClearQueuedOutput();
ClearQueuedTasks();
QueueOutputEvent(MessageImportance.Low, buildEvent);
}
/// <summary>
/// This is the delegate for BuildFinishedHandler events.
/// </summary>
/// <param name="sender"></param>
/// <param name="buildEvent"></param>
protected virtual void BuildFinishedHandler(object sender, BuildFinishedEventArgs buildEvent)
{
// NOTE: This may run on a background thread!
MessageImportance importance = buildEvent.Succeeded ? MessageImportance.Low : MessageImportance.High;
QueueOutputText(importance, Environment.NewLine);
QueueOutputEvent(importance, buildEvent);
// flush output and error queues
ReportQueuedOutput();
ReportQueuedTasks();
}
/// <summary>
/// This is the delegate for ProjectStartedHandler events.
/// </summary>
protected virtual void ProjectStartedHandler(object sender, ProjectStartedEventArgs buildEvent)
{
// NOTE: This may run on a background thread!
QueueOutputEvent(MessageImportance.Low, buildEvent);
}
/// <summary>
/// This is the delegate for ProjectFinishedHandler events.
/// </summary>
protected virtual void ProjectFinishedHandler(object sender, ProjectFinishedEventArgs buildEvent)
{
// NOTE: This may run on a background thread!
QueueOutputEvent(buildEvent.Succeeded ? MessageImportance.Low : MessageImportance.High, buildEvent);
}
/// <summary>
/// This is the delegate for TargetStartedHandler events.
/// </summary>
protected virtual void TargetStartedHandler(object sender, TargetStartedEventArgs buildEvent)
{
// NOTE: This may run on a background thread!
QueueOutputEvent(MessageImportance.Low, buildEvent);
IndentOutput();
}
/// <summary>
/// This is the delegate for TargetFinishedHandler events.
/// </summary>
protected virtual void TargetFinishedHandler(object sender, TargetFinishedEventArgs buildEvent)
{
// NOTE: This may run on a background thread!
UnindentOutput();
QueueOutputEvent(MessageImportance.Low, buildEvent);
}
/// <summary>
/// This is the delegate for TaskStartedHandler events.
/// </summary>
protected virtual void TaskStartedHandler(object sender, TaskStartedEventArgs buildEvent)
{
// NOTE: This may run on a background thread!
QueueOutputEvent(MessageImportance.Low, buildEvent);
IndentOutput();
}
/// <summary>
/// This is the delegate for TaskFinishedHandler events.
/// </summary>
protected virtual void TaskFinishedHandler(object sender, TaskFinishedEventArgs buildEvent)
{
// NOTE: This may run on a background thread!
UnindentOutput();
QueueOutputEvent(MessageImportance.Low, buildEvent);
}
/// <summary>
/// This is the delegate for CustomHandler events.
/// </summary>
/// <param name="sender"></param>
/// <param name="buildEvent"></param>
protected virtual void CustomHandler(object sender, CustomBuildEventArgs buildEvent)
{
// NOTE: This may run on a background thread!
QueueOutputEvent(MessageImportance.High, buildEvent);
}
/// <summary>
/// This is the delegate for error events.
/// </summary>
protected virtual void ErrorRaisedHandler(object sender, BuildErrorEventArgs errorEvent)
{
// NOTE: This may run on a background thread!
QueueOutputText(GetFormattedErrorMessage(errorEvent.File, errorEvent.LineNumber, errorEvent.ColumnNumber, false, errorEvent.Code, errorEvent.Message));
QueueTaskEvent(errorEvent);
}
/// <summary>
/// This is the delegate for warning events.
/// </summary>
protected virtual void WarningHandler(object sender, BuildWarningEventArgs warningEvent)
{
// NOTE: This may run on a background thread!
QueueOutputText(MessageImportance.High, GetFormattedErrorMessage(warningEvent.File, warningEvent.LineNumber, warningEvent.ColumnNumber, true, warningEvent.Code, warningEvent.Message));
QueueTaskEvent(warningEvent);
}
/// <summary>
/// This is the delegate for Message event types
/// </summary>
protected virtual void MessageHandler(object sender, BuildMessageEventArgs messageEvent)
{
// NOTE: This may run on a background thread!
// Special-case this event type. It's reported by tasks derived from ToolTask, and prints out the command line used
// to invoke the tool. It has high priority for some unclear reason, but we really don't want to be showing it for
// verbosity below normal (https://nodejstools.codeplex.com/workitem/693). The check here is taken directly from the
// standard MSBuild console logger, which does the same thing.
if (messageEvent is TaskCommandLineEventArgs && !IsVerbosityAtLeast(LoggerVerbosity.Normal))
{
return;
}
QueueOutputEvent(messageEvent.Importance, messageEvent);
}
#endregion
#region output queue
protected void QueueOutputEvent(MessageImportance importance, BuildEventArgs buildEvent)
{
// NOTE: This may run on a background thread!
if (LogAtImportance(importance) && !string.IsNullOrEmpty(buildEvent.Message))
{
StringBuilder message = new StringBuilder(this.currentIndent + buildEvent.Message.Length);
if (this.currentIndent > 0)
{
message.Append('\t', this.currentIndent);
}
message.AppendLine(buildEvent.Message);
QueueOutputText(message.ToString());
}
}
protected void QueueOutputText(MessageImportance importance, string text)
{
// NOTE: This may run on a background thread!
if (LogAtImportance(importance))
{
QueueOutputText(text);
}
}
protected void QueueOutputText(string text)
{
// NOTE: This may run on a background thread!
if (this.OutputWindowPane != null)
{
// Enqueue the output text
lock (outputQueue)
{
this.outputQueue.Enqueue(new OutputQueueEntry(text, OutputWindowPane));
}
// We want to interactively report the output. But we dont want to dispatch
// more than one at a time, otherwise we might overflow the main thread's
// message queue. So, we only report the output if the queue was empty.
if (this.outputQueue.Count == 1)
{
ReportQueuedOutput();
}
}
}
private void IndentOutput()
{
// NOTE: This may run on a background thread!
this.currentIndent++;
}
private void UnindentOutput()
{
// NOTE: This may run on a background thread!
this.currentIndent--;
}
private void ReportQueuedOutput()
{
// NOTE: This may run on a background thread!
// We need to output this on the main thread. We must use BeginInvoke because the main thread may not be pumping events yet.
FlushBuildOutput();
}
internal void FlushBuildOutput()
{
OutputQueueEntry output;
lock (outputQueue)
{
if (!outputQueue.IsEmpty)
{
while (this.outputQueue.TryDequeue(out output))
{
#if DEV17
ErrorHandler.ThrowOnFailure(output.Pane.OutputStringThreadSafe(output.Message));
#else
ErrorHandler.ThrowOnFailure(output.Pane.OutputString(output.Message));
#endif
}
}
}
}
private void ClearQueuedOutput()
{
// NOTE: This may run on a background thread!
this.outputQueue = new ConcurrentQueue<OutputQueueEntry>();
}
#endregion output queue
#region task queue
class NavigableErrorTask : ErrorTask
{
private readonly IServiceProvider _serviceProvider;
public NavigableErrorTask(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
protected override void OnNavigate(EventArgs e)
{
ThreadHelper.ThrowIfNotOnUIThread();
VsUtilities.NavigateTo(
_serviceProvider,
Document,
Guid.Empty,
Line,
Column - 1
);
base.OnNavigate(e);
}
}
protected virtual void QueueTaskEvent(BuildEventArgs errorEvent)
{
this.taskQueue.Enqueue(() =>
{
var task = new NavigableErrorTask(serviceProvider);
if (errorEvent is BuildErrorEventArgs)
{
BuildErrorEventArgs errorArgs = (BuildErrorEventArgs)errorEvent;
task.Document = errorArgs.File;
task.ErrorCategory = TaskErrorCategory.Error;
task.Line = errorArgs.LineNumber - 1; // The task list does +1 before showing this number.
task.Column = errorArgs.ColumnNumber;
task.Priority = TaskPriority.High;
}
else if (errorEvent is BuildWarningEventArgs)
{
BuildWarningEventArgs warningArgs = (BuildWarningEventArgs)errorEvent;
task.Document = warningArgs.File;
task.ErrorCategory = TaskErrorCategory.Warning;
task.Line = warningArgs.LineNumber - 1; // The task list does +1 before showing this number.
task.Column = warningArgs.ColumnNumber;
task.Priority = TaskPriority.Normal;
}
task.Text = errorEvent.Message;
task.Category = TaskCategory.BuildCompile;
task.HierarchyItem = hierarchy;
return task;
});
// NOTE: Unlike output we don't want to interactively report the tasks. So we never queue
// call ReportQueuedTasks here. We do this when the build finishes.
}
private void ReportQueuedTasks()
{
// NOTE: This may run on a background thread!
// We need to output this on the main thread. We must use BeginInvoke because the main thread may not be pumping events yet.
this.taskProvider.SuspendRefresh();
try
{
Func<ErrorTask> taskFunc;
while (this.taskQueue.TryDequeue(out taskFunc))
{
// Create the error task
ErrorTask task = taskFunc();
// Log the task
this.taskProvider.Tasks.Add(task);
}
}
finally
{
this.taskProvider.ResumeRefresh();
}
}
private void ClearQueuedTasks()
{
// NOTE: This may run on a background thread!
this.taskQueue = new ConcurrentQueue<Func<ErrorTask>>();
if (this.InteractiveBuild)
{
// We need to clear this on the main thread. We must use BeginInvoke because the main thread may not be pumping events yet.
this.taskProvider.Tasks.Clear();
}
}
#endregion task queue
#region helpers
/// <summary>
/// This method takes a MessageImportance and returns true if messages
/// at importance i should be logged. Otherwise return false.
/// </summary>
private bool LogAtImportance(MessageImportance importance)
{
// If importance is too low for current settings, ignore the event
bool logIt = false;
this.SetVerbosity();
switch (this.Verbosity)
{
case LoggerVerbosity.Quiet:
logIt = false;
break;
case LoggerVerbosity.Minimal:
logIt = (importance == MessageImportance.High);
break;
case LoggerVerbosity.Normal:
// Falling through...
case LoggerVerbosity.Detailed:
logIt = (importance != MessageImportance.Low);
break;
case LoggerVerbosity.Diagnostic:
logIt = true;
break;
default:
Debug.Fail("Unknown Verbosity level. Ignoring will cause nothing to be logged");
break;
}
return logIt;
}
/// <summary>
/// Format error messages for the task list
/// </summary>
private string GetFormattedErrorMessage(
string fileName,
int line,
int column,
bool isWarning,
string errorNumber,
string errorText)
{
string errorCode = isWarning ? this.WarningString : this.ErrorString;
StringBuilder message = new StringBuilder();
if (!string.IsNullOrEmpty(fileName))
{
message.AppendFormat(CultureInfo.CurrentCulture, "{0}({1},{2}):", fileName, line, column);
}
message.AppendFormat(CultureInfo.CurrentCulture, " {0} {1}: {2}", errorCode, errorNumber, errorText);
message.AppendLine();
return message.ToString();
}
/// <summary>
/// Sets the verbosity level.
/// </summary>
private void SetVerbosity()
{
if (!this.haveCachedVerbosity)
{
this.Verbosity = LoggerVerbosity.Normal;
try
{
var settings = new ShellSettingsManager(serviceProvider);
var store = settings.GetReadOnlySettingsStore(SettingsScope.UserSettings);
if (store.CollectionExists(GeneralCollection) && store.PropertyExists(GeneralCollection, BuildVerbosityProperty))
{
this.Verbosity = (LoggerVerbosity)store.GetInt32(GeneralCollection, BuildVerbosityProperty, (int)LoggerVerbosity.Normal);
}
}
catch (Exception ex)
{
var message = string.Format(
"Unable to read verbosity option from the registry.{0}{1}",
Environment.NewLine,
ex.ToString()
);
this.QueueOutputText(MessageImportance.High, message);
}
this.haveCachedVerbosity = true;
}
}
/// <summary>
/// Clear the cached verbosity, so that it will be re-evaluated from the build verbosity registry key.
/// </summary>
private void ClearCachedVerbosity()
{
this.haveCachedVerbosity = false;
}
#endregion helpers
#region exception handling helpers
/// <summary>
/// Call Dispatcher.BeginInvoke, showing an error message if there was a non-critical exception.
/// </summary>
/// <param name="serviceProvider">service provider</param>
/// <param name="dispatcher">dispatcher</param>
/// <param name="action">action to invoke</param>
/// <summary>
/// Show error message if exception is caught when invoking a method
/// </summary>
/// <param name="serviceProvider">service provider</param>
/// <param name="action">action to invoke</param>
private static void CallWithErrorMessage(IServiceProvider serviceProvider, Action action)
{
try
{
action();
}
catch (Exception ex)
{
if (Microsoft.VisualStudio.ErrorHandler.IsCriticalException(ex))
{
throw;
}
ShowErrorMessage(serviceProvider, ex);
}
}
/// <summary>
/// Show error window about the exception
/// </summary>
/// <param name="serviceProvider">service provider</param>
/// <param name="exception">exception</param>
private static void ShowErrorMessage(IServiceProvider serviceProvider, Exception exception)
{
IUIService UIservice = (IUIService)serviceProvider.GetService(typeof(IUIService));
if (UIservice != null && exception != null)
{
UIservice.ShowError(exception);
}
}
#endregion exception handling helpers
class OutputQueueEntry
{
public readonly string Message;
public readonly IVsOutputWindowPane Pane;
public OutputQueueEntry(string message, IVsOutputWindowPane pane)
{
Message = message;
Pane = pane;
}
}
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using osu.Game.Audio;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Edit.Checks;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Tests.Editing.Checks
{
[TestFixture]
public class CheckFewHitsoundsTest
{
private CheckFewHitsounds check;
private List<HitSampleInfo> notHitsounded;
private List<HitSampleInfo> hitsounded;
[SetUp]
public void Setup()
{
check = new CheckFewHitsounds();
notHitsounded = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL) };
hitsounded = new List<HitSampleInfo>
{
new HitSampleInfo(HitSampleInfo.HIT_NORMAL),
new HitSampleInfo(HitSampleInfo.HIT_FINISH)
};
}
[Test]
public void TestHitsounded()
{
var hitObjects = new List<HitObject>();
for (int i = 0; i < 16; ++i)
{
var samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL) };
if ((i + 1) % 2 == 0)
samples.Add(new HitSampleInfo(HitSampleInfo.HIT_CLAP));
if ((i + 1) % 3 == 0)
samples.Add(new HitSampleInfo(HitSampleInfo.HIT_WHISTLE));
if ((i + 1) % 4 == 0)
samples.Add(new HitSampleInfo(HitSampleInfo.HIT_FINISH));
hitObjects.Add(new HitCircle { StartTime = 1000 * i, Samples = samples });
}
assertOk(hitObjects);
}
[Test]
public void TestHitsoundedWithBreak()
{
var hitObjects = new List<HitObject>();
for (int i = 0; i < 32; ++i)
{
var samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL) };
if ((i + 1) % 2 == 0)
samples.Add(new HitSampleInfo(HitSampleInfo.HIT_CLAP));
if ((i + 1) % 3 == 0)
samples.Add(new HitSampleInfo(HitSampleInfo.HIT_WHISTLE));
if ((i + 1) % 4 == 0)
samples.Add(new HitSampleInfo(HitSampleInfo.HIT_FINISH));
// Leaves a gap in which no hitsounds exist or can be added, and so shouldn't be an issue.
if (i > 8 && i < 24)
continue;
hitObjects.Add(new HitCircle { StartTime = 1000 * i, Samples = samples });
}
assertOk(hitObjects);
}
[Test]
public void TestLightlyHitsounded()
{
var hitObjects = new List<HitObject>();
for (int i = 0; i < 30; ++i)
{
var samples = i % 8 == 0 ? hitsounded : notHitsounded;
hitObjects.Add(new HitCircle { StartTime = 1000 * i, Samples = samples });
}
assertLongPeriodNegligible(hitObjects, count: 3);
}
[Test]
public void TestRarelyHitsounded()
{
var hitObjects = new List<HitObject>();
for (int i = 0; i < 30; ++i)
{
var samples = (i == 0 || i == 15) ? hitsounded : notHitsounded;
hitObjects.Add(new HitCircle { StartTime = 1000 * i, Samples = samples });
}
// Should prompt one warning between 1st and 16th, and another between 16th and 31st.
assertLongPeriodWarning(hitObjects, count: 2);
}
[Test]
public void TestExtremelyRarelyHitsounded()
{
var hitObjects = new List<HitObject>();
for (int i = 0; i < 80; ++i)
{
var samples = i == 40 ? hitsounded : notHitsounded;
hitObjects.Add(new HitCircle { StartTime = 1000 * i, Samples = samples });
}
// Should prompt one problem between 1st and 41st, and another between 41st and 81st.
assertLongPeriodProblem(hitObjects, count: 2);
}
[Test]
public void TestNotHitsounded()
{
var hitObjects = new List<HitObject>();
for (int i = 0; i < 20; ++i)
hitObjects.Add(new HitCircle { StartTime = 1000 * i, Samples = notHitsounded });
assertNoHitsounds(hitObjects);
}
[Test]
public void TestNestedObjectsHitsounded()
{
var ticks = new List<HitObject>();
for (int i = 1; i < 16; ++i)
ticks.Add(new SliderTick { StartTime = 1000 * i, Samples = hitsounded });
var nested = new MockNestableHitObject(ticks.ToList(), 0, 16000)
{
Samples = hitsounded
};
nested.ApplyDefaults(new ControlPointInfo(), new BeatmapDifficulty());
assertOk(new List<HitObject> { nested });
}
[Test]
public void TestNestedObjectsRarelyHitsounded()
{
var ticks = new List<HitObject>();
for (int i = 1; i < 16; ++i)
ticks.Add(new SliderTick { StartTime = 1000 * i, Samples = i == 0 ? hitsounded : notHitsounded });
var nested = new MockNestableHitObject(ticks.ToList(), 0, 16000)
{
Samples = hitsounded
};
nested.ApplyDefaults(new ControlPointInfo(), new BeatmapDifficulty());
assertLongPeriodWarning(new List<HitObject> { nested });
}
[Test]
public void TestConcurrentObjects()
{
var hitObjects = new List<HitObject>();
var ticks = new List<HitObject>();
for (int i = 1; i < 10; ++i)
ticks.Add(new SliderTick { StartTime = 5000 * i, Samples = hitsounded });
var nested = new MockNestableHitObject(ticks.ToList(), 0, 50000)
{
Samples = notHitsounded
};
nested.ApplyDefaults(new ControlPointInfo(), new BeatmapDifficulty());
hitObjects.Add(nested);
for (int i = 1; i <= 6; ++i)
hitObjects.Add(new HitCircle { StartTime = 10000 * i, Samples = notHitsounded });
assertOk(hitObjects);
}
private void assertOk(List<HitObject> hitObjects)
{
Assert.That(check.Run(getContext(hitObjects)), Is.Empty);
}
private void assertLongPeriodProblem(List<HitObject> hitObjects, int count = 1)
{
var issues = check.Run(getContext(hitObjects)).ToList();
Assert.That(issues, Has.Count.EqualTo(count));
Assert.That(issues.All(issue => issue.Template is CheckFewHitsounds.IssueTemplateLongPeriodProblem));
}
private void assertLongPeriodWarning(List<HitObject> hitObjects, int count = 1)
{
var issues = check.Run(getContext(hitObjects)).ToList();
Assert.That(issues, Has.Count.EqualTo(count));
Assert.That(issues.All(issue => issue.Template is CheckFewHitsounds.IssueTemplateLongPeriodWarning));
}
private void assertLongPeriodNegligible(List<HitObject> hitObjects, int count = 1)
{
var issues = check.Run(getContext(hitObjects)).ToList();
Assert.That(issues, Has.Count.EqualTo(count));
Assert.That(issues.All(issue => issue.Template is CheckFewHitsounds.IssueTemplateLongPeriodNegligible));
}
private void assertNoHitsounds(List<HitObject> hitObjects)
{
var issues = check.Run(getContext(hitObjects)).ToList();
Assert.That(issues, Has.Count.EqualTo(1));
Assert.That(issues.Any(issue => issue.Template is CheckFewHitsounds.IssueTemplateNoHitsounds));
}
private BeatmapVerifierContext getContext(List<HitObject> hitObjects)
{
var beatmap = new Beatmap<HitObject> { HitObjects = hitObjects };
return new BeatmapVerifierContext(beatmap, new TestWorkingBeatmap(beatmap));
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
/*
================================================================================
The DOFPostEffect API
================================================================================
DOFPostEffect::setFocalDist( %dist )
@summary
This method is for manually controlling the focus distance. It will have no
effect if auto focus is currently enabled. Makes use of the parameters set by
setFocusParams.
@param dist
float distance in meters
--------------------------------------------------------------------------------
DOFPostEffect::setAutoFocus( %enabled )
@summary
This method sets auto focus enabled or disabled. Makes use of the parameters set
by setFocusParams. When auto focus is enabled it determines the focal depth
by performing a raycast at the screen-center.
@param enabled
bool
--------------------------------------------------------------------------------
DOFPostEffect::setFocusParams( %nearBlurMax, %farBlurMax, %minRange, %maxRange, %nearSlope, %farSlope )
Set the parameters that control how the near and far equations are calculated
from the focal distance. If you are not using auto focus you will need to call
setFocusParams PRIOR to calling setFocalDist.
@param nearBlurMax
float between 0.0 and 1.0
The max allowed value of near blur.
@param farBlurMax
float between 0.0 and 1.0
The max allowed value of far blur.
@param minRange/maxRange
float in meters
The distance range around the focal distance that remains in focus is a lerp
between the min/maxRange using the normalized focal distance as the parameter.
The point is to allow the focal range to expand as you focus farther away since this is
visually appealing.
Note: since min/maxRange are lerped by the "normalized" focal distance it is
dependant on the visible distance set in your level.
@param nearSlope
float less than zero
The slope of the near equation. A small number causes bluriness to increase gradually
at distances closer than the focal distance. A large number causes bluriness to
increase quickly.
@param farSlope
float greater than zero
The slope of the far equation. A small number causes bluriness to increase gradually
at distances farther than the focal distance. A large number causes bluriness to
increase quickly.
Note: To rephrase, the min/maxRange parameters control how much area around the
focal distance is completely in focus where the near/farSlope parameters control
how quickly or slowly bluriness increases at distances outside of that range.
================================================================================
Examples
================================================================================
Example1: Turn on DOF while zoomed in with a weapon.
NOTE: These are not real callbacks! Hook these up to your code where appropriate!
function onSniperZoom()
{
// Parameterize how you want DOF to look.
DOFPostEffect.setFocusParams( 0.3, 0.3, 50, 500, -5, 5 );
// Turn on auto focus
DOFPostEffect.setAutoFocus( true );
// Turn on the PostEffect
DOFPostEffect.enable();
}
function onSniperUnzoom()
{
// Turn off the PostEffect
DOFPostEffect.disable();
}
Example2: Manually control DOF with the mouse wheel.
// Somewhere on startup...
// Parameterize how you want DOF to look.
DOFPostEffect.setFocusParams( 0.3, 0.3, 50, 500, -5, 5 );
// Turn off auto focus
DOFPostEffect.setAutoFocus( false );
// Turn on the PostEffect
DOFPostEffect.enable();
NOTE: These are not real callbacks! Hook these up to your code where appropriate!
function onMouseWheelUp()
{
// Since setFocalDist is really just a wrapper to assign to the focalDist
// dynamic field we can shortcut and increment it directly.
DOFPostEffect.focalDist += 8;
}
function onMouseWheelDown()
{
DOFPostEffect.focalDist -= 8;
}
*/
/// This method is for manually controlling the focal distance. It will have no
/// effect if auto focus is currently enabled. Makes use of the parameters set by
/// setFocusParams.
function DOFPostEffect::setFocalDist( %this, %dist )
{
%this.focalDist = %dist;
}
/// This method sets auto focus enabled or disabled. Makes use of the parameters set
/// by setFocusParams. When auto focus is enabled it determine the focal depth
/// by performing a raycast at the screen-center.
function DOFPostEffect::setAutoFocus( %this, %enabled )
{
%this.autoFocusEnabled = %enabled;
}
/// Set the parameters that control how the near and far equations are calculated
/// from the focal distance. If you are not using auto focus you will need to call
/// setFocusParams PRIOR to calling setFocalDist.
function DOFPostEffect::setFocusParams( %this, %nearBlurMax, %farBlurMax, %minRange, %maxRange, %nearSlope, %farSlope )
{
%this.nearBlurMax = %nearBlurMax;
%this.farBlurMax = %farBlurMax;
%this.minRange = %minRange;
%this.maxRange = %maxRange;
%this.nearSlope = %nearSlope;
%this.farSlope = %farSlope;
}
/*
More information...
This DOF technique is based on this paper:
http://http.developer.nvidia.com/GPUGems3/gpugems3_ch28.html
================================================================================
1. Overview of how we represent "Depth of Field"
================================================================================
DOF is expressed as an amount of bluriness per pixel according to its depth.
We represented this by a piecewise linear curve depicted below.
Note: we also refer to "bluriness" as CoC ( circle of confusion ) which is the term
used in the basis paper and in photography.
X-axis (depth)
x = 0.0----------------------------------------------x = 1.0
Y-axis (bluriness)
y = 1.0
|
| ____(x1,y1) (x4,y4)____
| (ns,nb)\ <--Line1 line2---> /(fe,fb)
| \ /
| \(x2,y2) (x3,y3)/
| (ne,0)------(fs,0)
y = 0.0
I have labeled the "corners" of this graph with (Xn,Yn) to illustrate that
this is in fact a collection of line segments where the x/y of each point
corresponds to the key below.
key:
ns - (n)ear blur (s)tart distance
nb - (n)ear (b)lur amount (max value)
ne - (n)ear blur (e)nd distance
fs - (f)ar blur (s)tart distance
fe - (f)ar blur (e)nd distance
fb - (f)ar (b)lur amount (max value)
Of greatest importance in this graph is Line1 and Line2. Where...
L1 { (x1,y1), (x2,y2) }
L2 { (x3,y3), (x4,y4) }
Line one represents the amount of "near" blur given a pixels depth and line two
represents the amount of "far" blur at that depth.
Both these equations are evaluated for each pixel and then the larger of the two
is kept. Also the output blur (for each equation) is clamped between 0 and its
maximum allowable value.
Therefore, to specify a DOF "qualify" you need to specify the near-blur-line,
far-blur-line, and maximum near and far blur value.
================================================================================
2. Abstracting a "focal depth"
================================================================================
Although the shader(s) work in terms of a near and far equation it is more
useful to express DOF as an adjustable focal depth and derive the other parameters
"under the hood".
Given a maximum near/far blur amount and a near/far slope we can calculate the
near/far equations for any focal depth. We extend this to also support a range
of depth around the focal depth that is also in focus and for that range to
shrink or grow as the focal depth moves closer or farther.
Keep in mind this is only one implementation and depending on the effect you
desire you may which to express the relationship between focal depth and
the shader paramaters different.
*/
//-----------------------------------------------------------------------------
// GFXStateBlockData / ShaderData
//-----------------------------------------------------------------------------
singleton GFXStateBlockData( PFX_DefaultDOFStateBlock )
{
zDefined = true;
zEnable = false;
zWriteEnable = false;
samplersDefined = true;
samplerStates[0] = SamplerClampPoint;
samplerStates[1] = SamplerClampPoint;
};
singleton GFXStateBlockData( PFX_DOFCalcCoCStateBlock )
{
zDefined = true;
zEnable = false;
zWriteEnable = false;
samplersDefined = true;
samplerStates[0] = SamplerClampLinear;
samplerStates[1] = SamplerClampLinear;
};
singleton GFXStateBlockData( PFX_DOFDownSampleStateBlock )
{
zDefined = true;
zEnable = false;
zWriteEnable = false;
samplersDefined = true;
samplerStates[0] = SamplerClampLinear;
samplerStates[1] = SamplerClampPoint;
};
singleton GFXStateBlockData( PFX_DOFBlurStateBlock )
{
zDefined = true;
zEnable = false;
zWriteEnable = false;
samplersDefined = true;
samplerStates[0] = SamplerClampLinear;
};
singleton GFXStateBlockData( PFX_DOFFinalStateBlock )
{
zDefined = true;
zEnable = false;
zWriteEnable = false;
samplersDefined = true;
samplerStates[0] = SamplerClampLinear;
samplerStates[1] = SamplerClampLinear;
samplerStates[2] = SamplerClampLinear;
samplerStates[3] = SamplerClampPoint;
blendDefined = true;
blendEnable = true;
blendDest = GFXBlendInvSrcAlpha;
blendSrc = GFXBlendOne;
};
singleton ShaderData( PFX_DOFDownSampleShader )
{
DXVertexShaderFile = $Core::CommonShaderPath @ "/postFX/dof/DOF_DownSample_V.hlsl";
DXPixelShaderFile = $Core::CommonShaderPath @ "/postFX/dof/DOF_DownSample_P.hlsl";
OGLVertexShaderFile = $Core::CommonShaderPath @ "/postFX/dof/gl/DOF_DownSample_V.glsl";
OGLPixelShaderFile = $Core::CommonShaderPath @ "/postFX/dof/gl/DOF_DownSample_P.glsl";
samplerNames[0] = "$colorSampler";
samplerNames[1] = "$depthSampler";
pixVersion = 3.0;
};
singleton ShaderData( PFX_DOFBlurYShader )
{
DXVertexShaderFile = $Core::CommonShaderPath @ "/postFX/dof/DOF_Gausian_V.hlsl";
DXPixelShaderFile = $Core::CommonShaderPath @ "/postFX/dof/DOF_Gausian_P.hlsl";
OGLVertexShaderFile = $Core::CommonShaderPath @ "/postFX/dof/gl/DOF_Gausian_V.glsl";
OGLPixelShaderFile = $Core::CommonShaderPath @ "/postFX/dof/gl/DOF_Gausian_P.glsl";
samplerNames[0] = "$diffuseMap";
pixVersion = 2.0;
defines = "BLUR_DIR=float2(0.0,1.0)";
};
singleton ShaderData( PFX_DOFBlurXShader : PFX_DOFBlurYShader )
{
defines = "BLUR_DIR=float2(1.0,0.0)";
};
singleton ShaderData( PFX_DOFCalcCoCShader )
{
DXVertexShaderFile = $Core::CommonShaderPath @ "/postFX/dof/DOF_CalcCoC_V.hlsl";
DXPixelShaderFile = $Core::CommonShaderPath @ "/postFX/dof/DOF_CalcCoC_P.hlsl";
OGLVertexShaderFile = $Core::CommonShaderPath @ "/postFX/dof/gl/DOF_CalcCoC_V.glsl";
OGLPixelShaderFile = $Core::CommonShaderPath @ "/postFX/dof/gl/DOF_CalcCoC_P.glsl";
samplerNames[0] = "$shrunkSampler";
samplerNames[1] = "$blurredSampler";
pixVersion = 3.0;
};
singleton ShaderData( PFX_DOFSmallBlurShader )
{
DXVertexShaderFile = $Core::CommonShaderPath @ "/postFX/dof/DOF_SmallBlur_V.hlsl";
DXPixelShaderFile = $Core::CommonShaderPath @ "/postFX/dof/DOF_SmallBlur_P.hlsl";
OGLVertexShaderFile = $Core::CommonShaderPath @ "/postFX/dof/gl/DOF_SmallBlur_V.glsl";
OGLPixelShaderFile = $Core::CommonShaderPath @ "/postFX/dof/gl/DOF_SmallBlur_P.glsl";
samplerNames[0] = "$colorSampler";
pixVersion = 3.0;
};
singleton ShaderData( PFX_DOFFinalShader )
{
DXVertexShaderFile = $Core::CommonShaderPath @ "/postFX/dof/DOF_Final_V.hlsl";
DXPixelShaderFile = $Core::CommonShaderPath @ "/postFX/dof/DOF_Final_P.hlsl";
OGLVertexShaderFile = $Core::CommonShaderPath @ "/postFX/dof/gl/DOF_Final_V.glsl";
OGLPixelShaderFile = $Core::CommonShaderPath @ "/postFX/dof/gl/DOF_Final_P.glsl";
samplerNames[0] = "$colorSampler";
samplerNames[1] = "$smallBlurSampler";
samplerNames[2] = "$largeBlurSampler";
samplerNames[3] = "$depthSampler";
pixVersion = 3.0;
};
//-----------------------------------------------------------------------------
// PostEffects
//-----------------------------------------------------------------------------
function DOFPostEffect::onAdd( %this )
{
// The weighted distribution of CoC value to the three blur textures
// in the order small, medium, large. Most likely you will not need to
// change this value.
%this.setLerpDist( 0.2, 0.3, 0.5 );
// Fill out some default values but DOF really should not be turned on
// without actually specifying your own parameters!
%this.autoFocusEnabled = false;
%this.focalDist = 0.0;
%this.nearBlurMax = 0.5;
%this.farBlurMax = 0.5;
%this.minRange = 50;
%this.maxRange = 500;
%this.nearSlope = -5.0;
%this.farSlope = 5.0;
}
function DOFPostEffect::setLerpDist( %this, %d0, %d1, %d2 )
{
%this.lerpScale = -1.0 / %d0 SPC -1.0 / %d1 SPC -1.0 / %d2 SPC 1.0 / %d2;
%this.lerpBias = 1.0 SPC ( 1.0 - %d2 ) / %d1 SPC 1.0 / %d2 SPC ( %d2 - 1.0 ) / %d2;
}
singleton PostEffect( DOFPostEffect )
{
renderTime = "PFXAfterBin";
renderBin = "GlowBin";
renderPriority = 0.1;
shader = PFX_DOFDownSampleShader;
stateBlock = PFX_DOFDownSampleStateBlock;
texture[0] = "$backBuffer";
texture[1] = "#deferred";
target = "#shrunk";
targetScale = "0.25 0.25";
isEnabled = false;
};
singleton PostEffect( DOFBlurY )
{
shader = PFX_DOFBlurYShader;
stateBlock = PFX_DOFBlurStateBlock;
texture[0] = "#shrunk";
target = "$outTex";
};
DOFPostEffect.add( DOFBlurY );
singleton PostEffect( DOFBlurX )
{
shader = PFX_DOFBlurXShader;
stateBlock = PFX_DOFBlurStateBlock;
texture[0] = "$inTex";
target = "#largeBlur";
};
DOFPostEffect.add( DOFBlurX );
singleton PostEffect( DOFCalcCoC )
{
shader = PFX_DOFCalcCoCShader;
stateBlock = PFX_DOFCalcCoCStateBlock;
texture[0] = "#shrunk";
texture[1] = "#largeBlur";
target = "$outTex";
};
DOFPostEffect.add( DOFCalcCoc );
singleton PostEffect( DOFSmallBlur )
{
shader = PFX_DOFSmallBlurShader;
stateBlock = PFX_DefaultDOFStateBlock;
texture[0] = "$inTex";
target = "$outTex";
};
DOFPostEffect.add( DOFSmallBlur );
singleton PostEffect( DOFFinalPFX )
{
shader = PFX_DOFFinalShader;
stateBlock = PFX_DOFFinalStateBlock;
texture[0] = "$backBuffer";
texture[1] = "$inTex";
texture[2] = "#largeBlur";
texture[3] = "#deferred";
target = "$backBuffer";
};
DOFPostEffect.add( DOFFinalPFX );
//-----------------------------------------------------------------------------
// Scripts
//-----------------------------------------------------------------------------
function DOFPostEffect::setShaderConsts( %this )
{
if ( %this.autoFocusEnabled )
%this.autoFocus();
%fd = %this.focalDist / $Param::FarDist;
%range = mLerp( %this.minRange, %this.maxRange, %fd ) / $Param::FarDist * 0.5;
// We work in "depth" space rather than real-world units for the
// rest of this method...
// Given the focal distance and the range around it we want in focus
// we can determine the near-end-distance and far-start-distance
%ned = getMax( %fd - %range, 0.0 );
%fsd = getMin( %fd + %range, 1.0 );
// near slope
%nsl = %this.nearSlope;
// Given slope of near blur equation and the near end dist and amount (x2,y2)
// solve for the y-intercept
// y = mx + b
// so...
// y - mx = b
%b = 0.0 - %nsl * %ned;
%eqNear = %nsl SPC %b SPC 0.0;
// Do the same for the far blur equation...
%fsl = %this.farSlope;
%b = 0.0 - %fsl * %fsd;
%eqFar = %fsl SPC %b SPC 1.0;
%this.setShaderConst( "$dofEqWorld", %eqNear );
DOFFinalPFX.setShaderConst( "$dofEqFar", %eqFar );
%this.setShaderConst( "$maxWorldCoC", %this.nearBlurMax );
DOFFinalPFX.setShaderConst( "$maxFarCoC", %this.farBlurMax );
DOFFinalPFX.setShaderConst( "$dofLerpScale", %this.lerpScale );
DOFFinalPFX.setShaderConst( "$dofLerpBias", %this.lerpBias );
}
function DOFPostEffect::autoFocus( %this )
{
if ( !isObject( ServerConnection ) ||
!isObject( ServerConnection.getCameraObject() ) )
{
return;
}
%mask = $TypeMasks::StaticObjectType | $TypeMasks::TerrainObjectType;
%control = ServerConnection.getCameraObject();
%fvec = %control.getForwardVector();
%start = %control.getPosition();
%end = VectorAdd( %start, VectorScale( %fvec, $Param::FarDist ) );
// Use the client container for this ray cast.
%result = containerRayCast( %start, %end, %mask, %control, true );
%hitPos = getWords( %result, 1, 3 );
if ( %hitPos $= "" )
%focDist = $Param::FarDist;
else
%focDist = VectorDist( %hitPos, %start );
// For debuging
//$DOF::debug_dist = %focDist;
//$DOF::debug_depth = %focDist / $Param::FarDist;
//echo( "F: " @ %focDist SPC "D: " @ %delta );
%this.focalDist = %focDist;
}
// For debugging
/*
function reloadDOF()
{
exec( "./dof.cs" );
DOFPostEffect.reload();
DOFPostEffect.disable();
DOFPostEffect.enable();
}
function dofMetricsCallback()
{
return " | DOF |" @
" Dist: " @ $DOF::debug_dist @
" Depth: " @ $DOF::debug_depth;
}
*/
| |
// 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.ComponentModel;
using System.Diagnostics.Tracing;
using System.IdentityModel.Security;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Runtime.Diagnostics;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Federation.System.Runtime;
using System.ServiceModel.Security;
using System.ServiceModel.Security.Tokens;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.WsAddressing;
using Microsoft.IdentityModel.Protocols.WsPolicy;
using Microsoft.IdentityModel.Protocols.WsSecurity;
using Microsoft.IdentityModel.Protocols.WsTrust;
using SecurityToken = System.IdentityModel.Tokens.SecurityToken;
namespace System.ServiceModel.Federation
{
/// <summary>
/// <see cref="WSTrustChannelSecurityTokenProvider"/> has been designed to work with the <see cref="WSFederationHttpBinding"/> to send a WsTrust message to obtain a SecurityToken from an STS. The SecurityToken is
/// added as an IssuedToken on the outbound WCF message.
/// </summary>
public class WSTrustChannelSecurityTokenProvider : SecurityTokenProvider, ICommunicationObject, ISecurityCommunicationObject
{
private const int DefaultPublicKeySize = 1024;
private const string Namespace = "http://schemas.microsoft.com/ws/2006/05/servicemodel/securitytokenrequirement";
private const string IssuedSecurityTokenParametersProperty = Namespace + "/IssuedSecurityTokenParameters";
private const string SecurityAlgorithmSuiteProperty = Namespace + "/SecurityAlgorithmSuite";
private const string SecurityBindingElementProperty = Namespace + "/SecurityBindingElement";
private const string TargetAddressProperty = Namespace + "/TargetAddress";
private SecurityKeyEntropyMode _keyEntropyMode;
private readonly SecurityAlgorithmSuite _securityAlgorithmSuite;
private WsSerializationContext _requestSerializationContext;
private WrapperSecurityCommunicationObject _communicationObject;
private EventTraceActivity _eventTraceActivity;
/// <summary>
/// Instantiates a <see cref="WSTrustChannelSecurityTokenProvider"/> that describe the parameters for a WSTrust request.
/// </summary>
/// <param name="tokenRequirement">the <see cref="SecurityTokenRequirement"/> that must contain a <see cref="WSTrustTokenParameters"/> as the <see cref="IssuedSecurityTokenParameters"/> property.</param>
/// <exception cref="ArgumentNullException">thrown if <paramref name="tokenRequirement"/> is null.</exception>
/// <exception cref="ArgumentException">thrown if <see cref="SecurityTokenRequirement.GetProperty{TValue}(string)"/> (IssuedSecurityTokenParameters) is not a <see cref="WSTrustTokenParameters"/>.</exception>
public WSTrustChannelSecurityTokenProvider(SecurityTokenRequirement tokenRequirement)
{
SecurityTokenRequirement = tokenRequirement ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelper(new ArgumentNullException(nameof(tokenRequirement)), EventLevel.Error);
SecurityTokenRequirement.TryGetProperty(SecurityAlgorithmSuiteProperty, out _securityAlgorithmSuite);
IssuedSecurityTokenParameters issuedSecurityTokenParameters = SecurityTokenRequirement.GetProperty<IssuedSecurityTokenParameters>(IssuedSecurityTokenParametersProperty);
WSTrustTokenParameters = issuedSecurityTokenParameters as WSTrustTokenParameters;
if (WSTrustTokenParameters == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelper(new ArgumentException(LogHelper.FormatInvariant(SR.GetResourceString(SR.IssuedSecurityTokenParametersIncorrectType), issuedSecurityTokenParameters), nameof(tokenRequirement)), EventLevel.Error);
}
_communicationObject = new WrapperSecurityCommunicationObject(this);
}
private DateTime AddTicks(DateTime time, long ticks)
{
if (ticks > 0 && DateTime.MaxValue.Subtract(time).Ticks <= ticks)
return DateTime.MaxValue;
if (ticks < 0 && time.Subtract(DateTime.MinValue).Ticks <= -ticks)
return DateTime.MinValue;
return time.AddTicks(ticks);
}
/// <summary>
/// Gets or sets the cached security token response.
/// </summary>
private WsTrustResponse CachedResponse
{
// FUTURE : At some point, it may be valuable to replace this with a cache (Microsoft.Extensions.Caching.Distributed.IDistributedCache, perhaps)
// so that caches can be shared between token providers. For the time being, this is just an in-memory WsTrustResponse since a
// WSTrustChannelSecurityTokenProvider will only ever use a single WsTrustRequest. If caches can be shared, though, then this would
// be replaced with a more full-featured cache allowing multiple providers to cache tokens in a single cache object.
get;
set;
}
private void CacheSecurityTokenResponse(WsTrustRequest request, WsTrustResponse response)
{
if (WSTrustTokenParameters.CacheIssuedTokens)
{
// If cached responses are stored in a shared cache in the future, that cache should be written
// to here, possibly including serializing the WsTrustResponse if the cache stores byte[] (as
// IDistributedCache does).
CachedResponse = response;
}
}
/// <summary>
/// Returns a channel factory with the credentials that the user set the users credentials on.
/// </summary>
/// <returns></returns>
internal virtual ChannelFactory<IRequestChannel> ChannelFactory { get; set; }
internal ClientCredentials ClientCredentials { get; set; }
/// <summary>
/// Creates a <see cref="WsTrustRequest"/> from the <see cref="WSTrustTokenParameters"/>
/// </summary>
/// <returns></returns>
protected virtual WsTrustRequest CreateWsTrustRequest()
{
EndpointAddress target = SecurityTokenRequirement.GetProperty<EndpointAddress>(TargetAddressProperty);
int keySize;
string keyType;
switch (WSTrustTokenParameters.KeyType)
{
case SecurityKeyType.AsymmetricKey:
keySize = DefaultPublicKeySize;
keyType = _requestSerializationContext.TrustKeyTypes.PublicKey;
break;
case SecurityKeyType.SymmetricKey:
keySize = _securityAlgorithmSuite.DefaultSymmetricKeyLength;
keyType = _requestSerializationContext.TrustKeyTypes.Symmetric;
break;
case SecurityKeyType.BearerKey:
keySize = 0;
keyType = _requestSerializationContext.TrustKeyTypes.Bearer;
break;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelper(new NotSupportedException(LogHelper.FormatInvariant("KeyType is not supported: {0}", WSTrustTokenParameters.KeyType)), EventLevel.Error);
}
Entropy entropy = null;
if (WSTrustTokenParameters.KeyType != SecurityKeyType.BearerKey &&
(KeyEntropyMode == SecurityKeyEntropyMode.ClientEntropy || KeyEntropyMode == SecurityKeyEntropyMode.CombinedEntropy))
{
byte[] entropyBytes = new byte[keySize / 8];
Psha1KeyGenerator.FillRandomBytes(entropyBytes);
entropy = new Entropy(new BinarySecret(entropyBytes));
}
var trustRequest = new WsTrustRequest(_requestSerializationContext.TrustActions.Issue)
{
AppliesTo = new AppliesTo(new EndpointReference(target.Uri.OriginalString)),
Context = RequestContext,
KeySizeInBits = keySize,
KeyType = keyType,
WsTrustVersion = _requestSerializationContext.TrustVersion
};
if (SecurityTokenRequirement.TokenType != null)
{
trustRequest.TokenType = SecurityTokenRequirement.TokenType;
}
if (entropy != null)
{
trustRequest.Entropy = entropy;
trustRequest.ComputedKeyAlgorithm = _requestSerializationContext.TrustKeyTypes.PSHA1;
}
return trustRequest;
}
private EventTraceActivity EventTraceActivity
{
get
{
if (_eventTraceActivity == null)
{
_eventTraceActivity = EventTraceActivity.GetFromThreadOrCreate();
}
return _eventTraceActivity;
}
}
private WsTrustResponse GetCachedResponse(WsTrustRequest request)
{
if (WSTrustTokenParameters.CacheIssuedTokens && CachedResponse != null)
{
// If cached responses are read from shared caches in the future, then that cache should be read here
// and, if necessary, translated (perhaps via deserialization) into a WsTrustResponse.
if (!IsWsTrustResponseExpired(CachedResponse))
return CachedResponse;
}
return null;
}
/// <summary>
/// Begins a WSTrust call to the STS to obtain a <see cref="SecurityToken"/> first checking if the token is available in the cache.
/// </summary>
/// <returns>A <see cref="IAsyncResult"/>.</returns>
protected override IAsyncResult BeginGetTokenCore(TimeSpan timeout, AsyncCallback callback, object state)
{
return GetTokenAsyncCore(timeout).ToApm(callback, state);
}
/// <summary>
/// Completes a WSTrust call to the STS to obtain a <see cref="SecurityToken"/> first checking if the token is available in the cache.
/// </summary>
/// <returns>A <see cref="SecurityToken"/>.</returns>
protected override SecurityToken EndGetTokenCore(IAsyncResult result)
{
return result.ToApmEnd<SecurityToken>();
}
private async Task<SecurityToken> GetTokenAsyncCore(TimeSpan timeout)
{
_communicationObject.ThrowIfClosedOrNotOpen();
WsTrustRequest request = CreateWsTrustRequest();
WsTrustResponse trustResponse = GetCachedResponse(request);
if (trustResponse is null)
{
using (var memeoryStream = new MemoryStream())
{
var writer = XmlDictionaryWriter.CreateTextWriter(memeoryStream, Encoding.UTF8);
var serializer = new WsTrustSerializer();
serializer.WriteRequest(writer, _requestSerializationContext.TrustVersion, request);
writer.Flush();
var reader = XmlDictionaryReader.CreateTextReader(memeoryStream.ToArray(), XmlDictionaryReaderQuotas.Max);
IRequestChannel channel = ChannelFactory.CreateChannel();
await Task.Factory.FromAsync(channel.BeginOpen, channel.EndOpen, null, TaskCreationOptions.None);
try
{
Message requestMessage = Message.CreateMessage(MessageVersion.Soap12WSAddressing10, _requestSerializationContext.TrustActions.IssueRequest, reader);
Message reply = await Task.Factory.FromAsync(channel.BeginRequest, channel.EndRequest, requestMessage, null, TaskCreationOptions.None);
SecurityUtils.ThrowIfNegotiationFault(reply, channel.RemoteAddress);
trustResponse = serializer.ReadResponse(reply.GetReaderAtBodyContents());
CacheSecurityTokenResponse(request, trustResponse);
}
finally
{
await Task.Factory.FromAsync(channel.BeginClose, channel.EndClose, null, TaskCreationOptions.None);
}
}
}
return WSTrustUtilities.CreateGenericXmlSecurityToken(request, trustResponse, _requestSerializationContext, _securityAlgorithmSuite);
}
/// <summary>
/// Makes a WSTrust call to the STS to obtain a <see cref="SecurityToken"/> first checking if the token is available in the cache.
/// </summary>
/// <returns>A <see cref="GenericXmlSecurityToken"/>.</returns>
protected override SecurityToken GetTokenCore(TimeSpan timeout)
{
_communicationObject.ThrowIfClosedOrNotOpen();
WsTrustRequest request = CreateWsTrustRequest();
WsTrustResponse trustResponse = GetCachedResponse(request);
if (trustResponse is null)
{
using (var memeoryStream = new MemoryStream())
{
var writer = XmlDictionaryWriter.CreateTextWriter(memeoryStream, Encoding.UTF8);
var serializer = new WsTrustSerializer();
serializer.WriteRequest(writer, _requestSerializationContext.TrustVersion, request);
writer.Flush();
var reader = XmlDictionaryReader.CreateTextReader(memeoryStream.ToArray(), XmlDictionaryReaderQuotas.Max);
IRequestChannel channel = ChannelFactory.CreateChannel();
try
{
channel.Open();
Message reply = channel.Request(Message.CreateMessage(MessageVersion.Soap12WSAddressing10, _requestSerializationContext.TrustActions.IssueRequest, reader));
SecurityUtils.ThrowIfNegotiationFault(reply, channel.RemoteAddress);
trustResponse = serializer.ReadResponse(reply.GetReaderAtBodyContents());
CacheSecurityTokenResponse(request, trustResponse);
}
finally
{
channel.Close();
}
}
}
return WSTrustUtilities.CreateGenericXmlSecurityToken(request, trustResponse, _requestSerializationContext, _securityAlgorithmSuite);
}
private WsTrustVersion GetWsTrustVersion(MessageSecurityVersion messageSecurityVersion)
{
if (messageSecurityVersion.TrustVersion == TrustVersion.WSTrust13)
return WsTrustVersion.Trust13;
if (messageSecurityVersion.TrustVersion == TrustVersion.WSTrustFeb2005)
return WsTrustVersion.TrustFeb2005;
throw DiagnosticUtility.ExceptionUtility.ThrowHelper(new NotSupportedException(LogHelper.FormatInvariant(SR.GetResourceString(SR.WsTrustVersionNotSupported), MessageSecurityVersion.TrustVersion)), EventLevel.Error);
}
private void InitializeKeyEntropyMode()
{
// Default to combined entropy unless another option is specified in the issuer's security binding element.
// In previous versions of .NET WsTrust token providers, it was possible to set the default key entropy mode in client credentials.
// That scenario does not seem to be needed in .NET Core WsTrust scenarios, so key entropy mode is simply being read from the issuer's
// security binding element. If, in the future, it's necessary to change the default (if some scenarios don't have a security binding
// element, for example), that could be done by adding a DefaultKeyEntropyMode property to WsTrustChannelCredentials and moving
// the code that calculates KeyEntropyMode out to WSTrustChannelSecurityTokenManager since it can set this property
// when it creates the provider and fall back to the credentials' default value if no security binding element is present.
KeyEntropyMode = SecurityKeyEntropyMode.CombinedEntropy;
SecurityBindingElement securityBindingElement = IssuerBinding?.CreateBindingElements().Find<SecurityBindingElement>();
if (securityBindingElement != null)
{
KeyEntropyMode = securityBindingElement.KeyEntropyMode;
}
}
/// <summary>
/// Gets the issuer binding from the issued token parameters.
/// </summary>
///
internal Binding IssuerBinding
{
get => WSTrustTokenParameters?.IssuerBinding;
}
private bool IsWsTrustResponseExpired(WsTrustResponse response)
{
Lifetime responseLifetime = response?.RequestSecurityTokenResponseCollection?[0]?.Lifetime;
if (responseLifetime == null || responseLifetime.Expires == null)
{
// A null lifetime could represent an invalid response or a valid response
// with an unspecified expiration. Similarly, a response lifetime without an expiration
// time represents an unspecified expiration. In any of these cases, err on the side of
// retrieving a new response instead of possibly using an invalid or expired one.
return true;
}
// If a response's lifetime doesn't specify a created time, conservatively assume the response was just created.
DateTime fromTime = responseLifetime.Created?.ToUniversalTime() ?? DateTime.UtcNow;
DateTime toTime = responseLifetime.Expires.Value.ToUniversalTime();
long interval = toTime.Ticks - fromTime.Ticks;
long effectiveInterval = (long)((WSTrustTokenParameters.IssuedTokenRenewalThresholdPercentage / (double)100) * interval);
DateTime effectiveExpiration = AddTicks(fromTime, Math.Min(effectiveInterval, WSTrustTokenParameters.MaxIssuedTokenCachingTime.Ticks));
return effectiveExpiration < DateTime.UtcNow;
}
/// <summary>
/// Gets or sets the desired key entroy mode to use when making requests to the STS.
/// </summary>
internal SecurityKeyEntropyMode KeyEntropyMode
{
get => _keyEntropyMode;
set
{
if (!Enum.IsDefined(typeof(SecurityKeyEntropyMode), value))
throw DiagnosticUtility.ExceptionUtility.ThrowHelper(new InvalidEnumArgumentException(nameof(value), (int)value, typeof(SecurityKeyEntropyMode)), EventLevel.Error);
_keyEntropyMode = value;
}
}
internal MessageSecurityVersion MessageSecurityVersion
{
get;
set;
}
/// <summary>
/// Gets a string used as a context sent in WsTrustRequests that is useful for correlating requests.
/// </summary>
internal string RequestContext
{
get; private set;
}
/// <summary>
/// Gets the <see cref="SecurityTokenRequirement"/>
/// </summary>
internal SecurityTokenRequirement SecurityTokenRequirement
{
get;
}
/// <summary>
/// Set initial MessageSecurityVersion based on (in priority order):
/// <para>1. The message security version of the issuer binding's security binding element.</para>
/// <para>2. The provided DefaultMessageSecurityVersion from issued token parameters.</para>
/// <para>3. The message security version of the outer security binding element (from the security token requirement).</para>
/// <para>4. MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11.</para>
/// </summary>
private void SetInboundSerializationContext()
{
// WSTrustTokenParameters.MessageSecurityVersion can be checked directly instead of
// extracting MessageSecurityVersion from the issuer binding, because the WSFederationHttpBinding
// creates its security binding element using the MessageSecurityVersion from its WSTrustTokenParameters.
MessageSecurityVersion messageSecurityVersion = WSTrustTokenParameters.MessageSecurityVersion;
if (messageSecurityVersion == null)
messageSecurityVersion = WSTrustTokenParameters.DefaultMessageSecurityVersion;
if (messageSecurityVersion == null)
{
if (SecurityTokenRequirement.TryGetProperty(SecurityBindingElementProperty, out SecurityBindingElement outerSecurityBindingElement))
messageSecurityVersion = outerSecurityBindingElement.MessageSecurityVersion;
}
if (messageSecurityVersion == null)
messageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11;
MessageSecurityVersion = messageSecurityVersion;
_requestSerializationContext = new WsSerializationContext(GetWsTrustVersion(messageSecurityVersion));
}
public override bool SupportsTokenCancellation => false;
public override bool SupportsTokenRenewal => false;
internal WSTrustTokenParameters WSTrustTokenParameters { get; }
#region ISecurityCommunicationObject
// This implementation is based on a combination of IssuanceTokenProviderBase<T> and CommunicationObjectSecurityTokenProvider
// As this class is public, it's not possible to derive from the internal CommunicationObjectSecurityTokenProvider class so the
// equivalent implementation has been provided inline in this class.
void ISecurityCommunicationObject.OnAbort()
{
if (ChannelFactory != null && ChannelFactory.State == CommunicationState.Opened)
{
ChannelFactory.Abort();
ChannelFactory = null;
}
}
async Task ISecurityCommunicationObject.OnCloseAsync(TimeSpan timeout)
{
if (ChannelFactory != null && ChannelFactory.State == CommunicationState.Opened)
{
await Task.Factory.FromAsync(ChannelFactory.BeginClose, ChannelFactory.EndClose, timeout, null, TaskCreationOptions.None);
ChannelFactory = null;
}
}
async Task ISecurityCommunicationObject.OnOpenAsync(TimeSpan timeout)
{
InitializeKeyEntropyMode();
SetInboundSerializationContext();
RequestContext = string.IsNullOrEmpty(WSTrustTokenParameters.RequestContext) ? Guid.NewGuid().ToString() : WSTrustTokenParameters.RequestContext;
var channelFactory = new ChannelFactory<IRequestChannel>(IssuerBinding, WSTrustTokenParameters.IssuerAddress);
if (ClientCredentials != null)
{
channelFactory.Endpoint.EndpointBehaviors.Remove(typeof(ClientCredentials));
channelFactory.Endpoint.EndpointBehaviors.Add(ClientCredentials.Clone());
}
await Task.Factory.FromAsync(channelFactory.BeginOpen, channelFactory.EndOpen, null, TaskCreationOptions.None);
ChannelFactory = channelFactory;
}
void ISecurityCommunicationObject.OnClosed() { }
void ISecurityCommunicationObject.OnClosing() { }
void ISecurityCommunicationObject.OnFaulted() { }
void ISecurityCommunicationObject.OnOpened()
{
SecurityTraceRecordHelper.TraceTokenProviderOpened(EventTraceActivity, this);
}
void ISecurityCommunicationObject.OnOpening() { }
TimeSpan ISecurityCommunicationObject.DefaultOpenTimeout => ServiceDefaults.OpenTimeout;
TimeSpan ISecurityCommunicationObject.DefaultCloseTimeout => ServiceDefaults.CloseTimeout;
#endregion
#region ICommunicationObject
event EventHandler ICommunicationObject.Closed
{
add { _communicationObject.Closed += value; }
remove { _communicationObject.Closed -= value; }
}
event EventHandler ICommunicationObject.Closing
{
add { _communicationObject.Closing += value; }
remove { _communicationObject.Closing -= value; }
}
event EventHandler ICommunicationObject.Faulted
{
add { _communicationObject.Faulted += value; }
remove { _communicationObject.Faulted -= value; }
}
event EventHandler ICommunicationObject.Opened
{
add { _communicationObject.Opened += value; }
remove { _communicationObject.Opened -= value; }
}
event EventHandler ICommunicationObject.Opening
{
add { _communicationObject.Opening += value; }
remove { _communicationObject.Opening -= value; }
}
CommunicationState ICommunicationObject.State
{
get { return _communicationObject.State; }
}
void ICommunicationObject.Abort()
{
_communicationObject.Abort();
}
void ICommunicationObject.Close()
{
_communicationObject.Close();
}
void ICommunicationObject.Close(TimeSpan timeout)
{
_communicationObject.Close(timeout);
}
IAsyncResult ICommunicationObject.BeginClose(AsyncCallback callback, object state)
{
return _communicationObject.BeginClose(callback, state);
}
IAsyncResult ICommunicationObject.BeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
return _communicationObject.BeginClose(timeout, callback, state);
}
void ICommunicationObject.EndClose(IAsyncResult result)
{
_communicationObject.EndClose(result);
}
void ICommunicationObject.Open()
{
_communicationObject.Open();
}
void ICommunicationObject.Open(TimeSpan timeout)
{
_communicationObject.Open(timeout);
}
IAsyncResult ICommunicationObject.BeginOpen(AsyncCallback callback, object state)
{
return _communicationObject.BeginOpen(callback, state);
}
IAsyncResult ICommunicationObject.BeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return _communicationObject.BeginOpen(timeout, callback, state);
}
void ICommunicationObject.EndOpen(IAsyncResult result)
{
_communicationObject.EndOpen(result);
}
#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.Composition;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.SolutionCrawler
{
[ExportWorkspaceService(typeof(ISolutionCrawlerRegistrationService), ServiceLayer.Host), Shared]
internal partial class SolutionCrawlerRegistrationService : ISolutionCrawlerRegistrationService
{
private const string Default = "*";
private readonly object _gate;
private readonly SolutionCrawlerProgressReporter _progressReporter;
private readonly IAsynchronousOperationListener _listener;
private readonly Dictionary<Workspace, WorkCoordinator> _documentWorkCoordinatorMap;
private ImmutableDictionary<string, ImmutableArray<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>>> _analyzerProviders;
[ImportingConstructor]
public SolutionCrawlerRegistrationService(
[ImportMany] IEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>> analyzerProviders,
[ImportMany] IEnumerable<Lazy<IAsynchronousOperationListener, FeatureMetadata>> asyncListeners)
{
_gate = new object();
_analyzerProviders = analyzerProviders.GroupBy(kv => kv.Metadata.Name).ToImmutableDictionary(g => g.Key, g => g.ToImmutableArray());
AssertAnalyzerProviders(_analyzerProviders);
_documentWorkCoordinatorMap = new Dictionary<Workspace, WorkCoordinator>(ReferenceEqualityComparer.Instance);
_listener = new AggregateAsynchronousOperationListener(asyncListeners, FeatureAttribute.SolutionCrawler);
_progressReporter = new SolutionCrawlerProgressReporter(_listener);
}
public void Register(Workspace workspace)
{
var correlationId = LogAggregator.GetNextId();
lock (_gate)
{
if (_documentWorkCoordinatorMap.ContainsKey(workspace))
{
// already registered.
return;
}
var coordinator = new WorkCoordinator(
_listener,
GetAnalyzerProviders(workspace),
new Registration(correlationId, workspace, _progressReporter));
_documentWorkCoordinatorMap.Add(workspace, coordinator);
}
SolutionCrawlerLogger.LogRegistration(correlationId, workspace);
}
public void Unregister(Workspace workspace, bool blockingShutdown = false)
{
var coordinator = default(WorkCoordinator);
lock (_gate)
{
if (!_documentWorkCoordinatorMap.TryGetValue(workspace, out coordinator))
{
// already unregistered
return;
}
_documentWorkCoordinatorMap.Remove(workspace);
coordinator.Shutdown(blockingShutdown);
}
SolutionCrawlerLogger.LogUnregistration(coordinator.CorrelationId);
}
public void AddAnalyzerProvider(IIncrementalAnalyzerProvider provider, IncrementalAnalyzerProviderMetadata metadata)
{
// now update all existing work coordinator
lock (_gate)
{
var lazyProvider = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => provider, metadata);
// update existing map for future solution crawler registration - no need for interlock but this makes add or update easier
ImmutableInterlocked.AddOrUpdate(ref _analyzerProviders, metadata.Name, (n) => ImmutableArray.Create(lazyProvider), (n, v) => v.Add(lazyProvider));
// assert map integrity
AssertAnalyzerProviders(_analyzerProviders);
// find existing coordinator to update
var lazyProviders = _analyzerProviders[metadata.Name];
foreach (var kv in _documentWorkCoordinatorMap)
{
var workspace = kv.Key;
var coordinator = kv.Value;
if (!TryGetProvider(workspace.Kind, lazyProviders, out var picked) || picked != lazyProvider)
{
// check whether new provider belong to current workspace
continue;
}
var analyzer = lazyProvider.Value.CreateIncrementalAnalyzer(workspace);
coordinator.AddAnalyzer(analyzer, metadata.HighPriorityForActiveFile);
}
}
}
public void Reanalyze(Workspace workspace, IIncrementalAnalyzer analyzer, IEnumerable<ProjectId> projectIds, IEnumerable<DocumentId> documentIds, bool highPriority)
{
lock (_gate)
{
if (!_documentWorkCoordinatorMap.TryGetValue(workspace, out var coordinator))
{
// this can happen if solution crawler is already unregistered from workspace.
// one of those example will be VS shutting down so roslyn package is disposed but there is a pending
// async operation.
return;
}
// no specific projects or documents provided
if (projectIds == null && documentIds == null)
{
coordinator.Reanalyze(analyzer, workspace.CurrentSolution.Projects.SelectMany(p => p.DocumentIds).ToSet(), highPriority);
return;
}
// specific documents provided
if (projectIds == null)
{
coordinator.Reanalyze(analyzer, documentIds.ToSet(), highPriority);
return;
}
var solution = workspace.CurrentSolution;
var set = new HashSet<DocumentId>(documentIds ?? SpecializedCollections.EmptyEnumerable<DocumentId>());
set.UnionWith(projectIds.Select(id => solution.GetProject(id)).SelectMany(p => p.DocumentIds));
coordinator.Reanalyze(analyzer, set, highPriority);
}
}
internal void WaitUntilCompletion_ForTestingPurposesOnly(Workspace workspace, ImmutableArray<IIncrementalAnalyzer> workers)
{
if (_documentWorkCoordinatorMap.ContainsKey(workspace))
{
_documentWorkCoordinatorMap[workspace].WaitUntilCompletion_ForTestingPurposesOnly(workers);
}
}
internal void WaitUntilCompletion_ForTestingPurposesOnly(Workspace workspace)
{
if (_documentWorkCoordinatorMap.ContainsKey(workspace))
{
_documentWorkCoordinatorMap[workspace].WaitUntilCompletion_ForTestingPurposesOnly();
}
}
private IEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>> GetAnalyzerProviders(Workspace workspace)
{
foreach (var kv in _analyzerProviders)
{
var lazyProviders = kv.Value;
// try get provider for the specific workspace kind
if (TryGetProvider(workspace.Kind, lazyProviders, out var lazyProvider))
{
yield return lazyProvider;
continue;
}
// try get default provider
if (TryGetProvider(Default, lazyProviders, out lazyProvider))
{
yield return lazyProvider;
}
}
}
private bool TryGetProvider(
string kind,
ImmutableArray<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>> lazyProviders,
out Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata> lazyProvider)
{
// set out param
lazyProvider = null;
// try find provider for specific workspace kind
if (kind != Default)
{
foreach (var provider in lazyProviders)
{
if (provider.Metadata.WorkspaceKinds?.Any(wk => wk == kind) == true)
{
lazyProvider = provider;
return true;
}
}
return false;
}
// try find default provider
foreach (var provider in lazyProviders)
{
if (IsDefaultProvider(provider.Metadata))
{
lazyProvider = provider;
return true;
}
return false;
}
return false;
}
[Conditional("DEBUG")]
private static void AssertAnalyzerProviders(
ImmutableDictionary<string, ImmutableArray<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>>> analyzerProviders)
{
#if DEBUG
// make sure there is duplicated provider defined for same workspace.
var set = new HashSet<string>();
foreach (var kv in analyzerProviders)
{
foreach (var lazyProvider in kv.Value)
{
if (IsDefaultProvider(lazyProvider.Metadata))
{
Contract.Requires(set.Add(Default));
continue;
}
foreach (var kind in lazyProvider.Metadata.WorkspaceKinds)
{
Contract.Requires(set.Add(kind));
}
}
set.Clear();
}
#endif
}
private static bool IsDefaultProvider(IncrementalAnalyzerProviderMetadata providerMetadata)
{
return providerMetadata.WorkspaceKinds == null || providerMetadata.WorkspaceKinds.Length == 0;
}
private class Registration
{
public readonly int CorrelationId;
public readonly Workspace Workspace;
public readonly SolutionCrawlerProgressReporter ProgressReporter;
public Registration(int correlationId, Workspace workspace, SolutionCrawlerProgressReporter progressReporter)
{
CorrelationId = correlationId;
Workspace = workspace;
ProgressReporter = progressReporter;
}
public Solution CurrentSolution => Workspace.CurrentSolution;
public TService GetService<TService>() where TService : IWorkspaceService
{
return Workspace.Services.GetService<TService>();
}
}
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Threading;
using ArcGIS.Core.CIM;
using ArcGIS.Core.Data;
using ArcGIS.Core.Events;
using ArcGIS.Core.Geometry;
using ArcGIS.Desktop.Catalog;
using ArcGIS.Desktop.Core;
using ArcGIS.Desktop.Editing;
using ArcGIS.Desktop.Editing.Attributes;
using ArcGIS.Desktop.Editing.Events;
using ArcGIS.Desktop.Extensions;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Contracts;
using ArcGIS.Desktop.Framework.Dialogs;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using ArcGIS.Desktop.Mapping;
using ArcGIS.Desktop.Mapping.Events;
namespace ModifyNewlyAddedFeatures
{
internal class ModifyMonitorViewModel : DockPane
{
private const string _dockPaneID = "ModifyNewlyAddedFeatures_ModifyMonitor";
private string _txtStatus;
private string _polygonLayerName = "TestPolygons";
private string _pointLayerName = "TestPoints";
private bool _isStoreInOnRowEventEnabled = false;
private bool _isModificationEnabled = false;
private SubscriptionToken _activeMapViewChangedEvent = null;
private SubscriptionToken _onRowChangedEvent = null;
private SubscriptionToken _onRowCreatedEvent = null;
private SubscriptionToken _onRowPointCreatedEvent = null;
private FeatureLayer _workedOnPolygonLayer = null;
private FeatureLayer _workedOnPointLayer = null;
protected ModifyMonitorViewModel() { }
private void ActivateModification()
{
DeActivateModification();
UpdateStatusText($@"Activate Modification - MapView active: {(MapView.Active != null)}");
var activeMapView = MapView.Active;
if (activeMapView == null)
{
// the map view is not active yet
_activeMapViewChangedEvent = ActiveMapViewChangedEvent.Subscribe(OnActiveMapViewChangedEvent);
return;
}
SetUpRowEventListener(activeMapView, PolygonLayerName, PointLayerName);
}
private void DeActivateModification()
{
if (_activeMapViewChangedEvent != null || _onRowChangedEvent != null || _onRowCreatedEvent != null || _onRowPointCreatedEvent != null)
{
UpdateStatusText($@"DeActivate Modification");
if (_activeMapViewChangedEvent != null) ActiveMapViewChangedEvent.Unsubscribe(_activeMapViewChangedEvent);
QueuedTask.Run(() =>
{
if (_onRowChangedEvent != null) RowChangedEvent.Unsubscribe(_onRowChangedEvent);
if (_onRowCreatedEvent != null) RowChangedEvent.Unsubscribe(_onRowCreatedEvent);
if (_onRowPointCreatedEvent != null) RowChangedEvent.Unsubscribe(_onRowPointCreatedEvent);
});
_onRowChangedEvent = null;
_onRowCreatedEvent = null;
_onRowPointCreatedEvent = null;
_activeMapViewChangedEvent = null;
}
}
/// <summary>
/// setup event listeners for a given featurelayer (with featurelayer name)
/// </summary>
/// <param name="activeMapView"></param>
/// <param name="polygonFeatureLayerName"></param>
/// <param name="pointFeatureLayerName"></param>
private void SetUpRowEventListener(MapView activeMapView, string polygonFeatureLayerName, string pointFeatureLayerName)
{
// Find our polygon feature layer
_workedOnPolygonLayer = activeMapView.Map.GetLayersAsFlattenedList().FirstOrDefault((fl) => fl.Name == polygonFeatureLayerName) as FeatureLayer;
UpdateStatusText((_workedOnPolygonLayer == null)
? $@"{polygonFeatureLayerName} NOT found"
: $@"Listening to {polygonFeatureLayerName} changes");
_workedOnPointLayer = activeMapView.Map.GetLayersAsFlattenedList().FirstOrDefault((fl) => fl.Name == pointFeatureLayerName) as FeatureLayer;
UpdateStatusText((_workedOnPolygonLayer == null)
? $@"{pointFeatureLayerName} NOT found"
: $@"Listening to {pointFeatureLayerName} changes");
// setup event listening ...
if (_workedOnPointLayer != null && _workedOnPolygonLayer != null)
{
QueuedTask.Run(() =>
{
_onRowChangedEvent = RowChangedEvent.Subscribe(OnRowChangedEvent, _workedOnPolygonLayer.GetTable());
_onRowCreatedEvent = RowCreatedEvent.Subscribe(OnRowCreatedEvent, _workedOnPolygonLayer.GetTable());
_onRowPointCreatedEvent = RowCreatedEvent.Subscribe(OnPointRowCreatedEvent, _workedOnPointLayer.GetTable());
});
}
}
/// <summary>
/// Called for each row change
/// </summary>
/// <param name="args"></param>
private void OnRowChangedEvent(RowChangedEventArgs args)
{
UpdateStatusText($@"Row changed: {args.EditType}");
UpdateRowIfNeeded(args);
}
/// <summary>
/// called for each newly created row
/// </summary>
/// <param name="args"></param>
private void OnRowCreatedEvent(RowChangedEventArgs args)
{
UpdateStatusText($@"Row created: {args.EditType}");
UpdateRowIfNeeded(args);
}
private void OnPointRowCreatedEvent(RowChangedEventArgs args)
{
UpdateStatusText($@"Point Row created: {args.EditType}");
}
private Guid _currentRowChangedGuid = Guid.Empty;
private void UpdateRowIfNeeded(RowChangedEventArgs args)
{
// From the ProConcept documentation @https://github.com/esri/arcgis-pro-sdk/wiki/ProConcepts-Editing#row-events
// If you need to edit additional tables within the RowEvent you must use the
// ArcGIS.Core.Data API to edit the tables directly.
// Do not use a new edit operation to create or modify features or rows in your
// RowEvent callbacks.
// RowEvent callbacks are always called on the QueuedTask so there is no need
// to wrap your code within a QueuedTask.Run lambda.
try
{
// prevent re-entrance (only if row.Store() is called)
if (_isStoreInOnRowEventEnabled
&& _currentRowChangedGuid == args.Guid)
{
UpdateStatusText($@"Re-entrant call - ignored");
return;
}
var row = args.Row;
var rowDefinition = (row.GetTable() as FeatureClass).GetDefinition();
var geom = row[rowDefinition.GetShapeField()] as Geometry;
MapPoint pntLogging = null;
var rowCursorOverlayPoly = _workedOnPolygonLayer.Search(geom, SpatialRelationship.Intersects);
Geometry geomOverlap = null;
Geometry geomChangedPolygon = null;
while (rowCursorOverlayPoly.MoveNext())
{
var feature = rowCursorOverlayPoly.Current as Feature;
var geomOverlayPoly = feature.GetShape();
if (geomOverlayPoly == null) continue;
// exclude the search polygon
if (row.GetObjectID() == feature.GetObjectID())
{
geomChangedPolygon = geomOverlayPoly.Clone();
continue;
}
if (geomOverlap == null)
{
geomOverlap = geomOverlayPoly.Clone();
continue;
}
geomOverlap = GeometryEngine.Instance.Union(geomOverlap, geomOverlayPoly);
}
var description = string.Empty;
if (!geomOverlap.IsNullOrEmpty())
{
var correctedGeom = GeometryEngine.Instance.Difference(geom, geomOverlap);
row["Shape"] = correctedGeom;
if (!correctedGeom.IsNullOrEmpty())
{
// use the centerpoint of the polygon as the point for the logging entry
pntLogging = GeometryEngine.Instance.LabelPoint(correctedGeom);
}
description = correctedGeom.IsEmpty ? "Polygon can't be inside existing polygon" : "Corrected input polygon";
}
else
{
description = "No overlapping polygons found";
if (!geomChangedPolygon.IsNullOrEmpty())
{
pntLogging = GeometryEngine.Instance.LabelPoint(geomChangedPolygon);
}
}
row["Description"] = description;
UpdateStatusText($@"Row: {description}");
if (_isStoreInOnRowEventEnabled)
{
// calling store will result in a recursive row changed event as long as any
// attribute columns have changed
// In this case i would need to look at args.Guid to prevent re-entrance
_currentRowChangedGuid = args.Guid;
row.Store();
_currentRowChangedGuid = Guid.Empty;
}
// update logging feature class with centerpoint of polygon
if (!pntLogging.IsNullOrEmpty())
{
var geoDatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(Project.Current.DefaultGeodatabasePath)));
var loggingFeatureClass = geoDatabase.OpenDataset<FeatureClass>(_pointLayerName);
var loggingFCDefinition = loggingFeatureClass.GetDefinition();
using (var rowbuff = loggingFeatureClass.CreateRowBuffer())
{
// needs a 3D point
rowbuff[loggingFCDefinition.GetShapeField()] = MapPointBuilder.CreateMapPoint(pntLogging.X, pntLogging.Y, 0, pntLogging.SpatialReference);
rowbuff["Description"] = "OID: " + row.GetObjectID().ToString() + " " + DateTime.Now.ToShortTimeString();
loggingFeatureClass.CreateRow(rowbuff);
}
}
}
catch (Exception e)
{
MessageBox.Show($@"Error in UpdateRowIfNeeded for OID: {args.Row.GetObjectID()} in {_workedOnPolygonLayer.Name}: {e.ToString()}");
}
}
/// <summary>
/// Waiting for the active map view to change in order to setup event listening
/// </summary>
/// <param name="args"></param>
private void OnActiveMapViewChangedEvent(ActiveMapViewChangedEventArgs args)
{
if (args.IncomingView != null)
{
SetUpRowEventListener(args.IncomingView, PolygonLayerName, PointLayerName);
ActiveMapViewChangedEvent.Unsubscribe(_activeMapViewChangedEvent);
_activeMapViewChangedEvent = null;
}
}
/// <summary>
/// Using RowChangedEventArgs returns inspector for changes (created) row
/// </summary>
/// <param name="args"></param>
/// <returns></returns>
private async Task<Inspector> GetInspectorForRow(RowChangedEventArgs args)
{
Inspector inspr = new Inspector();
try
{
//Load the inspector
await inspr.LoadAsync(_workedOnPolygonLayer, args.Row.GetObjectID());
}
catch (Exception e)
{
MessageBox.Show($@"Unable to get Inspector for OID: {args.Row.GetObjectID()} in {_workedOnPolygonLayer.Name}: {e.ToString()}");
}
return inspr;
}
/// <summary>
/// Update status text on GUI thread from non GUI thread
/// </summary>
/// <param name="text"></param>
private void UpdateStatusText(string text)
{
if (System.Windows.Application.Current.Dispatcher.CheckAccess())
{
TxtStatus += text + Environment.NewLine;
}
else
{
ProApp.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
(Action)(() =>
{
TxtStatus += text + Environment.NewLine;
}));
}
}
/// <summary>
/// Name of the Feature Layer to work with
/// </summary>
public string TxtStatus
{
get { return _txtStatus; }
set
{
SetProperty(ref _txtStatus, value, () => TxtStatus);
}
}
/// <summary>
/// Polygon Layer Name
/// </summary>
public string PolygonLayerName
{
get { return _polygonLayerName; }
set
{
SetProperty(ref _polygonLayerName, value, () => PolygonLayerName);
}
}
/// <summary>
/// Point Layer Name
/// </summary>
public string PointLayerName
{
get { return _pointLayerName; }
set
{
SetProperty(ref _pointLayerName, value, () => PointLayerName);
}
}
public bool IsStoreInOnRowEventEnabled
{
get { return _isStoreInOnRowEventEnabled; }
set
{
if (value == _isStoreInOnRowEventEnabled) return;
SetProperty(ref _isStoreInOnRowEventEnabled, value, () => IsStoreInOnRowEventEnabled);
}
}
public bool IsModificationEnabled
{
get { return _isModificationEnabled; }
set
{
if (value == _isModificationEnabled) return;
SetProperty(ref _isModificationEnabled, value, () => IsModificationEnabled);
if (_isModificationEnabled) ActivateModification();
else DeActivateModification();
}
}
/// <summary>
/// Show the DockPane.
/// </summary>
internal static void Show()
{
DockPane pane = FrameworkApplication.DockPaneManager.Find(_dockPaneID);
if (pane == null)
return;
pane.Activate();
}
/// <summary>
/// Text shown near the top of the DockPane.
/// </summary>
private string _heading = "Modify New Added Row Monitor";
public string Heading
{
get { return _heading; }
set
{
SetProperty(ref _heading, value, () => Heading);
}
}
}
/// <summary>
/// Button implementation to show the DockPane.
/// </summary>
internal class ModifyMonitor_ShowButton : Button
{
protected override void OnClick()
{
ModifyMonitorViewModel.Show();
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: booking/reservations/recommended_checkin_card_authorization_amounts.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace HOLMS.Types.Booking.Reservations {
/// <summary>Holder for reflection information generated from booking/reservations/recommended_checkin_card_authorization_amounts.proto</summary>
public static partial class RecommendedCheckinCardAuthorizationAmountsReflection {
#region Descriptor
/// <summary>File descriptor for booking/reservations/recommended_checkin_card_authorization_amounts.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static RecommendedCheckinCardAuthorizationAmountsReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cklib29raW5nL3Jlc2VydmF0aW9ucy9yZWNvbW1lbmRlZF9jaGVja2luX2Nh",
"cmRfYXV0aG9yaXphdGlvbl9hbW91bnRzLnByb3RvEiBob2xtcy50eXBlcy5i",
"b29raW5nLnJlc2VydmF0aW9ucxofcHJpbWl0aXZlL21vbmV0YXJ5X2Ftb3Vu",
"dC5wcm90byLUAgomUmVjb21tZW5kZWRDaGVja2luQXV0aG9yaXphdGlvbkFt",
"b3VudHMSRwoYbWluaW11bV9ndWFyYW50ZWVfdm9pZGVkGAEgASgLMiUuaG9s",
"bXMudHlwZXMucHJpbWl0aXZlLk1vbmV0YXJ5QW1vdW50EkoKG3dob2xlX3N0",
"YXlfZ3VhcmFudGVlX3ZvaWRlZBgCIAEoCzIlLmhvbG1zLnR5cGVzLnByaW1p",
"dGl2ZS5Nb25ldGFyeUFtb3VudBJIChltaW5pbXVtX2d1YXJhbnRlZV9jaGFy",
"Z2VkGAMgASgLMiUuaG9sbXMudHlwZXMucHJpbWl0aXZlLk1vbmV0YXJ5QW1v",
"dW50EksKHHdob2xlX3N0YXlfZ3VhcmFudGVlX2NoYXJnZWQYBCABKAsyJS5o",
"b2xtcy50eXBlcy5wcmltaXRpdmUuTW9uZXRhcnlBbW91bnRCOVoUYm9va2lu",
"Zy9yZXNlcnZhdGlvbnOqAiBIT0xNUy5UeXBlcy5Cb29raW5nLlJlc2VydmF0",
"aW9uc2IGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::HOLMS.Types.Primitive.MonetaryAmountReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.Reservations.RecommendedCheckinAuthorizationAmounts), global::HOLMS.Types.Booking.Reservations.RecommendedCheckinAuthorizationAmounts.Parser, new[]{ "MinimumGuaranteeVoided", "WholeStayGuaranteeVoided", "MinimumGuaranteeCharged", "WholeStayGuaranteeCharged" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class RecommendedCheckinAuthorizationAmounts : pb::IMessage<RecommendedCheckinAuthorizationAmounts> {
private static readonly pb::MessageParser<RecommendedCheckinAuthorizationAmounts> _parser = new pb::MessageParser<RecommendedCheckinAuthorizationAmounts>(() => new RecommendedCheckinAuthorizationAmounts());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<RecommendedCheckinAuthorizationAmounts> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Booking.Reservations.RecommendedCheckinCardAuthorizationAmountsReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RecommendedCheckinAuthorizationAmounts() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RecommendedCheckinAuthorizationAmounts(RecommendedCheckinAuthorizationAmounts other) : this() {
MinimumGuaranteeVoided = other.minimumGuaranteeVoided_ != null ? other.MinimumGuaranteeVoided.Clone() : null;
WholeStayGuaranteeVoided = other.wholeStayGuaranteeVoided_ != null ? other.WholeStayGuaranteeVoided.Clone() : null;
MinimumGuaranteeCharged = other.minimumGuaranteeCharged_ != null ? other.MinimumGuaranteeCharged.Clone() : null;
WholeStayGuaranteeCharged = other.wholeStayGuaranteeCharged_ != null ? other.WholeStayGuaranteeCharged.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RecommendedCheckinAuthorizationAmounts Clone() {
return new RecommendedCheckinAuthorizationAmounts(this);
}
/// <summary>Field number for the "minimum_guarantee_voided" field.</summary>
public const int MinimumGuaranteeVoidedFieldNumber = 1;
private global::HOLMS.Types.Primitive.MonetaryAmount minimumGuaranteeVoided_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Primitive.MonetaryAmount MinimumGuaranteeVoided {
get { return minimumGuaranteeVoided_; }
set {
minimumGuaranteeVoided_ = value;
}
}
/// <summary>Field number for the "whole_stay_guarantee_voided" field.</summary>
public const int WholeStayGuaranteeVoidedFieldNumber = 2;
private global::HOLMS.Types.Primitive.MonetaryAmount wholeStayGuaranteeVoided_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Primitive.MonetaryAmount WholeStayGuaranteeVoided {
get { return wholeStayGuaranteeVoided_; }
set {
wholeStayGuaranteeVoided_ = value;
}
}
/// <summary>Field number for the "minimum_guarantee_charged" field.</summary>
public const int MinimumGuaranteeChargedFieldNumber = 3;
private global::HOLMS.Types.Primitive.MonetaryAmount minimumGuaranteeCharged_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Primitive.MonetaryAmount MinimumGuaranteeCharged {
get { return minimumGuaranteeCharged_; }
set {
minimumGuaranteeCharged_ = value;
}
}
/// <summary>Field number for the "whole_stay_guarantee_charged" field.</summary>
public const int WholeStayGuaranteeChargedFieldNumber = 4;
private global::HOLMS.Types.Primitive.MonetaryAmount wholeStayGuaranteeCharged_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Primitive.MonetaryAmount WholeStayGuaranteeCharged {
get { return wholeStayGuaranteeCharged_; }
set {
wholeStayGuaranteeCharged_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as RecommendedCheckinAuthorizationAmounts);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(RecommendedCheckinAuthorizationAmounts other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(MinimumGuaranteeVoided, other.MinimumGuaranteeVoided)) return false;
if (!object.Equals(WholeStayGuaranteeVoided, other.WholeStayGuaranteeVoided)) return false;
if (!object.Equals(MinimumGuaranteeCharged, other.MinimumGuaranteeCharged)) return false;
if (!object.Equals(WholeStayGuaranteeCharged, other.WholeStayGuaranteeCharged)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (minimumGuaranteeVoided_ != null) hash ^= MinimumGuaranteeVoided.GetHashCode();
if (wholeStayGuaranteeVoided_ != null) hash ^= WholeStayGuaranteeVoided.GetHashCode();
if (minimumGuaranteeCharged_ != null) hash ^= MinimumGuaranteeCharged.GetHashCode();
if (wholeStayGuaranteeCharged_ != null) hash ^= WholeStayGuaranteeCharged.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (minimumGuaranteeVoided_ != null) {
output.WriteRawTag(10);
output.WriteMessage(MinimumGuaranteeVoided);
}
if (wholeStayGuaranteeVoided_ != null) {
output.WriteRawTag(18);
output.WriteMessage(WholeStayGuaranteeVoided);
}
if (minimumGuaranteeCharged_ != null) {
output.WriteRawTag(26);
output.WriteMessage(MinimumGuaranteeCharged);
}
if (wholeStayGuaranteeCharged_ != null) {
output.WriteRawTag(34);
output.WriteMessage(WholeStayGuaranteeCharged);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (minimumGuaranteeVoided_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(MinimumGuaranteeVoided);
}
if (wholeStayGuaranteeVoided_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(WholeStayGuaranteeVoided);
}
if (minimumGuaranteeCharged_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(MinimumGuaranteeCharged);
}
if (wholeStayGuaranteeCharged_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(WholeStayGuaranteeCharged);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(RecommendedCheckinAuthorizationAmounts other) {
if (other == null) {
return;
}
if (other.minimumGuaranteeVoided_ != null) {
if (minimumGuaranteeVoided_ == null) {
minimumGuaranteeVoided_ = new global::HOLMS.Types.Primitive.MonetaryAmount();
}
MinimumGuaranteeVoided.MergeFrom(other.MinimumGuaranteeVoided);
}
if (other.wholeStayGuaranteeVoided_ != null) {
if (wholeStayGuaranteeVoided_ == null) {
wholeStayGuaranteeVoided_ = new global::HOLMS.Types.Primitive.MonetaryAmount();
}
WholeStayGuaranteeVoided.MergeFrom(other.WholeStayGuaranteeVoided);
}
if (other.minimumGuaranteeCharged_ != null) {
if (minimumGuaranteeCharged_ == null) {
minimumGuaranteeCharged_ = new global::HOLMS.Types.Primitive.MonetaryAmount();
}
MinimumGuaranteeCharged.MergeFrom(other.MinimumGuaranteeCharged);
}
if (other.wholeStayGuaranteeCharged_ != null) {
if (wholeStayGuaranteeCharged_ == null) {
wholeStayGuaranteeCharged_ = new global::HOLMS.Types.Primitive.MonetaryAmount();
}
WholeStayGuaranteeCharged.MergeFrom(other.WholeStayGuaranteeCharged);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (minimumGuaranteeVoided_ == null) {
minimumGuaranteeVoided_ = new global::HOLMS.Types.Primitive.MonetaryAmount();
}
input.ReadMessage(minimumGuaranteeVoided_);
break;
}
case 18: {
if (wholeStayGuaranteeVoided_ == null) {
wholeStayGuaranteeVoided_ = new global::HOLMS.Types.Primitive.MonetaryAmount();
}
input.ReadMessage(wholeStayGuaranteeVoided_);
break;
}
case 26: {
if (minimumGuaranteeCharged_ == null) {
minimumGuaranteeCharged_ = new global::HOLMS.Types.Primitive.MonetaryAmount();
}
input.ReadMessage(minimumGuaranteeCharged_);
break;
}
case 34: {
if (wholeStayGuaranteeCharged_ == null) {
wholeStayGuaranteeCharged_ = new global::HOLMS.Types.Primitive.MonetaryAmount();
}
input.ReadMessage(wholeStayGuaranteeCharged_);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
// 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.Contracts;
using System.Security;
namespace System.IO
{
public sealed partial class DirectoryInfo : FileSystemInfo
{
[System.Security.SecuritySafeCritical]
public DirectoryInfo(string path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
Contract.EndContractBlock();
OriginalPath = PathHelpers.ShouldReviseDirectoryPathToCurrent(path) ? "." : path;
FullPath = Path.GetFullPath(path);
DisplayPath = GetDisplayName(OriginalPath);
}
[System.Security.SecuritySafeCritical]
internal DirectoryInfo(string fullPath, string originalPath)
{
Debug.Assert(Path.IsPathRooted(fullPath), "fullPath must be fully qualified!");
// Fast path when we know a DirectoryInfo exists.
OriginalPath = originalPath ?? Path.GetFileName(fullPath);
FullPath = fullPath;
DisplayPath = GetDisplayName(OriginalPath);
}
public override string Name
{
get
{
return GetDirName(FullPath);
}
}
public DirectoryInfo Parent
{
[System.Security.SecuritySafeCritical]
get
{
string s = FullPath;
// FullPath might end in either "parent\child" or "parent\child", and in either case we want
// the parent of child, not the child. Trim off an ending directory separator if there is one,
// but don't mangle the root.
if (!PathHelpers.IsRoot(s))
{
s = PathHelpers.TrimEndingDirectorySeparator(s);
}
string parentName = Path.GetDirectoryName(s);
return parentName != null ?
new DirectoryInfo(parentName, null) :
null;
}
}
[System.Security.SecuritySafeCritical]
public DirectoryInfo CreateSubdirectory(string path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
Contract.EndContractBlock();
return CreateSubdirectoryHelper(path);
}
[System.Security.SecurityCritical] // auto-generated
private DirectoryInfo CreateSubdirectoryHelper(string path)
{
Debug.Assert(path != null);
PathHelpers.ThrowIfEmptyOrRootedPath(path);
string newDirs = Path.Combine(FullPath, path);
string fullPath = Path.GetFullPath(newDirs);
if (0 != string.Compare(FullPath, 0, fullPath, 0, FullPath.Length, PathInternal.StringComparison))
{
throw new ArgumentException(SR.Format(SR.Argument_InvalidSubPath, path, DisplayPath), nameof(path));
}
FileSystem.Current.CreateDirectory(fullPath);
// Check for read permission to directory we hand back by calling this constructor.
return new DirectoryInfo(fullPath);
}
[System.Security.SecurityCritical]
public void Create()
{
FileSystem.Current.CreateDirectory(FullPath);
}
// Tests if the given path refers to an existing DirectoryInfo on disk.
//
// Your application must have Read permission to the directory's
// contents.
//
public override bool Exists
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
try
{
return FileSystemObject.Exists;
}
catch
{
return false;
}
}
}
// Returns an array of Files in the current DirectoryInfo matching the
// given search criteria (i.e. "*.txt").
[SecurityCritical]
public FileInfo[] GetFiles(string searchPattern)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
Contract.EndContractBlock();
return InternalGetFiles(searchPattern, SearchOption.TopDirectoryOnly);
}
// Returns an array of Files in the current DirectoryInfo matching the
// given search criteria (i.e. "*.txt").
public FileInfo[] GetFiles(string searchPattern, SearchOption searchOption)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum);
Contract.EndContractBlock();
return InternalGetFiles(searchPattern, searchOption);
}
// Returns an array of Files in the current DirectoryInfo matching the
// given search criteria (i.e. "*.txt").
private FileInfo[] InternalGetFiles(string searchPattern, SearchOption searchOption)
{
Debug.Assert(searchPattern != null);
Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
IEnumerable<FileInfo> enumerable = (IEnumerable<FileInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Files);
return EnumerableHelpers.ToArray(enumerable);
}
// Returns an array of Files in the DirectoryInfo specified by path
public FileInfo[] GetFiles()
{
return InternalGetFiles("*", SearchOption.TopDirectoryOnly);
}
// Returns an array of Directories in the current directory.
public DirectoryInfo[] GetDirectories()
{
return InternalGetDirectories("*", SearchOption.TopDirectoryOnly);
}
// Returns an array of strongly typed FileSystemInfo entries in the path with the
// given search criteria (i.e. "*.txt").
public FileSystemInfo[] GetFileSystemInfos(string searchPattern)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
Contract.EndContractBlock();
return InternalGetFileSystemInfos(searchPattern, SearchOption.TopDirectoryOnly);
}
// Returns an array of strongly typed FileSystemInfo entries in the path with the
// given search criteria (i.e. "*.txt").
public FileSystemInfo[] GetFileSystemInfos(string searchPattern, SearchOption searchOption)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum);
Contract.EndContractBlock();
return InternalGetFileSystemInfos(searchPattern, searchOption);
}
// Returns an array of strongly typed FileSystemInfo entries in the path with the
// given search criteria (i.e. "*.txt").
private FileSystemInfo[] InternalGetFileSystemInfos(string searchPattern, SearchOption searchOption)
{
Debug.Assert(searchPattern != null);
Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
IEnumerable<FileSystemInfo> enumerable = FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Both);
return EnumerableHelpers.ToArray(enumerable);
}
// Returns an array of strongly typed FileSystemInfo entries which will contain a listing
// of all the files and directories.
public FileSystemInfo[] GetFileSystemInfos()
{
return InternalGetFileSystemInfos("*", SearchOption.TopDirectoryOnly);
}
// Returns an array of Directories in the current DirectoryInfo matching the
// given search criteria (i.e. "System*" could match the System & System32
// directories).
public DirectoryInfo[] GetDirectories(string searchPattern)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
Contract.EndContractBlock();
return InternalGetDirectories(searchPattern, SearchOption.TopDirectoryOnly);
}
// Returns an array of Directories in the current DirectoryInfo matching the
// given search criteria (i.e. "System*" could match the System & System32
// directories).
public DirectoryInfo[] GetDirectories(string searchPattern, SearchOption searchOption)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum);
Contract.EndContractBlock();
return InternalGetDirectories(searchPattern, searchOption);
}
// Returns an array of Directories in the current DirectoryInfo matching the
// given search criteria (i.e. "System*" could match the System & System32
// directories).
private DirectoryInfo[] InternalGetDirectories(string searchPattern, SearchOption searchOption)
{
Debug.Assert(searchPattern != null);
Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
IEnumerable<DirectoryInfo> enumerable = (IEnumerable<DirectoryInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Directories);
return EnumerableHelpers.ToArray(enumerable);
}
public IEnumerable<DirectoryInfo> EnumerateDirectories()
{
return InternalEnumerateDirectories("*", SearchOption.TopDirectoryOnly);
}
public IEnumerable<DirectoryInfo> EnumerateDirectories(string searchPattern)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
Contract.EndContractBlock();
return InternalEnumerateDirectories(searchPattern, SearchOption.TopDirectoryOnly);
}
public IEnumerable<DirectoryInfo> EnumerateDirectories(string searchPattern, SearchOption searchOption)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum);
Contract.EndContractBlock();
return InternalEnumerateDirectories(searchPattern, searchOption);
}
private IEnumerable<DirectoryInfo> InternalEnumerateDirectories(string searchPattern, SearchOption searchOption)
{
Debug.Assert(searchPattern != null);
Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
return (IEnumerable<DirectoryInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Directories);
}
public IEnumerable<FileInfo> EnumerateFiles()
{
return InternalEnumerateFiles("*", SearchOption.TopDirectoryOnly);
}
public IEnumerable<FileInfo> EnumerateFiles(string searchPattern)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
Contract.EndContractBlock();
return InternalEnumerateFiles(searchPattern, SearchOption.TopDirectoryOnly);
}
public IEnumerable<FileInfo> EnumerateFiles(string searchPattern, SearchOption searchOption)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum);
Contract.EndContractBlock();
return InternalEnumerateFiles(searchPattern, searchOption);
}
private IEnumerable<FileInfo> InternalEnumerateFiles(string searchPattern, SearchOption searchOption)
{
Debug.Assert(searchPattern != null);
Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
return (IEnumerable<FileInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Files);
}
public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos()
{
return InternalEnumerateFileSystemInfos("*", SearchOption.TopDirectoryOnly);
}
public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string searchPattern)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
Contract.EndContractBlock();
return InternalEnumerateFileSystemInfos(searchPattern, SearchOption.TopDirectoryOnly);
}
public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string searchPattern, SearchOption searchOption)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum);
Contract.EndContractBlock();
return InternalEnumerateFileSystemInfos(searchPattern, searchOption);
}
private IEnumerable<FileSystemInfo> InternalEnumerateFileSystemInfos(string searchPattern, SearchOption searchOption)
{
Debug.Assert(searchPattern != null);
Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
return FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Both);
}
// Returns the root portion of the given path. The resulting string
// consists of those rightmost characters of the path that constitute the
// root of the path. Possible patterns for the resulting string are: An
// empty string (a relative path on the current drive), "\" (an absolute
// path on the current drive), "X:" (a relative path on a given drive,
// where X is the drive letter), "X:\" (an absolute path on a given drive),
// and "\\server\share" (a UNC path for a given server and share name).
// The resulting string is null if path is null.
//
public DirectoryInfo Root
{
[System.Security.SecuritySafeCritical]
get
{
string rootPath = Path.GetPathRoot(FullPath);
return new DirectoryInfo(rootPath);
}
}
[System.Security.SecuritySafeCritical]
public void MoveTo(string destDirName)
{
if (destDirName == null)
throw new ArgumentNullException(nameof(destDirName));
if (destDirName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destDirName));
Contract.EndContractBlock();
string destination = Path.GetFullPath(destDirName);
string destinationWithSeparator = destination;
if (destinationWithSeparator[destinationWithSeparator.Length - 1] != Path.DirectorySeparatorChar)
destinationWithSeparator = destinationWithSeparator + PathHelpers.DirectorySeparatorCharAsString;
string fullSourcePath;
if (FullPath.Length > 0 && FullPath[FullPath.Length - 1] == Path.DirectorySeparatorChar)
fullSourcePath = FullPath;
else
fullSourcePath = FullPath + PathHelpers.DirectorySeparatorCharAsString;
StringComparison pathComparison = PathInternal.StringComparison;
if (string.Equals(fullSourcePath, destinationWithSeparator, pathComparison))
throw new IOException(SR.IO_SourceDestMustBeDifferent);
string sourceRoot = Path.GetPathRoot(fullSourcePath);
string destinationRoot = Path.GetPathRoot(destinationWithSeparator);
if (!string.Equals(sourceRoot, destinationRoot, pathComparison))
throw new IOException(SR.IO_SourceDestMustHaveSameRoot);
// Windows will throw if the source file/directory doesn't exist, we preemptively check
// to make sure our cross platform behavior matches NetFX behavior.
if (!Exists && !FileSystem.Current.FileExists(FullPath))
throw new DirectoryNotFoundException(SR.Format(SR.IO_PathNotFound_Path, FullPath));
if (FileSystem.Current.DirectoryExists(destinationWithSeparator))
throw new IOException(SR.Format(SR.IO_AlreadyExists_Name, destinationWithSeparator));
FileSystem.Current.MoveDirectory(FullPath, destination);
FullPath = destinationWithSeparator;
OriginalPath = destDirName;
DisplayPath = GetDisplayName(OriginalPath);
// Flush any cached information about the directory.
Invalidate();
}
[System.Security.SecuritySafeCritical]
public override void Delete()
{
FileSystem.Current.RemoveDirectory(FullPath, false);
}
[System.Security.SecuritySafeCritical]
public void Delete(bool recursive)
{
FileSystem.Current.RemoveDirectory(FullPath, recursive);
}
/// <summary>
/// Returns the original path. Use FullPath or Name properties for the path / directory name.
/// </summary>
public override string ToString()
{
return DisplayPath;
}
private static string GetDisplayName(string originalPath)
{
Debug.Assert(originalPath != null);
// Desktop documents that the path returned by ToString() should be the original path.
// For SL/Phone we only gave the directory name regardless of what was passed in.
return PathHelpers.ShouldReviseDirectoryPathToCurrent(originalPath) ?
"." :
originalPath;
}
private static string GetDirName(string fullPath)
{
Debug.Assert(fullPath != null);
return PathHelpers.IsRoot(fullPath) ?
fullPath :
Path.GetFileName(PathHelpers.TrimEndingDirectorySeparator(fullPath));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using NAudio;
using NAudio.Mixer;
using NAudio.Wave;
using SIL.Reporting;
namespace SIL.Media.Naudio
{
public class AudioRecorder : IAudioRecorder, IDisposable
{
protected readonly int _maxMinutes;
/// <summary>
/// This guy is always working, whether we're playing, recording, or just idle (monitoring)
/// </summary>
protected WaveIn _waveIn;
/// <summary>
/// This guy is disposed each time the client calls stop to stop recording and gets recreated
/// each time the client starts recording (i.e. using BeginRecording).
/// </summary>
private FileWriterThread _fileWriterThread;
protected UnsignedMixerControl _volumeControl;
protected double _microphoneLevel = -1;//unknown
protected RecordingState _recordingState = RecordingState.NotYetStarted;
protected WaveFormat _recordingFormat;
protected RecordingProgressEventArgs _recProgressEventArgs = new RecordingProgressEventArgs();
protected PeakLevelEventArgs _peakLevelEventArgs = new PeakLevelEventArgs();
protected double _prevRecordedTime;
public SampleAggregator SampleAggregator { get; protected set; }
private IRecordingDevice _selectedDevice;
public IRecordingDevice SelectedDevice
{
get
{
lock (this)
{
return _selectedDevice;
}
}
set
{
lock (this)
{
if (_selectedDevice == value)
return;
if (IsRecording)
throw new InvalidOperationException(
"Cannot switch recording devices while recording is in progress.");
if (_waveIn != null)
{
// Switch device after we have started monitoring, typically because the user plugged in a new one.
// The usual way to achieve this is to display a RecordingDeviceIndicator connected to this Recorder.
// See the implementation of RecordingDeviceIndicator.checkNewMicTimer_Tick.
CloseWaveIn();
}
_selectedDevice = value;
if (RecordingState != RecordingState.NotYetStarted && _selectedDevice != null)
BeginMonitoring();
if (SelectedDeviceChanged != null)
SelectedDeviceChanged(this, new EventArgs());
}
}
}
public event EventHandler SelectedDeviceChanged;
public TimeSpan RecordedTime { get; set; }
private int _bufferSize = -1;
private int _bufferCount = -1;
private bool _waveInBuffersChanged;
private DateTime _recordingStartTime;
private DateTime _recordingStopTime;
private int _bytesRecorded;
public event EventHandler<PeakLevelEventArgs> PeakLevelChanged;
public event EventHandler<RecordingProgressEventArgs> RecordingProgress;
public event EventHandler RecordingStarted;
/// <summary>Fired when the transition from recording to monitoring is complete</summary>
public event Action<IAudioRecorder, ErrorEventArgs> Stopped;
/// ------------------------------------------------------------------------------------
/// <summary>
///
/// </summary>
/// <param name="maxMinutes">REVIW: why does this max time even exist? I don't see that it affects buffer size</param>
/// ------------------------------------------------------------------------------------
public AudioRecorder(int maxMinutes)
{
_maxMinutes = maxMinutes;
SampleAggregator = new SampleAggregator();
SampleAggregator.MaximumCalculated += delegate
{
_peakLevelEventArgs.Level = SampleAggregator.maxValue;
if (PeakLevelChanged != null)
PeakLevelChanged.BeginInvoke(this, _peakLevelEventArgs, null, null);
};
RecordingFormat = new WaveFormat(44100, 1);
}
/// ------------------------------------------------------------------------------------
public virtual void Dispose()
{
lock (this)
{
if (_fileWriterThread != null)
_fileWriterThread.Stop();
CloseWaveIn();
RecordingState = RecordingState.NotYetStarted;
}
}
/// ------------------------------------------------------------------------------------
protected void AbortRecording()
{
RecordedTime = TimeSpan.Zero;
RecordingState = RecordingState.Monitoring;
_fileWriterThread.Abort();
if (Stopped != null)
Stopped(this, new ErrorEventArgs(new Exception("NAudio recording stopped unexpectedly")));
}
/// ------------------------------------------------------------------------------------
protected virtual void CloseWaveIn()
{
if (_waveIn != null)
{
try { _waveIn.StopRecording(); }
catch { /* It's amazing all the bizarre things that can go wrong */ }
_waveIn.DataAvailable -= waveIn_DataAvailable;
_waveIn.RecordingStopped -= OnRecordingStopped;
try { _waveIn.Dispose(); }
catch { /* It's amazing all the bizarre things that can go wrong */ }
_waveIn = null;
RecordingState = RecordingState.Stopped;
}
}
/// ------------------------------------------------------------------------------------
public virtual WaveFormat RecordingFormat
{
get { return _recordingFormat; }
set
{
_recordingFormat = value;
SampleAggregator.NotificationCount = value.SampleRate / 10;
}
}
/// ------------------------------------------------------------------------------------
public virtual void BeginMonitoring()
{
lock (this)
{
if (_waveIn != null || (_recordingState != RecordingState.NotYetStarted && _recordingState != RecordingState.Stopped))
throw new InvalidOperationException("only call this once for a new WaveIn device");
try
{
Debug.Assert(_waveIn == null);
_waveIn = new WaveIn();
InitializeWaveIn();
_waveIn.DataAvailable += waveIn_DataAvailable;
_waveIn.RecordingStopped += OnRecordingStopped;
_waveIn.WaveFormat = _recordingFormat;
try
{
_waveIn.StartRecording();
}
catch (MmException error)
{
if (error.Result != MmResult.AlreadyAllocated)
//TODO: I get this most of the time, but I don't know how to prevent it... maybe it's a hold over from previous runs? In which case, we need to make this disposable and stop the recording
throw;
}
ConnectWithVolumeControl();
RecordingState = RecordingState.Monitoring;
}
catch (Exception e)
{
CloseWaveIn();
ErrorReport.NotifyUserOfProblem(new ShowOncePerSessionBasedOnExactMessagePolicy(), e,
"There was a problem starting up volume monitoring.");
}
}
}
/// <summary>
/// As of NAudio 1.6, this can occur because something went wrong, for example, someone unplugged the microphone.
/// We won't get a DataAvailable notification, so make sure we aren't stuck in a state where we expect it.
/// Note that we can get this even when nothing but monitoring is happening.
/// </summary>
/// <param name="sender"></param>
/// <param name="eventArgs"></param>
private void OnRecordingStopped(object sender, StoppedEventArgs eventArgs)
{
lock (this)
{
if (RecordingState == RecordingState.Stopped || RecordingState == RecordingState.NotYetStarted)
return;
if (eventArgs.Exception != null)
{
// Something went wrong, typically the user unplugged the microphone.
// We are not going to get any more data until we BeginMonitoring again.
// So make sure we get into a state where that can be done.
if (_fileWriterThread != null)
AbortRecording();
CloseWaveIn();
}
}
}
/// ------------------------------------------------------------------------------------
protected virtual void InitializeWaveIn()
{
_waveIn.DeviceNumber = SelectedDevice.DeviceNumber;
if (_bufferCount > 0)
_waveIn.NumberOfBuffers = _bufferCount;
if (_bufferSize > 0)
_waveIn.BufferMilliseconds = _bufferSize;
_waveInBuffersChanged = false;
// Get the defaults (or previous values)
_bufferCount = _waveIn.NumberOfBuffers;
_bufferSize = _waveIn.BufferMilliseconds;
}
/// ------------------------------------------------------------------------------------
public int NumberOfBuffers
{
set
{
_bufferCount = value;
_waveInBuffersChanged = true;
}
}
/// ------------------------------------------------------------------------------------
public int BufferMilliseconds
{
set
{
_bufferSize = value;
_waveInBuffersChanged = true;
}
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// as far as naudio is concerned, we are still "recording" (i.e., accepting waveIn
/// data), but we want to stop writing the data to the file.
/// </summary>
/// ------------------------------------------------------------------------------------
protected virtual void TransitionFromRecordingToMonitoring()
{
RecordingState = RecordingState.Stopping;
_fileWriterThread.Stop();
RecordedTime = _fileWriterThread.RecordedTimeInSeconds;
_fileWriterThread = null;
RecordingState = RecordingState.Monitoring;
if (Stopped != null)
Stopped(this, null);
}
/// ------------------------------------------------------------------------------------
public virtual void BeginRecording(string waveFileName)
{
BeginRecording(waveFileName, false);
}
/// ------------------------------------------------------------------------------------
public virtual void BeginRecording(string waveFileName, bool appendToFile)
{
if (_recordingState == RecordingState.NotYetStarted)
BeginMonitoring();
if (_recordingState != RecordingState.Monitoring)
{
throw new InvalidOperationException("Can't begin recording while we are in this state: " + _recordingState.ToString());
}
lock (this)
{
if (_waveInBuffersChanged)
{
CloseWaveIn();
BeginMonitoring();
}
_bytesRecorded = 0;
WaveFileWriter writer;
if (!File.Exists(waveFileName) || !appendToFile)
writer = new WaveFileWriter(waveFileName, _recordingFormat);
else
{
var buffer = GetAudioBufferToAppendTo(waveFileName);
writer = new WaveFileWriter(waveFileName, _recordingFormat);
writer.Write(buffer, 0, buffer.Length);
}
_fileWriterThread = new FileWriterThread(writer);
_recordingStartTime = DateTime.Now;
_prevRecordedTime = 0d;
RecordingState = RecordingState.Recording;
}
if (RecordingStarted != null)
RecordingStarted(this, EventArgs.Empty);
}
/// ------------------------------------------------------------------------------------
protected virtual byte[] GetAudioBufferToAppendTo(string waveFileName)
{
using (var stream = new WaveFileReader(waveFileName))
{
var buffer = new byte[stream.Length];
var count = (int)Math.Min(stream.Length, int.MaxValue);
int offset = 0;
while (stream.Read(buffer, offset, count) > 0)
offset += count;
stream.Close();
return buffer;
}
}
/// ------------------------------------------------------------------------------------
public virtual void Stop()
{
lock (this)
{
if (_recordingState == RecordingState.Recording)
{
_recordingStopTime = DateTime.Now;
RecordingState = RecordingState.RequestedStop;
Debug.WriteLine("Setting RequestedStop");
// Don't stop because we'll lose any buffer(s) that have not been processed.
// Then when we re-start, NAudio can crash because the buffers for which it has
// queued messages will be disposed
// _waveIn.StopRecording();
}
}
}
/// ------------------------------------------------------------------------------------
private IEnumerable<MixerControl> MixerLineControls
{
get
{
int attempts = 0;
while (attempts++ < 2)
{
try
{
if (Environment.OSVersion.Version.Major >= 6) // Vista and over
{
var mixerLine = _waveIn.GetMixerLine();
//new MixerLine((IntPtr)waveInDeviceNumber, 0, MixerFlags.WaveIn);
return mixerLine.Controls;
}
int waveInDeviceNumber = _waveIn.DeviceNumber;
var mixer = new Mixer(waveInDeviceNumber);
foreach (var source in from destination in mixer.Destinations
where destination.ComponentType == MixerLineComponentType.DestinationWaveIn
from source in destination.Sources
where source.ComponentType == MixerLineComponentType.SourceMicrophone
select source)
return source.Controls;
}
catch (MmException e)
{
Logger.WriteEvent("MmException caught: {0}", e.Message);
if (attempts > 2)
throw;
}
Thread.Sleep(50); // User might have been making changes in Control Panel that messed us up. Let's see if the problem fixes itself.
}
return new MixerControl[0];
}
}
/// ------------------------------------------------------------------------------------
protected virtual void ConnectWithVolumeControl()
{
foreach (var control in MixerLineControls)
{
if (control.ControlType == MixerControlType.Volume)
{
_volumeControl = control as UnsignedMixerControl;
//REVIEW: was this (from original author). This would boost us to the max (as the original code had a 100 for _microphoneLevel)
//MicrophoneLevel = _microphoneLevel;
//Now, we do the opposite. Give preference to the system volume. If your application supports independent volume setting, that's
//fine, but you'll have to explicity set it via the MicrophoneLevel property.
_microphoneLevel = _volumeControl.Percent;
break;
}
}
}
/// ------------------------------------------------------------------------------------
public virtual double MicrophoneLevel
{
get { return _microphoneLevel; }
set
{
_microphoneLevel = value;
if (_volumeControl == null)
ConnectWithVolumeControl();
if (_volumeControl != null) //did we get it?
_volumeControl.Percent = value;
}
}
/// ------------------------------------------------------------------------------------
public virtual bool IsRecording
{
get
{
lock (this)
{
return _recordingState == RecordingState.Recording ||
_recordingState == RecordingState.RequestedStop ||
_recordingState == RecordingState.Stopping;
}
}
}
/// ------------------------------------------------------------------------------------
public virtual RecordingState RecordingState
{
get
{
lock (this)
{
return _recordingState;
}
}
protected set
{
lock (this)
{
_recordingState = value;
Debug.WriteLine("recorder state--> " + value.ToString());
}
}
}
/// ------------------------------------------------------------------------------------
protected virtual void waveIn_DataAvailable(object sender, WaveInEventArgs e)
{
/*original from codeplex
byte[] buffer = e.Buffer;
int bytesRecorded = e.BytesRecorded;
WriteToFile(buffer, bytesRecorded);
for (int index = 0; index < e.BytesRecorded; index += 2)
{
short sample = (short)((buffer[index + 1] << 8) |
buffer[index + 0]);
float sample32 = sample / 32768f;
_sampleAggregator.Add(sample32);
}
*/
//David's version:
lock (this)
{
var buffer = e.Buffer;
int bytesRecorded = e.BytesRecorded;
bool hitMaximumFileSize = false;
if (_recordingState == RecordingState.Recording || _recordingState == RecordingState.RequestedStop)
{
Debug.WriteLine("Writing " + bytesRecorded + " bytes of data to file");
hitMaximumFileSize = !WriteToFile(buffer, bytesRecorded);
}
var bytesPerSample = _waveIn.WaveFormat.BitsPerSample / 8;
// It appears the data only occupies 2 bytes of those in a sample and that
// those 2 are always the last two in each sample. The other bytes are zero
// filled. Therefore, when getting those two bytes, the first index into a
// sample needs to be 0 for 16 bit samples, 1 for 24 bit samples and 2 for
// 32 bit samples. I'm not sure what to do for 8 bit samples. I could never
// figure out the correct conversion of a byte in an 8 bit per sample buffer
// to a float sample value. However, I doubt folks are going to be recording
// at 8 bits/sample so I'm ignoring that problem.
for (var index = bytesPerSample - 2; index < bytesRecorded - 1; index += bytesPerSample)
{
var sample = (short)((buffer[index + 1] << 8) | buffer[index]);
var sample32 = sample / 32768f;
SampleAggregator.Add(sample32);
}
if (_fileWriterThread == null)
return;
// Only fire the progress event every 10th of a second.
var currRecordedTime = (double)_bytesRecorded / _recordingFormat.AverageBytesPerSecond;
if (currRecordedTime - _prevRecordedTime >= 0.05d)
{
_prevRecordedTime = currRecordedTime;
_recProgressEventArgs.RecordedLength = TimeSpan.FromSeconds(currRecordedTime);
if (RecordingProgress != null)
RecordingProgress.BeginInvoke(this, _recProgressEventArgs, null, null);
}
if (RecordingState == RecordingState.RequestedStop)
{
if (DateTime.Now > _recordingStopTime.AddSeconds(2) || hitMaximumFileSize ||
_recordingStartTime.AddSeconds(currRecordedTime) >= _recordingStopTime)
{
Debug.WriteLine("Transition to monitoring from DataAvailable");
TransitionFromRecordingToMonitoring();
}
}
}
}
/// ------------------------------------------------------------------------------------
private bool WriteToFile(byte[] buffer, int bytesRecorded)
{
if (_bytesRecorded < _recordingFormat.AverageBytesPerSecond * 60 * _maxMinutes)
{
_bytesRecorded += buffer.Length;
_fileWriterThread.AddData(buffer, bytesRecorded);
return true;
}
Stop();
return false;
}
/// <summary>
/// Given a wav file, produce a different wav file with the given start and stop times
/// </summary>
/// <remarks>This is in this file because ideally it should be part of the recorder...
/// the use case at the moment is trimming off the last 200ms or so in order to remove
/// the sound of the click that ends the recording. That "amount to trim off the end"
/// would be a natural parameter
/// to add to the recording, perhaps under user-settings control. But doing that is
/// beyond the time I have to give to this now, so I'm at least positioning this code
/// in this library rather than in my app, as a first step. I call it when the AudioRecorder
/// raises the Stopped event.</remarks>
/// <param name="inPath"></param>
/// <param name="outPath"></param>
/// <param name="cutFromStart"></param>
/// <param name="cutFromEnd"></param>
/// <param name="minimumDesiredDuration">The start and end cuts will be reduced if the result would be less than this. Start has priority.</param>
public static void TrimWavFile(string inPath, string outPath, TimeSpan cutFromStart, TimeSpan cutFromEnd, TimeSpan minimumDesiredDuration)
{
using (var reader = new WaveFileReader(inPath))
{
long totalMilliseconds = 1000*reader.Length/reader.WaveFormat.AverageBytesPerSecond;
//we can't trim more than we have, and more than the stated minimum size
var cutFromStartMilliseconds = (long)Math.Min(totalMilliseconds - minimumDesiredDuration.TotalMilliseconds, cutFromStart.TotalMilliseconds);
cutFromStartMilliseconds = (long) Math.Max(0, cutFromStartMilliseconds); // has to be 0 or positive
totalMilliseconds -= cutFromStartMilliseconds;
var cutFromEndMilliseconds = (long)Math.Min(totalMilliseconds - minimumDesiredDuration.TotalMilliseconds, cutFromEnd.TotalMilliseconds);
cutFromEndMilliseconds = (long)Math.Max(0, cutFromEndMilliseconds); // has to be 0 or positive
//from https://stackoverflow.com/a/6488629/723299
using (var writer = new WaveFileWriter(outPath, reader.WaveFormat))
{
var bytesPerMillisecond = reader.WaveFormat.AverageBytesPerSecond / 1000;
var startPos = cutFromStartMilliseconds * bytesPerMillisecond;
startPos = startPos - startPos % reader.WaveFormat.BlockAlign;
var endBytes = cutFromEndMilliseconds * bytesPerMillisecond;
endBytes = endBytes - endBytes % reader.WaveFormat.BlockAlign;
var endPos = reader.Length - endBytes;
TrimWavFileInternal(reader, writer, startPos, endPos);
}
}
}
private static void TrimWavFileInternal(WaveFileReader reader, WaveFileWriter writer, long startPos, long endPos)
{
//from https://stackoverflow.com/a/6488629/723299, added the break if we aren't getting any more data
reader.Position = startPos;
var buffer = new byte[1024];
while (reader.Position < endPos)
{
var bytesRequired = (int)(endPos - reader.Position);
if (bytesRequired > 0)
{
var bytesToRead = Math.Min(bytesRequired, buffer.Length);
var bytesRead = reader.Read(buffer, 0, bytesToRead);
if (bytesRead > 0)
{
writer.Write(buffer, 0, bytesRead);
}
else
{
//assumption here is that we tried to trim more than the whole file has
break;
}
}
}
}
}
}
| |
// Copyright (C) 2015-2021 The Neo Project.
//
// The neo is free software distributed under the MIT software license,
// see the accompanying file LICENSE in the main directory of the
// project or http://www.opensource.org/licenses/mit-license.php
// for more details.
//
// Redistribution and use in source and binary forms with or without
// modifications are permitted.
using System;
using System.Numerics;
namespace Neo
{
/// <summary>
/// Represents a fixed-point number of arbitrary precision.
/// </summary>
public struct BigDecimal : IComparable<BigDecimal>, IEquatable<BigDecimal>
{
private readonly BigInteger value;
private readonly byte decimals;
/// <summary>
/// The <see cref="BigInteger"/> value of the number.
/// </summary>
public BigInteger Value => value;
/// <summary>
/// The number of decimal places for this number.
/// </summary>
public byte Decimals => decimals;
/// <summary>
/// The sign of the number.
/// </summary>
public int Sign => value.Sign;
/// <summary>
/// Initializes a new instance of the <see cref="BigDecimal"/> struct.
/// </summary>
/// <param name="value">The <see cref="BigInteger"/> value of the number.</param>
/// <param name="decimals">The number of decimal places for this number.</param>
public BigDecimal(BigInteger value, byte decimals)
{
this.value = value;
this.decimals = decimals;
}
/// <summary>
/// Initializes a new instance of the <see cref="BigDecimal"/> struct with the value of <see cref="decimal"/>.
/// </summary>
/// <param name="value">The value of the number.</param>
public unsafe BigDecimal(decimal value)
{
Span<int> span = stackalloc int[4];
decimal.GetBits(value, span);
fixed (int* p = span)
{
ReadOnlySpan<byte> buffer = new(p, 16);
this.value = new BigInteger(buffer[..12], isUnsigned: true);
if (buffer[15] != 0) this.value = -this.value;
this.decimals = buffer[14];
}
}
/// <summary>
/// Initializes a new instance of the <see cref="BigDecimal"/> struct with the value of <see cref="decimal"/>.
/// </summary>
/// <param name="value">The value of the number.</param>
/// <param name="decimals">The number of decimal places for this number.</param>
public unsafe BigDecimal(decimal value, byte decimals)
{
Span<int> span = stackalloc int[4];
decimal.GetBits(value, span);
fixed (int* p = span)
{
ReadOnlySpan<byte> buffer = new(p, 16);
this.value = new BigInteger(buffer[..12], isUnsigned: true);
if (buffer[14] > decimals)
throw new ArgumentException(null, nameof(value));
else if (buffer[14] < decimals)
this.value *= BigInteger.Pow(10, decimals - buffer[14]);
if (buffer[15] != 0)
this.value = -this.value;
}
this.decimals = decimals;
}
/// <summary>
/// Changes the decimals of the <see cref="BigDecimal"/>.
/// </summary>
/// <param name="decimals">The new decimals field.</param>
/// <returns>The <see cref="BigDecimal"/> that has the new number of decimal places.</returns>
public BigDecimal ChangeDecimals(byte decimals)
{
if (this.decimals == decimals) return this;
BigInteger value;
if (this.decimals < decimals)
{
value = this.value * BigInteger.Pow(10, decimals - this.decimals);
}
else
{
BigInteger divisor = BigInteger.Pow(10, this.decimals - decimals);
value = BigInteger.DivRem(this.value, divisor, out BigInteger remainder);
if (remainder > BigInteger.Zero)
throw new ArgumentOutOfRangeException(nameof(decimals));
}
return new BigDecimal(value, decimals);
}
/// <summary>
/// Parses a <see cref="BigDecimal"/> from the specified <see cref="string"/>.
/// </summary>
/// <param name="s">A number represented by a <see cref="string"/>.</param>
/// <param name="decimals">The number of decimal places for this number.</param>
/// <returns>The parsed <see cref="BigDecimal"/>.</returns>
/// <exception cref="FormatException"><paramref name="s"/> is not in the correct format.</exception>
public static BigDecimal Parse(string s, byte decimals)
{
if (!TryParse(s, decimals, out BigDecimal result))
throw new FormatException();
return result;
}
/// <summary>
/// Gets a <see cref="string"/> representing the number.
/// </summary>
/// <returns>The <see cref="string"/> representing the number.</returns>
public override string ToString()
{
BigInteger divisor = BigInteger.Pow(10, decimals);
BigInteger result = BigInteger.DivRem(value, divisor, out BigInteger remainder);
if (remainder == 0) return result.ToString();
return $"{result}.{remainder.ToString("d" + decimals)}".TrimEnd('0');
}
/// <summary>
/// Parses a <see cref="BigDecimal"/> from the specified <see cref="string"/>.
/// </summary>
/// <param name="s">A number represented by a <see cref="string"/>.</param>
/// <param name="decimals">The number of decimal places for this number.</param>
/// <param name="result">The parsed <see cref="BigDecimal"/>.</param>
/// <returns><see langword="true"/> if a number is successfully parsed; otherwise, <see langword="false"/>.</returns>
public static bool TryParse(string s, byte decimals, out BigDecimal result)
{
int e = 0;
int index = s.IndexOfAny(new[] { 'e', 'E' });
if (index >= 0)
{
if (!sbyte.TryParse(s[(index + 1)..], out sbyte e_temp))
{
result = default;
return false;
}
e = e_temp;
s = s.Substring(0, index);
}
index = s.IndexOf('.');
if (index >= 0)
{
s = s.TrimEnd('0');
e -= s.Length - index - 1;
s = s.Remove(index, 1);
}
int ds = e + decimals;
if (ds < 0)
{
result = default;
return false;
}
if (ds > 0)
s += new string('0', ds);
if (!BigInteger.TryParse(s, out BigInteger value))
{
result = default;
return false;
}
result = new BigDecimal(value, decimals);
return true;
}
public int CompareTo(BigDecimal other)
{
BigInteger left = value, right = other.value;
if (decimals < other.decimals)
left *= BigInteger.Pow(10, other.decimals - decimals);
else if (decimals > other.decimals)
right *= BigInteger.Pow(10, decimals - other.decimals);
return left.CompareTo(right);
}
public override bool Equals(object obj)
{
if (obj is not BigDecimal @decimal) return false;
return Equals(@decimal);
}
public bool Equals(BigDecimal other)
{
return CompareTo(other) == 0;
}
public override int GetHashCode()
{
BigInteger divisor = BigInteger.Pow(10, decimals);
BigInteger result = BigInteger.DivRem(value, divisor, out BigInteger remainder);
return HashCode.Combine(result, remainder);
}
public static bool operator ==(BigDecimal left, BigDecimal right)
{
return left.CompareTo(right) == 0;
}
public static bool operator !=(BigDecimal left, BigDecimal right)
{
return left.CompareTo(right) != 0;
}
public static bool operator <(BigDecimal left, BigDecimal right)
{
return left.CompareTo(right) < 0;
}
public static bool operator <=(BigDecimal left, BigDecimal right)
{
return left.CompareTo(right) <= 0;
}
public static bool operator >(BigDecimal left, BigDecimal right)
{
return left.CompareTo(right) > 0;
}
public static bool operator >=(BigDecimal left, BigDecimal right)
{
return left.CompareTo(right) >= 0;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Drawing.Drawing2D;
using System.Globalization;
using System.IO;
namespace System.Drawing.Imaging
{
// sdkinc\GDIplusImageAttributes.h
// There are 5 possible sets of color adjustments:
// ColorAdjustDefault,
// ColorAdjustBitmap,
// ColorAdjustBrush,
// ColorAdjustPen,
// ColorAdjustText,
// Bitmaps, Brushes, Pens, and Text will all use any color adjustments
// that have been set into the default ImageAttributes until their own
// color adjustments have been set. So as soon as any "Set" method is
// called for Bitmaps, Brushes, Pens, or Text, then they start from
// scratch with only the color adjustments that have been set for them.
// Calling Reset removes any individual color adjustments for a type
// and makes it revert back to using all the default color adjustments
// (if any). The SetToIdentity method is a way to force a type to
// have no color adjustments at all, regardless of what previous adjustments
// have been set for the defaults or for that type.
/// <summary>
/// Contains information about how image colors are manipulated during rendering.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public sealed class ImageAttributes : ICloneable, IDisposable
{
#if FINALIZATION_WATCH
private string allocationSite = Graphics.GetAllocationStack();
#endif
internal IntPtr nativeImageAttributes;
internal void SetNativeImageAttributes(IntPtr handle)
{
if (handle == IntPtr.Zero)
throw new ArgumentNullException("handle");
nativeImageAttributes = handle;
}
/// <summary>
/// Initializes a new instance of the <see cref='ImageAttributes'/> class.
/// </summary>
public ImageAttributes()
{
IntPtr newImageAttributes = IntPtr.Zero;
int status = SafeNativeMethods.Gdip.GdipCreateImageAttributes(out newImageAttributes);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
SetNativeImageAttributes(newImageAttributes);
}
internal ImageAttributes(IntPtr newNativeImageAttributes)
{
SetNativeImageAttributes(newNativeImageAttributes);
}
/// <summary>
/// Cleans up Windows resources for this <see cref='ImageAttributes'/>.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
#if FINALIZATION_WATCH
if (!disposing && nativeImageAttributes != IntPtr.Zero)
Debug.WriteLine("**********************\nDisposed through finalization:\n" + allocationSite);
#endif
if (nativeImageAttributes != IntPtr.Zero)
{
try
{
#if DEBUG
int status =
#endif
SafeNativeMethods.Gdip.GdipDisposeImageAttributes(new HandleRef(this, nativeImageAttributes));
#if DEBUG
Debug.Assert(status == SafeNativeMethods.Gdip.Ok, "GDI+ returned an error status: " + status.ToString(CultureInfo.InvariantCulture));
#endif
}
catch (Exception ex)
{
if (ClientUtils.IsSecurityOrCriticalException(ex))
{
throw;
}
Debug.Fail("Exception thrown during Dispose: " + ex.ToString());
}
finally
{
nativeImageAttributes = IntPtr.Zero;
}
}
}
/// <summary>
/// Cleans up Windows resources for this <see cref='ImageAttributes'/>.
/// </summary>
~ImageAttributes()
{
Dispose(false);
}
/// <summary>
/// Creates an exact copy of this <see cref='ImageAttributes'/>.
/// </summary>
public object Clone()
{
IntPtr clone = IntPtr.Zero;
int status = SafeNativeMethods.Gdip.GdipCloneImageAttributes(
new HandleRef(this, nativeImageAttributes),
out clone);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return new ImageAttributes(clone);
}
/// <summary>
/// Sets the 5 X 5 color adjust matrix to the specified <see cref='Matrix'/>.
/// </summary>
public void SetColorMatrix(ColorMatrix newColorMatrix)
{
SetColorMatrix(newColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Default);
}
/// <summary>
/// Sets the 5 X 5 color adjust matrix to the specified 'Matrix' with the specified 'ColorMatrixFlags'.
/// </summary>
public void SetColorMatrix(ColorMatrix newColorMatrix, ColorMatrixFlag flags)
{
SetColorMatrix(newColorMatrix, flags, ColorAdjustType.Default);
}
/// <summary>
/// Sets the 5 X 5 color adjust matrix to the specified 'Matrix' with the specified 'ColorMatrixFlags'.
/// </summary>
public void SetColorMatrix(ColorMatrix newColorMatrix, ColorMatrixFlag mode, ColorAdjustType type)
{
int status = SafeNativeMethods.Gdip.GdipSetImageAttributesColorMatrix(
new HandleRef(this, nativeImageAttributes),
type,
true,
newColorMatrix,
null,
mode);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
/// <summary>
/// Clears the color adjust matrix to all zeroes.
/// </summary>
public void ClearColorMatrix()
{
ClearColorMatrix(ColorAdjustType.Default);
}
/// <summary>
/// Clears the color adjust matrix.
/// </summary>
public void ClearColorMatrix(ColorAdjustType type)
{
int status = SafeNativeMethods.Gdip.GdipSetImageAttributesColorMatrix(
new HandleRef(this, nativeImageAttributes),
type,
false,
null,
null,
ColorMatrixFlag.Default);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
/// <summary>
/// Sets a color adjust matrix for image colors and a separate gray scale adjust matrix for gray scale values.
/// </summary>
public void SetColorMatrices(ColorMatrix newColorMatrix, ColorMatrix grayMatrix)
{
SetColorMatrices(newColorMatrix, grayMatrix, ColorMatrixFlag.Default, ColorAdjustType.Default);
}
public void SetColorMatrices(ColorMatrix newColorMatrix, ColorMatrix grayMatrix, ColorMatrixFlag flags)
{
SetColorMatrices(newColorMatrix, grayMatrix, flags, ColorAdjustType.Default);
}
public void SetColorMatrices(ColorMatrix newColorMatrix, ColorMatrix grayMatrix, ColorMatrixFlag mode,
ColorAdjustType type)
{
int status = SafeNativeMethods.Gdip.GdipSetImageAttributesColorMatrix(
new HandleRef(this, nativeImageAttributes),
type,
true,
newColorMatrix,
grayMatrix,
mode);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
public void SetThreshold(float threshold)
{
SetThreshold(threshold, ColorAdjustType.Default);
}
public void SetThreshold(float threshold, ColorAdjustType type)
{
int status = SafeNativeMethods.Gdip.GdipSetImageAttributesThreshold(
new HandleRef(this, nativeImageAttributes),
type,
true,
threshold);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
public void ClearThreshold()
{
ClearThreshold(ColorAdjustType.Default);
}
public void ClearThreshold(ColorAdjustType type)
{
int status = SafeNativeMethods.Gdip.GdipSetImageAttributesThreshold(
new HandleRef(this, nativeImageAttributes),
type,
false,
0.0f);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
public void SetGamma(float gamma)
{
SetGamma(gamma, ColorAdjustType.Default);
}
public void SetGamma(float gamma, ColorAdjustType type)
{
int status = SafeNativeMethods.Gdip.GdipSetImageAttributesGamma(
new HandleRef(this, nativeImageAttributes),
type,
true,
gamma);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
public void ClearGamma()
{
ClearGamma(ColorAdjustType.Default);
}
public void ClearGamma(ColorAdjustType type)
{
int status = SafeNativeMethods.Gdip.GdipSetImageAttributesGamma(
new HandleRef(this, nativeImageAttributes),
type,
false,
0.0f);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
public void SetNoOp()
{
SetNoOp(ColorAdjustType.Default);
}
public void SetNoOp(ColorAdjustType type)
{
int status = SafeNativeMethods.Gdip.GdipSetImageAttributesNoOp(
new HandleRef(this, nativeImageAttributes),
type,
true);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
public void ClearNoOp()
{
ClearNoOp(ColorAdjustType.Default);
}
public void ClearNoOp(ColorAdjustType type)
{
int status = SafeNativeMethods.Gdip.GdipSetImageAttributesNoOp(
new HandleRef(this, nativeImageAttributes),
type,
false);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
public void SetColorKey(Color colorLow, Color colorHigh)
{
SetColorKey(colorLow, colorHigh, ColorAdjustType.Default);
}
public void SetColorKey(Color colorLow, Color colorHigh, ColorAdjustType type)
{
int lowInt = colorLow.ToArgb();
int highInt = colorHigh.ToArgb();
int status = SafeNativeMethods.Gdip.GdipSetImageAttributesColorKeys(
new HandleRef(this, nativeImageAttributes),
type,
true,
lowInt,
highInt);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
public void ClearColorKey()
{
ClearColorKey(ColorAdjustType.Default);
}
public void ClearColorKey(ColorAdjustType type)
{
int zero = 0;
int status = SafeNativeMethods.Gdip.GdipSetImageAttributesColorKeys(
new HandleRef(this, nativeImageAttributes),
type,
false,
zero,
zero);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
public void SetOutputChannel(ColorChannelFlag flags)
{
SetOutputChannel(flags, ColorAdjustType.Default);
}
public void SetOutputChannel(ColorChannelFlag flags, ColorAdjustType type)
{
int status = SafeNativeMethods.Gdip.GdipSetImageAttributesOutputChannel(
new HandleRef(this, nativeImageAttributes),
type,
true,
flags);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
public void ClearOutputChannel()
{
ClearOutputChannel(ColorAdjustType.Default);
}
public void ClearOutputChannel(ColorAdjustType type)
{
int status = SafeNativeMethods.Gdip.GdipSetImageAttributesOutputChannel(
new HandleRef(this, nativeImageAttributes),
type,
false,
ColorChannelFlag.ColorChannelLast);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
public void SetOutputChannelColorProfile(String colorProfileFilename)
{
SetOutputChannelColorProfile(colorProfileFilename, ColorAdjustType.Default);
}
public void SetOutputChannelColorProfile(String colorProfileFilename,
ColorAdjustType type)
{
// Called in order to emulate exception behavior from netfx related to invalid file paths.
Path.GetFullPath(colorProfileFilename);
int status = SafeNativeMethods.Gdip.GdipSetImageAttributesOutputChannelColorProfile(
new HandleRef(this, nativeImageAttributes),
type,
true,
colorProfileFilename);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
public void ClearOutputChannelColorProfile()
{
ClearOutputChannel(ColorAdjustType.Default);
}
public void ClearOutputChannelColorProfile(ColorAdjustType type)
{
int status = SafeNativeMethods.Gdip.GdipSetImageAttributesOutputChannel(
new HandleRef(this, nativeImageAttributes),
type,
false,
ColorChannelFlag.ColorChannelLast);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
public void SetRemapTable(ColorMap[] map)
{
SetRemapTable(map, ColorAdjustType.Default);
}
public void SetRemapTable(ColorMap[] map, ColorAdjustType type)
{
int index = 0;
int mapSize = map.Length;
int size = 4; // Marshal.SizeOf(index.GetType());
IntPtr memory = Marshal.AllocHGlobal(checked(mapSize * size * 2));
try
{
for (index = 0; index < mapSize; index++)
{
Marshal.StructureToPtr(map[index].OldColor.ToArgb(), (IntPtr)((long)memory + index * size * 2), false);
Marshal.StructureToPtr(map[index].NewColor.ToArgb(), (IntPtr)((long)memory + index * size * 2 + size), false);
}
int status = SafeNativeMethods.Gdip.GdipSetImageAttributesRemapTable(
new HandleRef(this, nativeImageAttributes),
type,
true,
mapSize,
new HandleRef(null, memory));
if (status != SafeNativeMethods.Gdip.Ok)
{
throw SafeNativeMethods.Gdip.StatusException(status);
}
}
finally
{
Marshal.FreeHGlobal(memory);
}
}
public void ClearRemapTable()
{
ClearRemapTable(ColorAdjustType.Default);
}
public void ClearRemapTable(ColorAdjustType type)
{
int status = SafeNativeMethods.Gdip.GdipSetImageAttributesRemapTable(
new HandleRef(this, nativeImageAttributes),
type,
false,
0,
NativeMethods.NullHandleRef);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
public void SetBrushRemapTable(ColorMap[] map)
{
SetRemapTable(map, ColorAdjustType.Brush);
}
public void ClearBrushRemapTable()
{
ClearRemapTable(ColorAdjustType.Brush);
}
public void SetWrapMode(WrapMode mode)
{
SetWrapMode(mode, new Color(), false);
}
public void SetWrapMode(WrapMode mode, Color color)
{
SetWrapMode(mode, color, false);
}
public void SetWrapMode(WrapMode mode, Color color, bool clamp)
{
int status = SafeNativeMethods.Gdip.GdipSetImageAttributesWrapMode(
new HandleRef(this, nativeImageAttributes),
unchecked((int)mode),
color.ToArgb(),
clamp);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
public void GetAdjustedPalette(ColorPalette palette, ColorAdjustType type)
{
// does inplace adjustment
IntPtr memory = palette.ConvertToMemory();
try
{
int status = SafeNativeMethods.Gdip.GdipGetImageAttributesAdjustedPalette(
new HandleRef(this, nativeImageAttributes), new HandleRef(null, memory), type);
if (status != SafeNativeMethods.Gdip.Ok)
{
throw SafeNativeMethods.Gdip.StatusException(status);
}
palette.ConvertFromMemory(memory);
}
finally
{
if (memory != IntPtr.Zero)
{
Marshal.FreeHGlobal(memory);
}
}
}
}
}
| |
// 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.Runtime.InteropServices;
using EnvDTE;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.Mocks;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests.CodeModel
{
public class FileCodeFunctionTests : AbstractFileCodeElementTests
{
public FileCodeFunctionTests()
: base(@"using System;
public class A
{
public A()
{
}
~A()
{
}
public static A operator +(A a1, A a2)
{
return a1;
}
private int MethodA()
{
return 1;
}
protected virtual string MethodB(int intA)
{
return intA.ToString();
}
internal static bool MethodC(int intA, bool boolB)
{
return boolB;
}
public float MethodD(int intA, bool boolB, string stringC)
{
return 1.5f;
}
void MethodE()
{
}
void MethodE(int intA)
{
}
void MethodWithBlankLine()
{
}
}
public class B : A
{
protected override string MethodB(int intA)
{
return ""Override!"";
}
}
public abstract class C
{
/// <summary>
/// A short summary.
/// </summary>
/// <param name=""intA"">A parameter.</param>
/// <returns>An int.</returns>
public abstract int MethodA(int intA);
// This is a short comment.
public abstract int MethodB(string foo);
dynamic DynamicField;
dynamic DynamicMethod(dynamic foo = 5);
}
public class Entity { }
public class Ref<T> where T : Entity
{
public static implicit operator Ref<T>(T entity)
{
return new Ref<T>(entity);
}
}
")
{
}
private CodeFunction GetCodeFunction(params object[] path)
{
return (CodeFunction)GetCodeElement(path);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void CanOverride_False()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
Assert.False(testObject.CanOverride);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void CanOverride_True()
{
CodeFunction testObject = GetCodeFunction("A", "MethodB");
Assert.True(testObject.CanOverride);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void FullName()
{
CodeFunction testObject = GetCodeFunction("A", "MethodD");
Assert.Equal("A.MethodD", testObject.FullName);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void FunctionKind_Function()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
Assert.Equal(vsCMFunction.vsCMFunctionFunction, testObject.FunctionKind);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void FunctionKind_Constructor()
{
CodeFunction testObject = GetCodeFunction("A", 1);
Assert.Equal(vsCMFunction.vsCMFunctionConstructor, testObject.FunctionKind);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void FunctionKind_Finalizer()
{
CodeFunction testObject = GetCodeFunction("A", 2);
Assert.Equal(vsCMFunction.vsCMFunctionDestructor, testObject.FunctionKind);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void IsOverloaded_True()
{
CodeFunction testObject = GetCodeFunction("A", "MethodE");
Assert.True(testObject.IsOverloaded);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void IsOverloaded_False()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
Assert.False(testObject.IsOverloaded);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void IsShared_False()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
Assert.False(testObject.IsShared);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void IsShared_True()
{
CodeFunction testObject = GetCodeFunction("A", "MethodC");
Assert.True(testObject.IsShared);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Kind()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
Assert.Equal(vsCMElement.vsCMElementFunction, testObject.Kind);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Name()
{
CodeFunction testObject = GetCodeFunction("A", "MethodC");
Assert.Equal("MethodC", testObject.Name);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Parameters_Count()
{
CodeFunction testObject = GetCodeFunction("A", "MethodD");
Assert.Equal(3, testObject.Parameters.Count);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Parent()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
Assert.NotNull(testObject.Parent);
Assert.True(testObject.Parent is CodeClass, testObject.Parent.GetType().ToString());
Assert.Equal("A", ((CodeClass)testObject.Parent).FullName);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Type()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
Assert.Equal("System.Int32", testObject.Type.AsFullName);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Comment()
{
CodeFunction testObject = GetCodeFunction("C", "MethodB");
string expected = "This is a short comment.\r\n";
Assert.Equal(expected, testObject.Comment);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void DocComment()
{
CodeFunction testObject = GetCodeFunction("C", "MethodA");
string expected = "<doc>\r\n<summary>\r\nA short summary.\r\n</summary>\r\n<param name=\"intA\">A parameter.</param>\r\n<returns>An int.</returns>\r\n</doc>";
Assert.Equal(expected, testObject.DocComment);
}
[ConditionalFact(typeof(x86), Skip = "636860")]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Overloads_Count()
{
CodeFunction testObject = GetCodeFunction("A", "MethodE");
Assert.Equal(2, testObject.Overloads.Count);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Attributes()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
AssertEx.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartAttributes));
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_AttributesWithDelimiter()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
AssertEx.Throws<COMException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartAttributesWithDelimiter));
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Body()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
TextPoint startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartBody);
Assert.Equal(20, startPoint.Line);
Assert.Equal(1, startPoint.LineCharOffset);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_BodyWithDelimiter()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
AssertEx.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartBodyWithDelimiter));
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Header()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
TextPoint startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartHeader);
Assert.Equal(18, startPoint.Line);
Assert.Equal(5, startPoint.LineCharOffset);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_HeaderWithAttributes()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
AssertEx.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartHeaderWithAttributes));
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Name()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
AssertEx.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartName));
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Navigate()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
TextPoint startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartNavigate);
Assert.Equal(20, startPoint.Line);
Assert.Equal(9, startPoint.LineCharOffset);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_NavigateWithBlankLine()
{
CodeFunction testObject = GetCodeFunction("A", "MethodWithBlankLine");
TextPoint startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartNavigate);
Assert.Equal(48, startPoint.Line);
Assert.Equal(9, startPoint.LineCharOffset);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Whole()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
AssertEx.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartWhole));
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_WholeWithAttributes()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
TextPoint startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartWholeWithAttributes);
Assert.Equal(18, startPoint.Line);
Assert.Equal(5, startPoint.LineCharOffset);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Attributes()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
AssertEx.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartAttributes));
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_AttributesWithDelimiter()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
AssertEx.Throws<COMException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartAttributesWithDelimiter));
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Body()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
TextPoint endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartBody);
Assert.Equal(21, endPoint.Line);
Assert.Equal(1, endPoint.LineCharOffset);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_BodyWithDelimiter()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
AssertEx.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartBodyWithDelimiter));
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Header()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
AssertEx.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartHeader));
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_HeaderWithAttributes()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
AssertEx.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartHeaderWithAttributes));
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Name()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
AssertEx.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartName));
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Navigate()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
TextPoint endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartNavigate);
Assert.Equal(21, endPoint.Line);
Assert.Equal(1, endPoint.LineCharOffset);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Whole()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
AssertEx.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartWhole));
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_WholeWithAttributes()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
TextPoint endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartWholeWithAttributes);
Assert.Equal(21, endPoint.Line);
Assert.Equal(6, endPoint.LineCharOffset);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void StartPoint()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
TextPoint startPoint = testObject.StartPoint;
Assert.Equal(18, startPoint.Line);
Assert.Equal(5, startPoint.LineCharOffset);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void EndPoint()
{
CodeFunction testObject = GetCodeFunction("A", "MethodA");
TextPoint endPoint = testObject.EndPoint;
Assert.Equal(21, endPoint.Line);
Assert.Equal(6, endPoint.LineCharOffset);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void DynamicReturnType()
{
CodeVariable testObject = (CodeVariable)GetCodeElement("C", "DynamicField");
CodeTypeRef returnType = testObject.Type;
Assert.Equal(returnType.AsFullName, "dynamic");
Assert.Equal(returnType.AsString, "dynamic");
Assert.Equal(returnType.CodeType.FullName, "System.Object");
Assert.Equal(returnType.TypeKind, vsCMTypeRef.vsCMTypeRefOther);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void DynamicParameter()
{
CodeFunction testObject = GetCodeFunction("C", "DynamicMethod");
CodeTypeRef returnType = ((CodeParameter)testObject.Parameters.Item(1)).Type;
Assert.Equal(returnType.AsFullName, "dynamic");
Assert.Equal(returnType.AsString, "dynamic");
Assert.Equal(returnType.CodeType.FullName, "System.Object");
Assert.Equal(returnType.TypeKind, vsCMTypeRef.vsCMTypeRefOther);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
[WorkItem(530496)]
public void TestCodeElementFromPoint()
{
var text = CurrentDocument.GetTextAsync().Result;
var tree = CurrentDocument.GetSyntaxTreeAsync().Result;
var position = text.ToString().IndexOf("DynamicMethod", StringComparison.Ordinal);
var virtualTreePoint = new VirtualTreePoint(tree, text, position);
var textPoint = new MockTextPoint(virtualTreePoint, 4);
var scope = vsCMElement.vsCMElementFunction;
var element = CodeModel.CodeElementFromPoint(textPoint, scope);
Assert.Equal("DynamicMethod", element.Name);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
[WorkItem(726710)]
public void TestCodeElementFromPointBetweenMembers()
{
var text = CurrentDocument.GetTextAsync().Result;
var tree = CurrentDocument.GetSyntaxTreeAsync().Result;
var position = text.ToString().IndexOf("protected virtual string MethodB", StringComparison.Ordinal) - 1;
var virtualTreePoint = new VirtualTreePoint(tree, text, position);
var textPoint = new MockTextPoint(virtualTreePoint, 4);
Assert.Throws<COMException>(() =>
CodeModel.CodeElementFromPoint(textPoint, vsCMElement.vsCMElementFunction));
var element = CodeModel.CodeElementFromPoint(textPoint, vsCMElement.vsCMElementClass);
Assert.Equal("A", element.Name);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Operator()
{
CodeFunction functionObject = GetCodeFunction("A", 3);
Assert.Equal("operator +", functionObject.Name);
}
[ConditionalFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
[WorkItem(924179)]
public void ConversionOperator()
{
CodeClass classObject = (CodeClass)GetCodeElement("Ref");
var element = classObject.Members.Item(1);
Assert.Equal("implicit operator Ref<T>", element.Name);
}
}
}
| |
using System.Data.Entity;
using System.Threading.Tasks;
using JetBrains.Annotations;
using JoinRpg.Dal.Impl.Repositories;
using JoinRpg.Data.Interfaces;
using JoinRpg.Data.Interfaces.Claims;
using JoinRpg.Data.Write.Interfaces;
using JoinRpg.DataModel;
using JoinRpg.DataModel.Finances;
namespace JoinRpg.Dal.Impl
{
[UsedImplicitly]
public class MyDbContext : DbContext, IUnitOfWork
{
/// <summary>
/// Constructor for migrations
/// </summary>
public MyDbContext() : base("DefaultConnection") => Database.Log = sql => DbEasyLog(sql);
/// <summary>
/// Main constructor
/// </summary>
public MyDbContext(IJoinDbContextConfiguration configuration) : base(configuration.ConnectionString)
=> Database.Log = sql => DbEasyLog(sql);
private static void DbEasyLog(string sql) => System.Diagnostics.Debug.WriteLine(sql);
public DbSet<Project> ProjectsSet => Set<Project>();
public DbSet<User> UserSet => Set<User>();
public DbSet<Claim> ClaimSet => Set<Claim>();
DbSet<T> IUnitOfWork.GetDbSet<T>() => Set<T>();
Task IUnitOfWork.SaveChangesAsync() => SaveChangesAsync();
public IUserRepository GetUsersRepository() => new UserInfoRepository(this);
public IProjectRepository GetProjectRepository() => new ProjectRepository(this);
public IClaimsRepository GetClaimsRepository() => new ClaimsRepositoryImpl(this);
public IPlotRepository GetPlotRepository() => new PlotRepositoryImpl(this);
public IForumRepository GetForumRepository() => new ForumRepositoryImpl(this);
public ICharacterRepository GetCharactersRepository() => new CharacterRepositoryImpl(this);
public IAccommodationRepository GetAccomodationRepository() =>
new AccommodationRepositoryImpl(this);
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
ConfigureProjectDetails(modelBuilder);
_ = modelBuilder.Entity<ProjectAcl>().HasKey(c => new { c.UserId, c.ProjectId });
_ = modelBuilder.Entity<ProjectAcl>().HasKey(acl => acl.ProjectAclId);
_ = modelBuilder.Entity<CharacterGroup>()
.HasOptional(c => c.ResponsibleMasterUser)
.WithMany()
.HasForeignKey(c => c.ResponsibleMasterUserId);
modelBuilder.Entity<Project>().HasMany(p => p.Characters).WithRequired(c => c.Project)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Claim>().HasOptional(c => c.Group).WithMany()
.WillCascadeOnDelete(false);
modelBuilder.Entity<Claim>().HasOptional(c => c.Character).WithMany()
.HasForeignKey(c => c.CharacterId).WillCascadeOnDelete(false);
modelBuilder.Entity<Claim>().HasRequired(c => c.Player).WithMany(p => p.Claims)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Claim>().HasRequired(c => c.Project).WithMany(p => p.Claims)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Character>().HasOptional(c => c.ApprovedClaim).WithMany()
.HasForeignKey(c => c.ApprovedClaimId).WillCascadeOnDelete(false);
_ = modelBuilder.Entity<CommentDiscussion>().HasMany(c => c.Comments)
.WithRequired(c => c.Discussion);
modelBuilder.Entity<Claim>()
.HasRequired(c => c.CommentDiscussion)
.WithMany()
.HasForeignKey(c => c.CommentDiscussionId)
.WillCascadeOnDelete(false);
modelBuilder.Entity<ForumThread>()
.HasRequired(c => c.CommentDiscussion)
.WithMany()
.HasForeignKey(ft => ft.CommentDiscussionId)
.WillCascadeOnDelete(false);
_ = modelBuilder.Entity<Claim>()
.HasRequired(c => c.ResponsibleMasterUser)
.WithMany()
.HasForeignKey(c => c.ResponsibleMasterUserId);
_ = modelBuilder.Entity<Claim>()
.HasMany(c => c.FinanceOperations)
.WithRequired(fo => fo.Claim)
.HasForeignKey(fo => fo.ClaimId);
_ = modelBuilder.Entity<AccommodationRequest>().HasMany(c => c.Subjects)
.WithOptional(c => c.AccommodationRequest);
modelBuilder.Entity<Comment>().HasOptional(c => c.Parent).WithMany()
.WillCascadeOnDelete(false);
_ = modelBuilder.Entity<Comment>().HasRequired(comment => comment.CommentText)
.WithRequiredPrincipal();
_ = modelBuilder.Entity<CommentText>().HasKey(pd => pd.CommentId);
modelBuilder.Entity<Comment>().HasRequired(comment => comment.Project).WithMany()
.WillCascadeOnDelete(false);
modelBuilder.Entity<Comment>().HasRequired(comment => comment.Author).WithMany()
.WillCascadeOnDelete(false);
_ = modelBuilder.Entity<Comment>().HasRequired(c => c.Finance)
.WithRequiredPrincipal(fo => fo.Comment);
_ = modelBuilder.Entity<FinanceOperation>().HasKey(fo => fo.CommentId);
_ = modelBuilder.Entity<FinanceOperation>()
.HasOptional(fo => fo.LinkedClaim)
.WithMany()
.HasForeignKey(fo => fo.LinkedClaimId);
_ = modelBuilder.Entity<PlotFolder>().HasMany(pf => pf.RelatedGroups)
.WithMany(cg => cg.DirectlyRelatedPlotFolders);
modelBuilder.Entity<PlotFolder>().HasRequired(pf => pf.Project)
.WithMany(p => p.PlotFolders).WillCascadeOnDelete(false);
_ = modelBuilder.Entity<PlotElement>().HasMany(pe => pe.TargetCharacters)
.WithMany(c => c.DirectlyRelatedPlotElements);
_ = modelBuilder.Entity<PlotElement>().HasMany(pe => pe.TargetGroups)
.WithMany(c => c.DirectlyRelatedPlotElements);
modelBuilder.Entity<PlotElement>().HasRequired(pf => pf.Project).WithMany()
.WillCascadeOnDelete(false);
_ = modelBuilder.Entity<PlotElement>().HasMany(plotElement => plotElement.Texts)
.WithRequired(text => text.PlotElement);
_ = modelBuilder.Entity<PlotElementTexts>()
.HasKey(text => new { text.PlotElementId, text.Version });
_ = modelBuilder.Entity<PlotElementTexts>()
.HasOptional(text => text.AuthorUser)
.WithMany()
.HasForeignKey(text => text.AuthorUserId);
ConfigureUser(modelBuilder);
_ = modelBuilder.Entity<ProjectFieldDropdownValue>()
.HasOptional(v => v.CharacterGroup)
.WithOptionalDependent();
_ = modelBuilder.Entity<ProjectField>()
.HasOptional(v => v.CharacterGroup)
.WithOptionalDependent();
modelBuilder.Entity<UserForumSubscription>().HasRequired(ufs => ufs.User).WithMany()
.WillCascadeOnDelete(false);
modelBuilder.Entity<ProjectItemTag>().Property(tag => tag.TagName).IsUnique();
_ = modelBuilder.Entity<PlotFolder>().HasMany(tag => tag.PlotTags).WithMany();
_ = modelBuilder.Entity<ProjectAccommodationType>();
_ = modelBuilder.Entity<ProjectAccommodation>();
_ = modelBuilder.Entity<AccommodationRequest>();
_ = modelBuilder.Entity<AccommodationInvite>();
ConfigureMoneyTransfer(modelBuilder);
base.OnModelCreating(modelBuilder);
}
private static void ConfigureUser(DbModelBuilder modelBuilder)
{
_ = modelBuilder.Entity<User>().HasRequired(u => u.Auth).WithRequiredPrincipal();
_ = modelBuilder.Entity<UserAuthDetails>().HasKey(uad => uad.UserId);
_ = modelBuilder.Entity<User>().HasRequired(u => u.Allrpg).WithRequiredPrincipal();
_ = modelBuilder.Entity<AllrpgUserDetails>().HasKey(a => a.UserId);
_ = modelBuilder.Entity<User>().HasRequired(u => u.Extra).WithRequiredPrincipal();
_ = modelBuilder.Entity<UserExtra>().HasKey(a => a.UserId);
_ = modelBuilder.Entity<User>()
.HasMany(u => u.ExternalLogins)
.WithRequired(uel => uel.User)
.HasForeignKey(uel => uel.UserId);
modelBuilder.Entity<User>().HasMany(u => u.Subscriptions).WithRequired(s => s.User)
.WillCascadeOnDelete(true);
modelBuilder.Entity<UserSubscription>().HasRequired(us => us.Project).WithMany()
.WillCascadeOnDelete(false);
modelBuilder.Entity<UserSubscription>()
.HasOptional(us => us.Claim)
.WithMany(c => c.Subscriptions)
.HasForeignKey(us => us.ClaimId)
.WillCascadeOnDelete(false);
modelBuilder.Entity<User>()
.HasMany(u => u.Avatars)
.WithRequired(a => a.User)
.HasForeignKey(a => a.UserId)
.WillCascadeOnDelete(false);
modelBuilder.Entity<User>()
.HasOptional(c => c.SelectedAvatar)
.WithMany()
.WillCascadeOnDelete(false);
}
private static void ConfigureProjectDetails(DbModelBuilder modelBuilder)
{
_ = modelBuilder.Entity<Project>().HasRequired(p => p.Details).WithRequiredPrincipal();
_ = modelBuilder.Entity<ProjectDetails>().HasKey(pd => pd.ProjectId);
}
private static void ConfigureMoneyTransfer(DbModelBuilder modelBuilder)
{
var entity = modelBuilder.Entity<MoneyTransfer>();
entity.HasRequired(e => e.Sender).WithMany().WillCascadeOnDelete(false);
entity.HasRequired(e => e.Receiver).WithMany().WillCascadeOnDelete(false);
entity.HasRequired(e => e.CreatedBy).WithMany().WillCascadeOnDelete(false);
entity.HasRequired(e => e.ChangedBy).WithMany().WillCascadeOnDelete(false);
_ = entity.HasRequired(comment => comment.TransferText).WithRequiredPrincipal();
_ = modelBuilder.Entity<TransferText>().HasKey(pd => pd.MoneyTransferId);
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V10.Resources
{
/// <summary>Resource name for the <c>ConversionGoalCampaignConfig</c> resource.</summary>
public sealed partial class ConversionGoalCampaignConfigName : gax::IResourceName, sys::IEquatable<ConversionGoalCampaignConfigName>
{
/// <summary>The possible contents of <see cref="ConversionGoalCampaignConfigName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>customers/{customer_id}/conversionGoalCampaignConfigs/{campaign_id}</c>.
/// </summary>
CustomerCampaign = 1,
}
private static gax::PathTemplate s_customerCampaign = new gax::PathTemplate("customers/{customer_id}/conversionGoalCampaignConfigs/{campaign_id}");
/// <summary>
/// Creates a <see cref="ConversionGoalCampaignConfigName"/> 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="ConversionGoalCampaignConfigName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static ConversionGoalCampaignConfigName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new ConversionGoalCampaignConfigName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="ConversionGoalCampaignConfigName"/> with the pattern
/// <c>customers/{customer_id}/conversionGoalCampaignConfigs/{campaign_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// A new instance of <see cref="ConversionGoalCampaignConfigName"/> constructed from the provided ids.
/// </returns>
public static ConversionGoalCampaignConfigName FromCustomerCampaign(string customerId, string campaignId) =>
new ConversionGoalCampaignConfigName(ResourceNameType.CustomerCampaign, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ConversionGoalCampaignConfigName"/> with
/// pattern <c>customers/{customer_id}/conversionGoalCampaignConfigs/{campaign_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ConversionGoalCampaignConfigName"/> with pattern
/// <c>customers/{customer_id}/conversionGoalCampaignConfigs/{campaign_id}</c>.
/// </returns>
public static string Format(string customerId, string campaignId) => FormatCustomerCampaign(customerId, campaignId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ConversionGoalCampaignConfigName"/> with
/// pattern <c>customers/{customer_id}/conversionGoalCampaignConfigs/{campaign_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ConversionGoalCampaignConfigName"/> with pattern
/// <c>customers/{customer_id}/conversionGoalCampaignConfigs/{campaign_id}</c>.
/// </returns>
public static string FormatCustomerCampaign(string customerId, string campaignId) =>
s_customerCampaign.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="ConversionGoalCampaignConfigName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/conversionGoalCampaignConfigs/{campaign_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="conversionGoalCampaignConfigName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <returns>The parsed <see cref="ConversionGoalCampaignConfigName"/> if successful.</returns>
public static ConversionGoalCampaignConfigName Parse(string conversionGoalCampaignConfigName) =>
Parse(conversionGoalCampaignConfigName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="ConversionGoalCampaignConfigName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/conversionGoalCampaignConfigs/{campaign_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="conversionGoalCampaignConfigName">
/// 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="ConversionGoalCampaignConfigName"/> if successful.</returns>
public static ConversionGoalCampaignConfigName Parse(string conversionGoalCampaignConfigName, bool allowUnparsed) =>
TryParse(conversionGoalCampaignConfigName, allowUnparsed, out ConversionGoalCampaignConfigName 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="ConversionGoalCampaignConfigName"/>
/// instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/conversionGoalCampaignConfigs/{campaign_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="conversionGoalCampaignConfigName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ConversionGoalCampaignConfigName"/>, 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 conversionGoalCampaignConfigName, out ConversionGoalCampaignConfigName result) =>
TryParse(conversionGoalCampaignConfigName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ConversionGoalCampaignConfigName"/>
/// instance; optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/conversionGoalCampaignConfigs/{campaign_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="conversionGoalCampaignConfigName">
/// 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="ConversionGoalCampaignConfigName"/>, 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 conversionGoalCampaignConfigName, bool allowUnparsed, out ConversionGoalCampaignConfigName result)
{
gax::GaxPreconditions.CheckNotNull(conversionGoalCampaignConfigName, nameof(conversionGoalCampaignConfigName));
gax::TemplatedResourceName resourceName;
if (s_customerCampaign.TryParseName(conversionGoalCampaignConfigName, out resourceName))
{
result = FromCustomerCampaign(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(conversionGoalCampaignConfigName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private ConversionGoalCampaignConfigName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string campaignId = null, string customerId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CampaignId = campaignId;
CustomerId = customerId;
}
/// <summary>
/// Constructs a new instance of a <see cref="ConversionGoalCampaignConfigName"/> class from the component parts
/// of pattern <c>customers/{customer_id}/conversionGoalCampaignConfigs/{campaign_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
public ConversionGoalCampaignConfigName(string customerId, string campaignId) : this(ResourceNameType.CustomerCampaign, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)))
{
}
/// <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>Campaign</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CampaignId { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>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.CustomerCampaign: return s_customerCampaign.Expand(CustomerId, CampaignId);
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 ConversionGoalCampaignConfigName);
/// <inheritdoc/>
public bool Equals(ConversionGoalCampaignConfigName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(ConversionGoalCampaignConfigName a, ConversionGoalCampaignConfigName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(ConversionGoalCampaignConfigName a, ConversionGoalCampaignConfigName b) => !(a == b);
}
public partial class ConversionGoalCampaignConfig
{
/// <summary>
/// <see cref="ConversionGoalCampaignConfigName"/>-typed view over the <see cref="ResourceName"/> resource name
/// property.
/// </summary>
internal ConversionGoalCampaignConfigName ResourceNameAsConversionGoalCampaignConfigName
{
get => string.IsNullOrEmpty(ResourceName) ? null : ConversionGoalCampaignConfigName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="CampaignName"/>-typed view over the <see cref="Campaign"/> resource name property.
/// </summary>
internal CampaignName CampaignAsCampaignName
{
get => string.IsNullOrEmpty(Campaign) ? null : CampaignName.Parse(Campaign, allowUnparsed: true);
set => Campaign = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="CustomConversionGoalName"/>-typed view over the <see cref="CustomConversionGoal"/> resource name
/// property.
/// </summary>
internal CustomConversionGoalName CustomConversionGoalAsCustomConversionGoalName
{
get => string.IsNullOrEmpty(CustomConversionGoal) ? null : CustomConversionGoalName.Parse(CustomConversionGoal, allowUnparsed: true);
set => CustomConversionGoal = value?.ToString() ?? "";
}
}
}
| |
namespace Microsoft.Protocols.TestSuites.MS_FSSHTTP_FSSHTTPB
{
using Microsoft.Protocols.TestSuites.Common;
using Microsoft.Protocols.TestSuites.SharedAdapter;
using Microsoft.Protocols.TestSuites.SharedTestSuite;
using Microsoft.Protocols.TestTools;
using Microsoft.VisualStudio.TestTools.UnitTesting;
/// <summary>
/// A class which contains test cases used to verify the exclusive lock sub request operation.
/// </summary>
[TestClass]
public sealed class MS_FSSHTTP_FSSHTTPB_S04_ExclusiveLock : S04_ExclusiveLock
{
#region Test Suite Initialization and clean up
/// <summary>
/// Class initialization
/// </summary>
/// <param name="testContext">The context of the test suite.</param>
[ClassInitialize]
public static new void ClassInitialize(TestContext testContext)
{
S04_ExclusiveLock.ClassInitialize(testContext);
}
/// <summary>
/// Class clean up
/// </summary>
[ClassCleanup]
public static new void ClassCleanup()
{
S04_ExclusiveLock.ClassCleanup();
}
#endregion
/// <summary>
/// A method used to test the ErrorCode value when getting an exclusive lock and the file URL is not present.
/// </summary>
[TestCategory("MSFSSHTTP_FSSHTTPB"), TestMethod()]
public void MSFSSHTTP_FSSHTTPB_S04_TC01_ExclusiveLock_UrlNotSpecified()
{
// Initialize the service
this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain);
ExclusiveLockSubRequestType subRequest = SharedTestSuiteHelper.CreateExclusiveLockSubRequest(ExclusiveLockRequestTypes.GetLock);
CellStorageResponse response = new CellStorageResponse();
bool isR3006Verified = false;
try
{
// Send a GetLock for exclusive subRequest to the protocol server without specifying URL attribute.
response = this.Adapter.CellStorageRequest(null, new SubRequestType[] { subRequest });
}
catch (System.Xml.XmlException exception)
{
string message = exception.Message;
isR3006Verified = message.Contains("Duplicate attribute");
isR3006Verified &= message.Contains("ErrorCode");
}
if (SharedContext.Current.IsMsFsshttpRequirementsCaptured)
{
// Verify MS-FSSHTTP requirement: MS-FSSHTTP_R3006
if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 3006, this.Site))
{
Site.Log.Add(
LogEntryKind.Debug,
"SharePoint server 2010 and SharePoint Foundation responses two ErrorCode attributes when the URL is non exists.");
Site.CaptureRequirementIfIsTrue(
isR3006Verified,
"MS-FSSHTTP",
3006,
@"[In Appendix B: Product Behavior] If the Url attribute of the corresponding Request element doesn't exist, the implementation does return two ErrorCode attributes in Response element. <11> Section 2.2.3.5: SharePoint Server 2010 will return 2 ErrorCode attributes in Response element.");
}
// Verify MS-FSSHTTP requirement: MS-FSSHTTP_R3007
if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 3007, this.Site))
{
Site.CaptureRequirementIfIsNull(
response.ResponseCollection,
"MS-FSSHTTP",
3007,
@"[In Appendix B: Product Behavior] If the Url attribute of the corresponding Request element doesn't exist, the implementation does not return Response element. <8> Section 2.2.3.5: SharePoint Server 2013 will not return Response element.");
}
}
else
{
if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 3006, this.Site))
{
Site.Log.Add(
LogEntryKind.Debug,
"SharePoint server 2010 and SharePoint Foundation responses two ErrorCode attributes when the URL is non exists.");
Site.Assert.IsTrue(
isR3006Verified,
"SharePoint server 2010 and SharePoint Foundation responses two ErrorCode attributes when the URL is non exists.");
}
if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 3007, this.Site))
{
Site.Assert.IsNull(
response.ResponseCollection,
@"[In Appendix B: Product Behavior] If the Url attribute of the corresponding Request element doesn't exist, the implementation does not return Response element. <8> Section 2.2.3.5: SharePoint Server 2013 will not return Response element.");
}
}
}
/// <summary>
/// A method used to verify the related requirements when get an exclusive lock on a file which is already checked out by the same client.
/// </summary>
[TestCategory("MSFSSHTTP_FSSHTTPB"), TestMethod()]
public void MSFSSHTTP_FSSHTTPB_S04_TC02_GetExclusiveLock_CheckoutByCurrentClient()
{
// Check out one file by a specified user name.
if (!this.SutManagedAdapter.CheckOutFile(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain))
{
this.Site.Assert.Fail("Cannot change the file {0} to check out status using the user name {1} and password{2}", this.DefaultFileUrl, this.UserName01, this.Password01);
}
// Record the file check out status.
this.StatusManager.RecordFileCheckOut(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain);
// Initialize the service.
this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain);
CheckLockAvailability();
// Get the exclusive lock using the same user name comparing with the previous step for the already checked out file, expect the server responds the error code "Success".
// Now the service channel is initialized using the userName01 account by default.
ExclusiveLockSubRequestType subRequest = SharedTestSuiteHelper.CreateExclusiveLockSubRequest(ExclusiveLockRequestTypes.GetLock);
CellStorageResponse response = this.Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { subRequest });
ExclusiveLockSubResponseType exclusiveResponse = SharedTestSuiteHelper.ExtractSubResponse<ExclusiveLockSubResponseType>(response, 0, 0, this.Site);
if (SharedContext.Current.IsMsFsshttpRequirementsCaptured)
{
// If the error code equals "Success", then capture MS-FSSHTTP_R1247
Site.CaptureRequirementIfAreEqual<ErrorCodeType>(
ErrorCodeType.Success,
SharedTestSuiteHelper.ConvertToErrorCodeType(exclusiveResponse.ErrorCode, this.Site),
"MS-FSSHTTP",
1247,
@"[In Get Lock] If the checkout of the file has been done by the current client, the protocol server MUST allow an exclusive lock on the file.");
}
else
{
Site.Assert.AreEqual<ErrorCodeType>(
ErrorCodeType.Success,
SharedTestSuiteHelper.ConvertToErrorCodeType(exclusiveResponse.ErrorCode, this.Site),
@"[In Get Lock] If the checkout of the file has been done by the current client, the protocol server MUST allow an exclusive lock on the file.");
}
// Record the file exclusive lock status.
this.StatusManager.RecordExclusiveLock(this.DefaultFileUrl, subRequest.SubRequestData.ExclusiveLockID);
}
/// <summary>
/// A method used to verify the related requirements when the Check Lock Availability of ExclusiveLock sub request succeeds.
/// </summary>
[TestCategory("MSFSSHTTP_FSSHTTPB"), TestMethod()]
public void MSFSSHTTP_FSSHTTPB_S04_TC03_CheckExclusiveLockAvailability_Success()
{
// Initialize the service.
this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain);
ExclusiveLockSubRequestType exclusiveLocksubRequest = SharedTestSuiteHelper.CreateExclusiveLockSubRequest(ExclusiveLockRequestTypes.CheckLockAvailability);
// Check the exclusive lock availability with all valid parameters on a file on which there is no lock, expect the server responds the error code "Success".
CellStorageResponse response = this.Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { exclusiveLocksubRequest });
ExclusiveLockSubResponseType exclusiveResponse = SharedTestSuiteHelper.ExtractSubResponse<ExclusiveLockSubResponseType>(response, 0, 0, this.Site);
if (SharedContext.Current.IsMsFsshttpRequirementsCaptured)
{
// If the error code equals "Success", then capture MS-FSSHTTP_RR13122
Site.CaptureRequirementIfAreEqual<ErrorCodeType>(
ErrorCodeType.Success,
SharedTestSuiteHelper.ConvertToErrorCodeType(exclusiveResponse.ErrorCode, this.Site),
"MS-FSSHTTP",
13122,
@"[In Check Lock Availability] The protocol server returns error codes according to the following rules: In all other cases[the file is not checked out and there is no current exclusive lock and shared lock on the file], the protocol server returns an error code value set to ""Success"" to indicate the availability of the file for locking.");
// If the error code equals "Success", then capture MS-FSSHTTP_R1236
Site.CaptureRequirementIfAreEqual<ErrorCodeType>(
ErrorCodeType.Success,
SharedTestSuiteHelper.ConvertToErrorCodeType(exclusiveResponse.ErrorCode, this.Site),
"MS-FSSHTTP",
1236,
@"[In ExclusiveLock Subrequest] An ErrorCode value of ""Success"" indicates success in processing the exclusive lock request.");
}
else
{
Site.Assert.AreEqual<ErrorCodeType>(
ErrorCodeType.Success,
SharedTestSuiteHelper.ConvertToErrorCodeType(exclusiveResponse.ErrorCode, this.Site),
@"[In Check Lock Availability] The protocol server returns error codes according to the following rules: In all other cases[the file is not checked out and there is no current exclusive lock and shared lock on the file], the protocol server returns an error code value set to ""Success"" to indicate the availability of the file for locking.");
}
// Prepare an exclusive lock
this.PrepareExclusiveLock(this.DefaultFileUrl, SharedTestSuiteHelper.DefaultExclusiveLockID);
// Check the exclusive lock availability with all valid parameters on a file which is locked by the same exclusive lock id, expect the server responds the error code "Success".
exclusiveLocksubRequest = SharedTestSuiteHelper.CreateExclusiveLockSubRequest(ExclusiveLockRequestTypes.CheckLockAvailability);
response = this.Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { exclusiveLocksubRequest });
exclusiveResponse = SharedTestSuiteHelper.ExtractSubResponse<ExclusiveLockSubResponseType>(response, 0, 0, this.Site);
if (SharedContext.Current.IsMsFsshttpRequirementsCaptured)
{
// If the error code equals "Success", then capture MS-FSSHTTP_R13121
Site.CaptureRequirementIfAreEqual<ErrorCodeType>(
ErrorCodeType.Success,
SharedTestSuiteHelper.ConvertToErrorCodeType(exclusiveResponse.ErrorCode, this.Site),
"MS-FSSHTTP",
13121,
@"[In Check Lock Availability] The protocol server returns error codes according to the following rules: In all other cases[there is a current exclusive lock on the file with a same exclusive lock identifier with the one specified by the current client], the protocol server returns an error code value set to ""Success"" to indicate the availability of the file for locking.");
}
else
{
Site.Assert.AreEqual<ErrorCodeType>(
ErrorCodeType.Success,
SharedTestSuiteHelper.ConvertToErrorCodeType(exclusiveResponse.ErrorCode, this.Site),
@"[In Check Lock Availability] The protocol server returns error codes according to the following rules: In all other cases[there is a current exclusive lock on the file with a same exclusive lock identifier with the one specified by the current client], the protocol server returns an error code value set to ""Success"" to indicate the availability of the file for locking.");
}
if (!this.StatusManager.RollbackStatus())
{
this.Site.Assert.Fail("Cannot release the exclusive lock {0}", SharedTestSuiteHelper.DefaultExclusiveLockID);
}
// Check out one file by a specified user name.
if (!this.SutManagedAdapter.CheckOutFile(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain))
{
this.Site.Assert.Fail("Cannot change the file {0} to check out status using the user name {1} and password {2}", this.DefaultFileUrl, this.UserName01, this.Password01);
}
this.StatusManager.RecordFileCheckOut(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain);
CheckLockAvailability();
// Check the exclusive lock availability with all valid parameters on a file which is checked out by the same user, expect the server responds the error code "Success".
exclusiveLocksubRequest = SharedTestSuiteHelper.CreateExclusiveLockSubRequest(ExclusiveLockRequestTypes.CheckLockAvailability);
response = this.Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { exclusiveLocksubRequest });
exclusiveResponse = SharedTestSuiteHelper.ExtractSubResponse<ExclusiveLockSubResponseType>(response, 0, 0, this.Site);
if (SharedContext.Current.IsMsFsshttpRequirementsCaptured)
{
// If the error code equals "Success", then capture MS-FSSHTTP_R13123
Site.CaptureRequirementIfAreEqual<ErrorCodeType>(
ErrorCodeType.Success,
SharedTestSuiteHelper.ConvertToErrorCodeType(exclusiveResponse.ErrorCode, this.Site),
"MS-FSSHTTP",
13123,
@"[In Check Lock Availability] The protocol server returns error codes according to the following rules: In all other cases[the file has been checked out by the current user and there is no current exclusive lock and shared lock on the file], the protocol server returns an error code value set to ""Success"" to indicate the availability of the file for locking.");
}
else
{
Site.Assert.AreEqual<ErrorCodeType>(
ErrorCodeType.Success,
SharedTestSuiteHelper.ConvertToErrorCodeType(exclusiveResponse.ErrorCode, this.Site),
@"[In Check Lock Availability] The protocol server returns error codes according to the following rules: In all other cases[the file has been checked out by the current user and there is no current exclusive lock and shared lock on the file], the protocol server returns an error code value set to ""Success"" to indicate the availability of the file for locking.");
}
}
/// <summary>
/// A method used to verify the related requirements when convert an exclusive lock to coauthoring lock on a file which is checked out by the same client.
/// </summary>
[TestCategory("MSFSSHTTP_FSSHTTPB"), TestMethod()]
public void MSFSSHTTP_FSSHTTPB_S04_TC04_ConvertToSchemaJoinCoauth_ConvertToSchemaFailedFileCheckedOutByCurrentUser()
{
// Check out one file by a specified user name.
if (!this.SutManagedAdapter.CheckOutFile(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain))
{
this.Site.Assert.Fail("Cannot change the file {0} to check out status using the user name {1} and password{2}", this.DefaultFileUrl, this.UserName01, this.Password01);
}
// Record the file check out status.
this.StatusManager.RecordFileCheckOut(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain);
// Initialize the service
this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain);
CheckLockAvailability();
// Get the exclusive lock using the same user name on the already checked out file, expect the server response the error code "Success".
this.PrepareExclusiveLock(this.DefaultFileUrl, SharedTestSuiteHelper.DefaultExclusiveLockID);
// Convert current exclusive lock to a coauthoring shared lock with the same exclusive lock id as the previous step on the already checked out file, expect the server returns the error code "ConvertToSchemaFailedFileCheckedOutByCurrentUser".
ExclusiveLockSubRequestType subRequest = SharedTestSuiteHelper.CreateExclusiveLockSubRequest(ExclusiveLockRequestTypes.ConvertToSchemaJoinCoauth);
CellStorageResponse response = this.Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { subRequest });
ExclusiveLockSubResponseType exclusiveResponse = SharedTestSuiteHelper.ExtractSubResponse<ExclusiveLockSubResponseType>(response, 0, 0, this.Site);
if (SharedContext.Current.IsMsFsshttpRequirementsCaptured)
{
// If the error code equals ConvertToSchemaFailedFileCheckedOutByCurrentUser, then capture MS-FSSHTTP requirement: MS-FSSHTTP_R1229, MS-FSSHTTP_R1279
Site.CaptureRequirementIfAreEqual<ErrorCodeType>(
ErrorCodeType.ConvertToSchemaFailedFileCheckedOutByCurrentUser,
SharedTestSuiteHelper.ConvertToErrorCodeType(exclusiveResponse.ErrorCode, this.Site),
"MS-FSSHTTP",
1229,
@"[In ExclusiveLock Subrequest][The protocol returns results based on the following conditions: ] If the protocol server gets an exclusive lock subrequest of type ""Convert to schema lock with coauthoring transition tracked"" for a file, and the conversion fails because the file is checked out by the current client, the protocol server returns an error code value set to ""ConvertToSchemaFailedFileCheckedOutByCurrentUser"".");
// Verify MS-FSSHTTP requirement: MS-FSSHTTP_R1279
Site.CaptureRequirementIfAreEqual<ErrorCodeType>(
ErrorCodeType.ConvertToSchemaFailedFileCheckedOutByCurrentUser,
SharedTestSuiteHelper.ConvertToErrorCodeType(exclusiveResponse.ErrorCode, this.Site),
"MS-FSSHTTP",
1279,
@"[In Convert to Schema Lock with Coauthoring Transition Tracked] The protocol server returns error codes according to the following rules: If the protocol server is unable to convert the exclusive lock to a shared lock on the file because the file is checked out by the current user, the protocol server returns an error code value set to ""ConvertToSchemaFailedFileCheckedOutByCurrentUser"".");
// Verify MS-FSSHTTP requirement: MS-FSSHTTP_R387
Site.CaptureRequirementIfAreEqual<ErrorCodeType>(
ErrorCodeType.ConvertToSchemaFailedFileCheckedOutByCurrentUser,
SharedTestSuiteHelper.ConvertToErrorCodeType(exclusiveResponse.ErrorCode, this.Site),
"MS-FSSHTTP",
387,
@"[In LockAndCoauthRelatedErrorCodeTypes] ConvertToSchemaFailedFileCheckedOutByCurrentUser indicates an error when converting to a shared lock fails because the file is checked out by the current client.");
}
else
{
Site.Assert.AreEqual<ErrorCodeType>(
ErrorCodeType.ConvertToSchemaFailedFileCheckedOutByCurrentUser,
SharedTestSuiteHelper.ConvertToErrorCodeType(exclusiveResponse.ErrorCode, this.Site),
@"[In ExclusiveLock Subrequest][The protocol returns results based on the following conditions: ] If the protocol server gets an exclusive lock subrequest of type ""Convert to schema lock with coauthoring transition tracked"" for a file, and the conversion fails because the file is checked out by the current client, the protocol server returns an error code value set to ""ConvertToSchemaFailedFileCheckedOutByCurrentUser"".");
}
}
/// <summary>
/// A method used to verify the related requirements when convert an exclusive lock to schema lock on a file which is checked out by the same client.
/// </summary>
[TestCategory("MSFSSHTTP_FSSHTTPB"), TestMethod()]
public void MSFSSHTTP_FSSHTTPB_S04_TC05_ConvertToSchema_ConvertToSchemaFailedFileCheckedOutByCurrentUser()
{
// Check out one file by a specified user name.
if (!this.SutManagedAdapter.CheckOutFile(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain))
{
this.Site.Assert.Fail("Cannot change the file {0} to check out status using the user name {1} and password{2}", this.DefaultFileUrl, this.UserName01, this.UserName01);
}
// Record the file check out status.
this.StatusManager.RecordFileCheckOut(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain);
// Initialize the service
this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain);
CheckLockAvailability();
// Get the exclusive lock with same user name on the checked out file.
this.PrepareExclusiveLock(this.DefaultFileUrl, SharedTestSuiteHelper.DefaultExclusiveLockID);
// Convert the current exclusive lock to a coauthoring shared lock on the already check out file, expect the server returns the error code "ConvertToSchemaFailedFileCheckedOutByCurrentUser".
ExclusiveLockSubRequestType subRequest = SharedTestSuiteHelper.CreateExclusiveLockSubRequest(ExclusiveLockRequestTypes.ConvertToSchema);
CellStorageResponse response = this.Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { subRequest });
ExclusiveLockSubResponseType exclusiveResponse = SharedTestSuiteHelper.ExtractSubResponse<ExclusiveLockSubResponseType>(response, 0, 0, this.Site);
if (SharedContext.Current.IsMsFsshttpRequirementsCaptured)
{
// If the error code equals "FailedFileCheckedOutByCurrentUser", then capture MS-FSSHTTP_R1230,MS-FSSHTTP_R1949
Site.CaptureRequirementIfAreEqual<ErrorCodeType>(
ErrorCodeType.ConvertToSchemaFailedFileCheckedOutByCurrentUser,
SharedTestSuiteHelper.ConvertToErrorCodeType(exclusiveResponse.ErrorCode, this.Site),
"MS-FSSHTTP",
1230,
@"[In ExclusiveLock Subrequest][If the protocol server gets an exclusive lock subrequest of type ""Convert to schema lock with] ""Convert to schema lock"" for a file, and the conversion fails because the file is checked out by the current client, the protocol server returns an error code value set to ""ConvertToSchemaFailedFileCheckedOutByCurrentUser"".");
// Verify MS-FSSHTTP requirement: MS-FSSHTTP_R1299
Site.CaptureRequirementIfAreEqual<ErrorCodeType>(
ErrorCodeType.ConvertToSchemaFailedFileCheckedOutByCurrentUser,
SharedTestSuiteHelper.ConvertToErrorCodeType(exclusiveResponse.ErrorCode, this.Site),
"MS-FSSHTTP",
1299,
@"[In Convert to Schema Lock] The protocol server returns error codes according to the following rules: If the protocol server is unable to convert the exclusive lock to a shared lock on the file because the file is checked out by the current user, the protocol server returns an error code value set to ""ConvertToSchemaFailedFileCheckedOutByCurrentUser"".");
// Verify MS-FSSHTTP requirement: MS-FSSHTTP_R387
Site.CaptureRequirementIfAreEqual<ErrorCodeType>(
ErrorCodeType.ConvertToSchemaFailedFileCheckedOutByCurrentUser,
SharedTestSuiteHelper.ConvertToErrorCodeType(exclusiveResponse.ErrorCode, this.Site),
"MS-FSSHTTP",
387,
@"[In LockAndCoauthRelatedErrorCodeTypes] ConvertToSchemaFailedFileCheckedOutByCurrentUser indicates an error when converting to a shared lock fails because the file is checked out by the current client.");
}
else
{
Site.Assert.AreEqual<ErrorCodeType>(
ErrorCodeType.ConvertToSchemaFailedFileCheckedOutByCurrentUser,
SharedTestSuiteHelper.ConvertToErrorCodeType(exclusiveResponse.ErrorCode, this.Site),
@"[In ExclusiveLock Subrequest][If the protocol server gets an exclusive lock subrequest of type ""Convert to schema lock with] ""Convert to schema lock"" for a file, and the conversion fails because the file is checked out by the current client, the protocol server returns an error code value set to ""ConvertToSchemaFailedFileCheckedOutByCurrentUser"".");
}
}
/// <summary>
/// A method used to test the ErrorCode value when getting an exclusive lock on a non-existent file.
/// </summary>
[TestCategory("MSFSSHTTP_FSSHTTPB"), TestMethod()]
public void MSFSSHTTP_FSSHTTPB_S04_TC06_ExclusiveLock_FileNotExistsOrCannotBeCreated()
{
// Initialize the service
this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain);
string notExistsFileUrl = this.DefaultFileUrl.Substring(0, this.DefaultFileUrl.LastIndexOf('/')) + "/noexistsFile.txt";
ExclusiveLockSubRequestType subRequest = SharedTestSuiteHelper.CreateExclusiveLockSubRequest(ExclusiveLockRequestTypes.GetLock);
// Get the exclusive lock with nonexistent file URL and expect the server returns error code "LockRequestFail" or "Unknown".
CellStorageResponse response = this.Adapter.CellStorageRequest(notExistsFileUrl, new SubRequestType[] { subRequest });
ExclusiveLockSubResponseType exclusiveResponse = SharedTestSuiteHelper.ExtractSubResponse<ExclusiveLockSubResponseType>(response, 0, 0, this.Site);
ErrorCodeType errorType = SharedTestSuiteHelper.ConvertToErrorCodeType(exclusiveResponse.ErrorCode, this.Site);
bool isR1926Verified = errorType == ErrorCodeType.LockRequestFail || errorType == ErrorCodeType.Unknown || errorType == ErrorCodeType.FileNotExistsOrCannotBeCreated;
this.Site.Log.Add(
LogEntryKind.Debug,
"For requirement MS-FSSHTTP_R1926, expect the error code LockRequestFail or Unknown or FileNotExistsOrCannotBeCreated, but actually error code is " + errorType);
if (Common.IsRequirementEnabled(1926, this.Site))
{
if (SharedContext.Current.IsMsFsshttpRequirementsCaptured)
{
// Verify MS-FSSHTTP requirement: MS-FSSHTTP_R1926
Site.CaptureRequirementIfIsTrue(
isR1926Verified,
"MS-FSSHTTP",
1926,
@"[In ExclusiveLock Subrequest][The protocol returns results based on the following conditions: ] If the protocol server was unable to find the URL for the file specified in the Url attribute, the protocol server reports a failure by returning an error code value set to ""LockRequestFail "" or ""Unknown"" or ""FileNotExistsOrCannotBeCreated"" in the ErrorCode attribute sent back in the SubResponse element.");
}
else
{
Site.Assert.IsTrue(
isR1926Verified,
@"[In ExclusiveLock Subrequest][The protocol returns results based on the following conditions: ] If the protocol server was unable to find the URL for the file specified in the Url attribute, the protocol server reports a failure by returning an error code value set to ""LockRequestFail "" or ""Unknown"" or ""FileNotExistsOrCannotBeCreated"" in the ErrorCode attribute sent back in the SubResponse element.");
}
}
}
/// <summary>
/// A method used to test calling cell storage web service when this service is turned off.
/// </summary>
[TestCategory("MSFSSHTTP_FSSHTTPB"), TestMethod()]
public void MSFSSHTTP_FSSHTTPB_S04_TC07_ExclusiveLock_CellStorageWebServiceDisabled()
{
if (!this.SutPowerShellAdapter.SwitchCellStorageService(false))
{
this.Site.Assert.Fail("Cannot disable the cell storage web service.");
}
this.StatusManager.RecordDisableCellStorageService();
// Initialize the service
this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain);
// Call the GetExclusiveLock to expect fail.
ExclusiveLockSubRequestType subRequest = SharedTestSuiteHelper.CreateExclusiveLockSubRequest(ExclusiveLockRequestTypes.GetLock);
CellStorageResponse response = this.Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { subRequest });
this.Site.Log.Add(
LogEntryKind.Debug,
"When the cell storage service is turned off, the error code should be not null but actual {0}",
response.ResponseVersion.ErrorCodeSpecified ? "is not null" : "null");
if (SharedContext.Current.IsMsFsshttpRequirementsCaptured)
{
if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 15181, this.Site))
{
// Verify MS-FSSHTTP requirement: MS-FSSHTTP_R15181
Site.CaptureRequirementIfIsTrue(
response.ResponseVersion.ErrorCodeSpecified,
"MS-FSSHTTP",
15181,
@"[In Appendix B: Product Behavior] ErrorCode attribute is present if this protocol is not enabled on the protocol server.(<15> Section 2.2.3.7: In SharePoint Foundation 2010, SharePoint Server 2010, SharePoint Foundation 2013 and SharePoint Server 2013, the ErrorCode attribute is present if this protocol is not enabled on the protocol server.)");
// Verify MS-FSSHTTP requirement: MS-FSSHTTP_R368
Site.CaptureRequirementIfAreEqual<GenericErrorCodeTypes>(
GenericErrorCodeTypes.WebServiceTurnedOff,
response.ResponseVersion.ErrorCode,
"MS-FSSHTTP",
368,
@"[In GenericErrorCodeTypes] WebServiceTurnedOff indicates an error when the web service is turned off during the processing of the cell storage service request.");
}
else
{
// Verify MS-FSSHTTP requirement: MS-FSSHTTP_R2458
Site.CaptureRequirementIfIsFalse(
response.ResponseVersion.ErrorCodeSpecified,
"MS-FSSHTTP",
2458,
@"[In Appendix B: Product Behavior] ErrorCode attribute is not present if this protocol is not enabled on the protocol server.(SharePoint Server 2016 and above follow this behavior)");
}
}
else
{
if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 15181, this.Site))
{
Site.Assert.IsTrue(
response.ResponseVersion.ErrorCodeSpecified,
@"ErrorCode attribute is present if this protocol is not enabled on the protocol server.(<15> Section 2.2.3.7: In SharePoint Foundation 2010, SharePoint Server 2010, SharePoint Foundation 2013 and SharePoint Server 2013, the ErrorCode attribute is present if this protocol is not enabled on the protocol server.)");
Site.Assert.AreEqual<GenericErrorCodeTypes>(
GenericErrorCodeTypes.WebServiceTurnedOff,
response.ResponseVersion.ErrorCode,
@"[In GenericErrorCodeTypes] WebServiceTurnedOff indicates an error when the web service is turned off during the processing of the cell storage service request.");
}
}
}
/// <summary>
/// A method used to verify the protocol server returns ErrorCode "FileUnauthorizedAccess" when the user does not have permission to issue a cell storage service request to the file.
/// </summary>
[TestCategory("MSFSSHTTP_FSSHTTPB"), TestMethod()]
public void MSFSSHTTP_FSSHTTPB_S04_TC08_ExclusiveLock_NoPermissionIssueCellStorageService()
{
// Initialize the service
this.InitializeContext(this.DefaultFileUrl, Common.GetConfigurationPropertyValue("NoPermisionToUseRemoteInterfaceUser", this.Site), Common.GetConfigurationPropertyValue("NoPermisionToUseRemoteInterfaceUserPwd", this.Site), this.Domain);
ExclusiveLockSubRequestType subRequest = SharedTestSuiteHelper.CreateExclusiveLockSubRequest(ExclusiveLockRequestTypes.GetLock);
CellStorageResponse response = this.Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { subRequest });
this.Site.Log.Add(
LogEntryKind.Debug,
"When the user {0} does not have permission to use remote service, the error code should be not null but actual {1}",
Common.GetConfigurationPropertyValue("NoPermisionToUseRemoteInterfaceUser", this.Site),
response.ResponseVersion.ErrorCodeSpecified ? "is not null" : "null");
if (SharedContext.Current.IsMsFsshttpRequirementsCaptured)
{
if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 15171, this.Site))
{
// Verify MS-FSSHTTP requirement: MS-FSSHTTP_R15171
Site.CaptureRequirementIfIsTrue(
response.ResponseVersion.ErrorCodeSpecified,
"MS-FSSHTTP",
15171,
@"[In ResponseVersion] This attribute[ErrorCode] MUST be present if any one of the following is true.
The user does not have permission to issue a cell storage service request to the file identified by the Url attribute of the Request element.");
// Verify MS-FSSHTTP requirement: MS-FSSHTTP_R359
Site.CaptureRequirementIfAreEqual<GenericErrorCodeTypes>(
GenericErrorCodeTypes.FileUnauthorizedAccess,
response.ResponseVersion.ErrorCode,
"MS-FSSHTTP",
359,
@"[In GenericErrorCodeTypes] FileUnauthorizedAccess indicates an error when the targeted URL for the file specified as part of the Request element does not have correct authorization.");
}
}
else
{
Site.Assert.IsTrue(
response.ResponseVersion.ErrorCodeSpecified,
@"[In ResponseVersion] This attribute[ErrorCode] MUST be present if any one of the following is true.
The user does not have permission to issue a cell storage service request to the file identified by the URL attribute of the Request element.");
Site.Assert.AreEqual<GenericErrorCodeTypes>(
GenericErrorCodeTypes.FileUnauthorizedAccess,
response.ResponseVersion.ErrorCode,
@"[In GenericErrorCodeTypes] FileUnauthorizedAccess indicates an error when the targeted URL for the file specified as part of the Request element does not have correct authorization.");
}
}
/// <summary>
/// A method used to test the ErrorCode value when getting an exclusive lock and the file URL is empty.
/// </summary>
[TestCategory("MSFSSHTTP_FSSHTTPB"), TestMethod()]
public void MSFSSHTTP_FSSHTTPB_S04_TC09_ExclusiveLock_EmptyUrl()
{
// Initialize the service
this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain);
ExclusiveLockSubRequestType subRequest = SharedTestSuiteHelper.CreateExclusiveLockSubRequest(ExclusiveLockRequestTypes.GetLock);
CellStorageResponse response = new CellStorageResponse();
bool isR3008Verified = false;
try
{
// Send a GetLock for exclusive subRequest to the protocol server with empty URL.
response = this.Adapter.CellStorageRequest(string.Empty, new SubRequestType[] { subRequest });
}
catch (System.Xml.XmlException exception)
{
string message = exception.Message;
isR3008Verified = message.Contains("Duplicate attribute");
isR3008Verified &= message.Contains("ErrorCode");
}
if (SharedContext.Current.IsMsFsshttpRequirementsCaptured)
{
// Verify MS-FSSHTTP requirement: MS-FSSHTTP_R3008
if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 3008, this.Site))
{
Site.Log.Add(
LogEntryKind.Debug,
"SharePoint server 2010 and SharePoint Foundation responses two ErrorCode attributes when the URL is empty string.");
Site.CaptureRequirementIfIsTrue(
isR3008Verified,
"MS-FSSHTTP",
3008,
@"[In Appendix B: Product Behavior] If the Url attribute of the corresponding Request element is an empty string, the implementation does return two ErrorCode attributes in Response element. <11> Section 2.2.3.5: SharePoint Server 2010 will return 2 ErrorCode attributes in Response element.");
}
// Verify MS-FSSHTTP requirement: MS-FSSHTTP_R3009
if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 3009, this.Site))
{
Site.CaptureRequirementIfIsNull(
response.ResponseCollection,
"MS-FSSHTTP",
3009,
@"[In Appendix B: Product Behavior] If the Url attribute of the corresponding Request element is an empty string, the implementation does not return Response element. <11> Section 2.2.3.5: SharePoint Server 2013 will not return Response element.");
}
}
else
{
if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 3008, this.Site))
{
Site.Log.Add(
LogEntryKind.Debug,
"SharePoint server 2010 and SharePoint Foundation responses two ErrorCode attributes when the URL is empty string.");
Site.Assert.IsTrue(
isR3008Verified,
"[In Appendix B: Product Behavior] If the URL attribute of the corresponding Request element is an empty string, the implementation does return two ErrorCode attributes in Response element. <3> Section 2.2.3.5: SharePoint Server 2010 will return 2 ErrorCode attributes in Response element.");
}
if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 3009, this.Site))
{
Site.Assert.IsNull(
response.ResponseCollection,
@"[In Appendix B: Product Behavior] If the Url attribute of the corresponding Request element is an empty string, the implementation does not return Response element. <8> Section 2.2.3.5: SharePoint Server 2013 will not return Response element.");
}
}
}
/// <summary>
/// Initialize the shared context based on the specified request file URL, user name, password and domain for the MS-FSSHTTP test purpose.
/// </summary>
/// <param name="requestFileUrl">Specify the request file URL.</param>
/// <param name="userName">Specify the user name.</param>
/// <param name="password">Specify the password.</param>
/// <param name="domain">Specify the domain.</param>
protected override void InitializeContext(string requestFileUrl, string userName, string password, string domain)
{
SharedContextUtils.InitializeSharedContextForFSSHTTP(userName, password, domain, this.Site);
}
/// <summary>
/// Merge the common configuration and should/may configuration file.
/// </summary>
/// <param name="site">An instance of interface ITestSite which provides logging, assertions,
/// and adapters for test code onto its execution context.</param>
protected override void MergeConfigurationFile(TestTools.ITestSite site)
{
ConfigurationFileHelper.MergeConfigurationFile(site);
}
}
}
| |
// 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.Tracing;
using System.Globalization;
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
namespace System.Net
{
//TODO: If localization resources are not found, logging does not work. Issue #5126.
[EventSource(Name = "Microsoft-System-Net-Security", LocalizationResources = "FxResources.System.Net.Security.SR")]
internal sealed partial class NetEventSource
{
private const int SecureChannelCtorId = NextAvailableEventId;
private const int LocatingPrivateKeyId = SecureChannelCtorId + 1;
private const int CertIsType2Id = LocatingPrivateKeyId + 1;
private const int FoundCertInStoreId = CertIsType2Id + 1;
private const int NotFoundCertInStoreId = FoundCertInStoreId + 1;
private const int RemoteCertificateId = NotFoundCertInStoreId + 1;
private const int CertificateFromDelegateId = RemoteCertificateId + 1;
private const int NoDelegateNoClientCertId = CertificateFromDelegateId + 1;
private const int NoDelegateButClientCertId = NoDelegateNoClientCertId + 1;
private const int AttemptingRestartUsingCertId = NoDelegateButClientCertId + 1;
private const int NoIssuersTryAllCertsId = AttemptingRestartUsingCertId + 1;
private const int LookForMatchingCertsId = NoIssuersTryAllCertsId + 1;
private const int SelectedCertId = LookForMatchingCertsId + 1;
private const int CertsAfterFilteringId = SelectedCertId + 1;
private const int FindingMatchingCertsId = CertsAfterFilteringId + 1;
private const int UsingCachedCredentialId = FindingMatchingCertsId + 1;
private const int SspiSelectedCipherSuitId = UsingCachedCredentialId + 1;
private const int RemoteCertificateErrorId = SspiSelectedCipherSuitId + 1;
private const int RemoteVertificateValidId = RemoteCertificateErrorId + 1;
private const int RemoteCertificateSuccesId = RemoteVertificateValidId + 1;
private const int RemoteCertificateInvalidId = RemoteCertificateSuccesId + 1;
[Event(EnumerateSecurityPackagesId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
public void EnumerateSecurityPackages(string securityPackage)
{
if (IsEnabled())
{
WriteEvent(EnumerateSecurityPackagesId, securityPackage ?? "");
}
}
[Event(SspiPackageNotFoundId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
public void SspiPackageNotFound(string packageName)
{
if (IsEnabled())
{
WriteEvent(SspiPackageNotFoundId, packageName ?? "");
}
}
[NonEvent]
public void SecureChannelCtor(SecureChannel secureChannel, string hostname, X509CertificateCollection clientCertificates, EncryptionPolicy encryptionPolicy)
{
if (IsEnabled())
{
SecureChannelCtor(hostname, GetHashCode(secureChannel), clientCertificates?.Count ?? 0, encryptionPolicy);
}
}
[Event(SecureChannelCtorId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
private unsafe void SecureChannelCtor(string hostname, int secureChannelHash, int clientCertificatesCount, EncryptionPolicy encryptionPolicy) =>
WriteEvent(SecureChannelCtorId, hostname, secureChannelHash, clientCertificatesCount, (int)encryptionPolicy);
[NonEvent]
public void LocatingPrivateKey(X509Certificate x509Certificate, SecureChannel secureChannel)
{
if (IsEnabled())
{
LocatingPrivateKey(x509Certificate.ToString(true), GetHashCode(secureChannel));
}
}
[Event(LocatingPrivateKeyId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
private void LocatingPrivateKey(string x509Certificate, int secureChannelHash) =>
WriteEvent(LocatingPrivateKeyId, x509Certificate, secureChannelHash);
[NonEvent]
public void CertIsType2(SecureChannel secureChannel)
{
if (IsEnabled())
{
CertIsType2(GetHashCode(secureChannel));
}
}
[Event(CertIsType2Id, Keywords = Keywords.Default, Level = EventLevel.Informational)]
private void CertIsType2(int secureChannelHash) =>
WriteEvent(CertIsType2Id, secureChannelHash);
[NonEvent]
public void FoundCertInStore(bool serverMode, SecureChannel secureChannel)
{
if (IsEnabled())
{
FoundCertInStore(serverMode ? "LocalMachine" : "CurrentUser", GetHashCode(secureChannel));
}
}
[Event(FoundCertInStoreId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
private void FoundCertInStore(string store, int secureChannelHash) =>
WriteEvent(FoundCertInStoreId, store, secureChannelHash);
[NonEvent]
public void NotFoundCertInStore(SecureChannel secureChannel)
{
if (IsEnabled())
{
NotFoundCertInStore(GetHashCode(secureChannel));
}
}
[Event(NotFoundCertInStoreId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
private void NotFoundCertInStore(int secureChannelHash) =>
WriteEvent(NotFoundCertInStoreId, secureChannelHash);
[NonEvent]
public void RemoteCertificate(X509Certificate remoteCertificate)
{
if (IsEnabled())
{
WriteEvent(RemoteCertificateId, remoteCertificate?.ToString(true));
}
}
[Event(RemoteCertificateId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
private void RemoteCertificate(string remoteCertificate) =>
WriteEvent(RemoteCertificateId, remoteCertificate);
[NonEvent]
public void CertificateFromDelegate(SecureChannel secureChannel)
{
if (IsEnabled())
{
CertificateFromDelegate(GetHashCode(secureChannel));
}
}
[Event(CertificateFromDelegateId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
private void CertificateFromDelegate(int secureChannelHash) =>
WriteEvent(CertificateFromDelegateId, secureChannelHash);
[NonEvent]
public void NoDelegateNoClientCert(SecureChannel secureChannel)
{
if (IsEnabled())
{
NoDelegateNoClientCert(GetHashCode(secureChannel));
}
}
[Event(NoDelegateNoClientCertId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
private void NoDelegateNoClientCert(int secureChannelHash) =>
WriteEvent(NoDelegateNoClientCertId, secureChannelHash);
[NonEvent]
public void NoDelegateButClientCert(SecureChannel secureChannel)
{
if (IsEnabled())
{
NoDelegateButClientCert(GetHashCode(secureChannel));
}
}
[Event(NoDelegateButClientCertId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
private void NoDelegateButClientCert(int secureChannelHash) =>
WriteEvent(NoDelegateButClientCertId, secureChannelHash);
[NonEvent]
public void AttemptingRestartUsingCert(X509Certificate clientCertificate, SecureChannel secureChannel)
{
if (IsEnabled())
{
AttemptingRestartUsingCert(clientCertificate?.ToString(true), GetHashCode(secureChannel));
}
}
[Event(AttemptingRestartUsingCertId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
private void AttemptingRestartUsingCert(string clientCertificate, int secureChannelHash) =>
WriteEvent(AttemptingRestartUsingCertId, clientCertificate, secureChannelHash);
[NonEvent]
public void NoIssuersTryAllCerts(SecureChannel secureChannel)
{
if (IsEnabled())
{
NoIssuersTryAllCerts(GetHashCode(secureChannel));
}
}
[Event(NoIssuersTryAllCertsId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
private void NoIssuersTryAllCerts(int secureChannelHash) =>
WriteEvent(NoIssuersTryAllCertsId, secureChannelHash);
[NonEvent]
public void LookForMatchingCerts(int issuersCount, SecureChannel secureChannel)
{
if (IsEnabled())
{
LookForMatchingCerts(issuersCount, GetHashCode(secureChannel));
}
}
[Event(LookForMatchingCertsId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
private void LookForMatchingCerts(int issuersCount, int secureChannelHash) =>
WriteEvent(LookForMatchingCertsId, issuersCount, secureChannelHash);
[NonEvent]
public void SelectedCert(X509Certificate clientCertificate, SecureChannel secureChannel)
{
if (IsEnabled())
{
SelectedCert(clientCertificate?.ToString(true), GetHashCode(secureChannel));
}
}
[Event(SelectedCertId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
private void SelectedCert(string clientCertificate, int secureChannelHash) =>
WriteEvent(SelectedCertId, clientCertificate, secureChannelHash);
[NonEvent]
public void CertsAfterFiltering(int filteredCertsCount, SecureChannel secureChannel)
{
if (IsEnabled())
{
CertsAfterFiltering(filteredCertsCount, GetHashCode(secureChannel));
}
}
[Event(CertsAfterFilteringId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
private void CertsAfterFiltering(int filteredCertsCount, int secureChannelHash) =>
WriteEvent(CertsAfterFilteringId, filteredCertsCount, secureChannelHash);
[NonEvent]
public void FindingMatchingCerts(SecureChannel secureChannel)
{
if (IsEnabled())
{
FindingMatchingCerts(GetHashCode(secureChannel));
}
}
[Event(FindingMatchingCertsId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
private void FindingMatchingCerts(int secureChannelHash) =>
WriteEvent(FindingMatchingCertsId, secureChannelHash);
[NonEvent]
public void UsingCachedCredential(SecureChannel secureChannel)
{
if (IsEnabled())
{
WriteEvent(UsingCachedCredentialId, GetHashCode(secureChannel));
}
}
[Event(UsingCachedCredentialId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
private void UsingCachedCredential(int secureChannelHash) =>
WriteEvent(UsingCachedCredentialId, secureChannelHash);
[Event(SspiSelectedCipherSuitId, Keywords = Keywords.Default, Level = EventLevel.Informational)]
public unsafe void SspiSelectedCipherSuite(
string process,
SslProtocols sslProtocol,
CipherAlgorithmType cipherAlgorithm,
int cipherStrength,
HashAlgorithmType hashAlgorithm,
int hashStrength,
ExchangeAlgorithmType keyExchangeAlgorithm,
int keyExchangeStrength)
{
if (IsEnabled())
{
WriteEvent(SspiSelectedCipherSuitId,
process, (int)sslProtocol, (int)cipherAlgorithm, cipherStrength,
(int)hashAlgorithm, hashStrength, (int)keyExchangeAlgorithm, keyExchangeStrength);
}
}
[NonEvent]
public void RemoteCertificateError(SecureChannel secureChannel, string message)
{
if (IsEnabled())
{
RemoteCertificateError(GetHashCode(secureChannel), message);
}
}
[Event(RemoteCertificateErrorId, Keywords = Keywords.Default, Level = EventLevel.Verbose)]
private void RemoteCertificateError(int secureChannelHash, string message) =>
WriteEvent(RemoteCertificateErrorId, secureChannelHash, message);
[NonEvent]
public void RemoteCertDeclaredValid(SecureChannel secureChannel)
{
if (IsEnabled())
{
RemoteCertDeclaredValid(GetHashCode(secureChannel));
}
}
[Event(RemoteVertificateValidId, Keywords = Keywords.Default, Level = EventLevel.Verbose)]
private void RemoteCertDeclaredValid(int secureChannelHash) =>
WriteEvent(RemoteVertificateValidId, secureChannelHash);
[NonEvent]
public void RemoteCertHasNoErrors(SecureChannel secureChannel)
{
if (IsEnabled())
{
RemoteCertHasNoErrors(GetHashCode(secureChannel));
}
}
[Event(RemoteCertificateSuccesId, Keywords = Keywords.Default, Level = EventLevel.Verbose)]
private void RemoteCertHasNoErrors(int secureChannelHash) =>
WriteEvent(RemoteCertificateSuccesId, secureChannelHash);
[NonEvent]
public void RemoteCertUserDeclaredInvalid(SecureChannel secureChannel)
{
if (IsEnabled())
{
RemoteCertUserDeclaredInvalid(GetHashCode(secureChannel));
}
}
[Event(RemoteCertificateInvalidId, Keywords = Keywords.Default, Level = EventLevel.Verbose)]
private void RemoteCertUserDeclaredInvalid(int secureChannelHash) =>
WriteEvent(RemoteCertificateInvalidId, secureChannelHash);
static partial void AdditionalCustomizedToString<T>(T value, ref string result)
{
X509Certificate cert = value as X509Certificate;
if (cert != null)
{
result = cert.ToString(fVerbose: true);
}
}
[NonEvent]
private unsafe void WriteEvent(int eventId, string arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8)
{
if (IsEnabled())
{
if (arg1 == null) arg1 = "";
fixed (char* arg1Ptr = arg1)
{
const int NumEventDatas = 8;
var descrs = stackalloc EventData[NumEventDatas];
descrs[0] = new EventData
{
DataPointer = (IntPtr)(arg1Ptr),
Size = (arg1.Length + 1) * sizeof(char)
};
descrs[1] = new EventData
{
DataPointer = (IntPtr)(&arg2),
Size = sizeof(int)
};
descrs[2] = new EventData
{
DataPointer = (IntPtr)(&arg3),
Size = sizeof(int)
};
descrs[3] = new EventData
{
DataPointer = (IntPtr)(&arg4),
Size = sizeof(int)
};
descrs[4] = new EventData
{
DataPointer = (IntPtr)(&arg5),
Size = sizeof(int)
};
descrs[5] = new EventData
{
DataPointer = (IntPtr)(&arg6),
Size = sizeof(int)
};
descrs[6] = new EventData
{
DataPointer = (IntPtr)(&arg7),
Size = sizeof(int)
};
descrs[7] = new EventData
{
DataPointer = (IntPtr)(&arg8),
Size = sizeof(int)
};
WriteEventCore(eventId, NumEventDatas, descrs);
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Runtime;
using System.Runtime.InteropServices;
namespace System.Management
{
public class QualifierDataCollection : ICollection, IEnumerable
{
private ManagementBaseObject parent;
private string propertyOrMethodName;
private QualifierType qualifierSetType;
public int Count
{
get
{
int num;
string[] strArrays = null;
try
{
IWbemQualifierSetFreeThreaded typeQualifierSet = this.GetTypeQualifierSet();
int names_ = typeQualifierSet.GetNames_(0, out strArrays);
if (names_ < 0)
{
if (((long)names_ & (long)-4096) != (long)-2147217408)
{
Marshal.ThrowExceptionForHR(names_);
}
else
{
ManagementException.ThrowWithExtendedInfo((ManagementStatus)names_);
}
}
return (int)strArrays.Length;
}
catch (ManagementException managementException1)
{
ManagementException managementException = managementException1;
if (this.qualifierSetType != QualifierType.PropertyQualifier || managementException.ErrorCode != ManagementStatus.SystemProperty)
{
throw;
}
else
{
num = 0;
}
}
return num;
}
}
public bool IsSynchronized
{
get
{
return false;
}
}
public virtual QualifierData this[string qualifierName]
{
get
{
if (qualifierName != null)
{
return new QualifierData(this.parent, this.propertyOrMethodName, qualifierName, this.qualifierSetType);
}
else
{
throw new ArgumentNullException("qualifierName");
}
}
}
public object SyncRoot
{
get
{
return this;
}
}
internal QualifierDataCollection(ManagementBaseObject parent)
{
this.parent = parent;
this.qualifierSetType = QualifierType.ObjectQualifier;
this.propertyOrMethodName = null;
}
internal QualifierDataCollection(ManagementBaseObject parent, string propertyOrMethodName, QualifierType type)
{
this.parent = parent;
this.propertyOrMethodName = propertyOrMethodName;
this.qualifierSetType = type;
}
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public virtual void Add(string qualifierName, object qualifierValue)
{
this.Add(qualifierName, qualifierValue, false, false, false, true);
}
public virtual void Add(string qualifierName, object qualifierValue, bool isAmended, bool propagatesToInstance, bool propagatesToSubclass, bool isOverridable)
{
int num = 0;
if (isAmended)
{
num = num | 128;
}
if (propagatesToInstance)
{
num = num | 1;
}
if (propagatesToSubclass)
{
num = num | 2;
}
if (!isOverridable)
{
num = num | 16;
}
int num1 = this.GetTypeQualifierSet().Put_(qualifierName, ref qualifierValue, num);
if (num1 < 0)
{
if (((long)num1 & (long)-4096) != (long)-2147217408)
{
Marshal.ThrowExceptionForHR(num1);
}
else
{
ManagementException.ThrowWithExtendedInfo((ManagementStatus)num1);
return;
}
}
}
public void CopyTo(Array array, int index)
{
IWbemQualifierSetFreeThreaded typeQualifierSet;
if (array != null)
{
if (index < array.GetLowerBound(0) || index > array.GetUpperBound(0))
{
throw new ArgumentOutOfRangeException("index");
}
else
{
string[] strArrays = null;
try
{
typeQualifierSet = this.GetTypeQualifierSet();
}
catch (ManagementException managementException1)
{
ManagementException managementException = managementException1;
if (this.qualifierSetType != QualifierType.PropertyQualifier || managementException.ErrorCode != ManagementStatus.SystemProperty)
{
throw;
}
else
{
return;
}
}
int names_ = typeQualifierSet.GetNames_(0, out strArrays);
if (names_ < 0)
{
if (((long)names_ & (long)-4096) != (long)-2147217408)
{
Marshal.ThrowExceptionForHR(names_);
}
else
{
ManagementException.ThrowWithExtendedInfo((ManagementStatus)names_);
}
}
if (index + (int)strArrays.Length <= array.Length)
{
string[] strArrays1 = strArrays;
for (int i = 0; i < (int)strArrays1.Length; i++)
{
string str = strArrays1[i];
int num = index;
index = num + 1;
array.SetValue(new QualifierData(this.parent, this.propertyOrMethodName, str, this.qualifierSetType), num);
}
}
else
{
throw new ArgumentException(null, "index");
}
return;
}
}
else
{
throw new ArgumentNullException("array");
}
}
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public void CopyTo(QualifierData[] qualifierArray, int index)
{
this.CopyTo(qualifierArray, index);
}
public QualifierDataCollection.QualifierDataEnumerator GetEnumerator()
{
return new QualifierDataCollection.QualifierDataEnumerator(this.parent, this.propertyOrMethodName, this.qualifierSetType);
}
private IWbemQualifierSetFreeThreaded GetTypeQualifierSet()
{
return this.GetTypeQualifierSet(this.qualifierSetType);
}
private IWbemQualifierSetFreeThreaded GetTypeQualifierSet(QualifierType qualifierSetType)
{
IWbemQualifierSetFreeThreaded wbemQualifierSetFreeThreaded = null;
int qualifierSet_ = 0;
QualifierType qualifierType = qualifierSetType;
if (qualifierType == QualifierType.ObjectQualifier)
{
qualifierSet_ = this.parent.wbemObject.GetQualifierSet_(out wbemQualifierSetFreeThreaded);
}
else if (qualifierType == QualifierType.PropertyQualifier)
{
qualifierSet_ = this.parent.wbemObject.GetPropertyQualifierSet_(this.propertyOrMethodName, out wbemQualifierSetFreeThreaded);
}
else if (qualifierType == QualifierType.MethodQualifier)
{
qualifierSet_ = this.parent.wbemObject.GetMethodQualifierSet_(this.propertyOrMethodName, out wbemQualifierSetFreeThreaded);
}
else
{
throw new ManagementException(ManagementStatus.Unexpected, null, null);
}
if (qualifierSet_ < 0)
{
if (((long)qualifierSet_ & (long)-4096) != (long)-2147217408)
{
Marshal.ThrowExceptionForHR(qualifierSet_);
}
else
{
ManagementException.ThrowWithExtendedInfo((ManagementStatus)qualifierSet_);
}
}
return wbemQualifierSetFreeThreaded;
}
public virtual void Remove(string qualifierName)
{
int num = this.GetTypeQualifierSet().Delete_(qualifierName);
if (num < 0)
{
if (((long)num & (long)-4096) != (long)-2147217408)
{
Marshal.ThrowExceptionForHR(num);
}
else
{
ManagementException.ThrowWithExtendedInfo((ManagementStatus)num);
return;
}
}
}
IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new QualifierDataCollection.QualifierDataEnumerator(this.parent, this.propertyOrMethodName, this.qualifierSetType);
}
public class QualifierDataEnumerator : IEnumerator
{
private ManagementBaseObject parent;
private string propertyOrMethodName;
private QualifierType qualifierType;
private string[] qualifierNames;
private int index;
public QualifierData Current
{
get
{
if (this.index == -1 || this.index == (int)this.qualifierNames.Length)
{
throw new InvalidOperationException();
}
else
{
return new QualifierData(this.parent, this.propertyOrMethodName, this.qualifierNames[this.index], this.qualifierType);
}
}
}
object System.Collections.IEnumerator.Current
{
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
get
{
return this.Current;
}
}
internal QualifierDataEnumerator(ManagementBaseObject parent, string propertyOrMethodName, QualifierType qualifierType)
{
this.index = -1;
this.parent = parent;
this.propertyOrMethodName = propertyOrMethodName;
this.qualifierType = qualifierType;
this.qualifierNames = null;
IWbemQualifierSetFreeThreaded wbemQualifierSetFreeThreaded = null;
int qualifierSet_ = 0;
QualifierType qualifierType1 = qualifierType;
if (qualifierType1 == QualifierType.ObjectQualifier)
{
qualifierSet_ = parent.wbemObject.GetQualifierSet_(out wbemQualifierSetFreeThreaded);
}
else if (qualifierType1 == QualifierType.PropertyQualifier)
{
qualifierSet_ = parent.wbemObject.GetPropertyQualifierSet_(propertyOrMethodName, out wbemQualifierSetFreeThreaded);
}
else if (qualifierType1 == QualifierType.MethodQualifier)
{
qualifierSet_ = parent.wbemObject.GetMethodQualifierSet_(propertyOrMethodName, out wbemQualifierSetFreeThreaded);
}
else
{
throw new ManagementException(ManagementStatus.Unexpected, null, null);
}
if (qualifierSet_ >= 0)
{
qualifierSet_ = wbemQualifierSetFreeThreaded.GetNames_(0, out this.qualifierNames);
if (qualifierSet_ < 0)
{
if (((long)qualifierSet_ & (long)-4096) != (long)-2147217408)
{
Marshal.ThrowExceptionForHR(qualifierSet_);
}
else
{
ManagementException.ThrowWithExtendedInfo((ManagementStatus)qualifierSet_);
return;
}
}
return;
}
else
{
this.qualifierNames = new string[0];
return;
}
}
public bool MoveNext()
{
if (this.index != (int)this.qualifierNames.Length)
{
QualifierDataCollection.QualifierDataEnumerator qualifierDataEnumerator = this;
qualifierDataEnumerator.index = qualifierDataEnumerator.index + 1;
if (this.index == (int)this.qualifierNames.Length)
{
return false;
}
else
{
return true;
}
}
else
{
return false;
}
}
public void Reset()
{
this.index = -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 global::System;
using global::System.Reflection;
using System.Reflection.Runtime.Assemblies;
using global::System.Collections.Generic;
using global::Internal.Metadata.NativeFormat;
using Debug = System.Diagnostics.Debug;
using AssemblyFlags = Internal.Metadata.NativeFormat.AssemblyFlags;
namespace Internal.Runtime.TypeLoader
{
public static class MetadataReaderHelpers
{
public static bool CompareTypeReferenceAcrossModules(TypeReferenceHandle tr1, MetadataReader mr1, TypeReferenceHandle tr2, MetadataReader mr2)
{
TypeReference trData1 = mr1.GetTypeReference(tr1);
TypeReference trData2 = mr2.GetTypeReference(tr2);
if (!trData1.TypeName.StringEquals(trData2.TypeName.GetConstantStringValue(mr2).Value, mr1))
return false;
if (trData1.ParentNamespaceOrType.HandleType != trData2.ParentNamespaceOrType.HandleType)
return false;
if (trData1.ParentNamespaceOrType.HandleType == HandleType.TypeReference)
return CompareTypeReferenceAcrossModules(trData1.ParentNamespaceOrType.ToTypeReferenceHandle(mr1), mr1, trData2.ParentNamespaceOrType.ToTypeReferenceHandle(mr2), mr2);
return CompareNamespaceReferenceAcrossModules(trData1.ParentNamespaceOrType.ToNamespaceReferenceHandle(mr1), mr1, trData2.ParentNamespaceOrType.ToNamespaceReferenceHandle(mr2), mr2);
}
public static bool CompareNamespaceReferenceAcrossModules(NamespaceReferenceHandle nr1, MetadataReader mr1, NamespaceReferenceHandle nr2, MetadataReader mr2)
{
NamespaceReference nrData1 = mr1.GetNamespaceReference(nr1);
NamespaceReference nrData2 = mr2.GetNamespaceReference(nr2);
if (nrData1.Name.IsNull(mr1) != nrData2.Name.IsNull(mr2))
return false;
if (!nrData1.Name.IsNull(mr1))
{
if (!nrData1.Name.StringEquals(nrData2.Name.GetConstantStringValue(mr2).Value, mr1))
return false;
}
if (nrData1.ParentScopeOrNamespace.HandleType != nrData1.ParentScopeOrNamespace.HandleType)
return false;
if (nrData1.ParentScopeOrNamespace.HandleType == HandleType.NamespaceReference)
return CompareNamespaceReferenceAcrossModules(nrData1.ParentScopeOrNamespace.ToNamespaceReferenceHandle(mr1), mr1, nrData2.ParentScopeOrNamespace.ToNamespaceReferenceHandle(mr2), mr2);
return CompareScopeReferenceAcrossModules(nrData1.ParentScopeOrNamespace.ToScopeReferenceHandle(mr1), mr1, nrData2.ParentScopeOrNamespace.ToScopeReferenceHandle(mr2), mr2);
}
public static bool CompareScopeReferenceAcrossModules(ScopeReferenceHandle sr1, MetadataReader mr1, ScopeReferenceHandle sr2, MetadataReader mr2)
{
ScopeReference srData1 = mr1.GetScopeReference(sr1);
ScopeReference srData2 = mr2.GetScopeReference(sr2);
if (!srData1.Name.StringEquals(srData2.Name.GetConstantStringValue(mr2).Value, mr1))
return false;
if (!srData1.Culture.StringEquals(srData2.Culture.GetConstantStringValue(mr2).Value, mr1))
return false;
if (srData1.MajorVersion != srData2.MajorVersion)
return false;
if (srData1.MinorVersion != srData2.MinorVersion)
return false;
if (srData1.RevisionNumber != srData2.RevisionNumber)
return false;
if (srData1.BuildNumber != srData2.BuildNumber)
return false;
return ComparePublicKeyOrTokens(srData1.PublicKeyOrToken, srData1.Flags.HasFlag(AssemblyFlags.PublicKey), srData2.PublicKeyOrToken, srData2.Flags.HasFlag(AssemblyFlags.PublicKey));
}
public static bool CompareTypeReferenceToDefinition(TypeReferenceHandle tr1, MetadataReader mr1, TypeDefinitionHandle td2, MetadataReader mr2)
{
// TODO! The correct implementation here is probably to call into the assembly binder, but that's not available due to layering.
// For now, just implement comparison, which will be equivalent in all cases until we support loading multiple copies of the same assembly
TypeReference trData1 = mr1.GetTypeReference(tr1);
TypeDefinition tdData2 = mr2.GetTypeDefinition(td2);
if (!trData1.TypeName.StringEquals(tdData2.Name.GetConstantStringValue(mr2).Value, mr1))
return false;
switch (trData1.ParentNamespaceOrType.HandleType)
{
case HandleType.TypeReference:
if (tdData2.EnclosingType.IsNull(mr2))
return false;
return CompareTypeReferenceToDefinition(trData1.ParentNamespaceOrType.ToTypeReferenceHandle(mr1), mr1, tdData2.EnclosingType, mr2);
case HandleType.NamespaceReference:
return CompareNamespaceReferenceToDefinition(trData1.ParentNamespaceOrType.ToNamespaceReferenceHandle(mr1), mr1, tdData2.NamespaceDefinition, mr2);
default:
Debug.Assert(false);
throw new BadImageFormatException();
}
}
public static bool CompareNamespaceReferenceToDefinition(NamespaceReferenceHandle nr1, MetadataReader mr1, NamespaceDefinitionHandle nd2, MetadataReader mr2)
{
NamespaceReference nrData1 = mr1.GetNamespaceReference(nr1);
NamespaceDefinition ndData2 = mr2.GetNamespaceDefinition(nd2);
if (nrData1.Name.IsNull(mr1) != ndData2.Name.IsNull(mr2))
return false;
if (!nrData1.Name.IsNull(mr1))
{
if (!nrData1.Name.StringEquals(ndData2.Name.GetConstantStringValue(mr2).Value, mr1))
return false;
}
switch (nrData1.ParentScopeOrNamespace.HandleType)
{
case HandleType.NamespaceReference:
if (ndData2.ParentScopeOrNamespace.HandleType != HandleType.NamespaceDefinition)
return false;
return CompareNamespaceReferenceToDefinition(nrData1.ParentScopeOrNamespace.ToNamespaceReferenceHandle(mr1), mr1, ndData2.ParentScopeOrNamespace.ToNamespaceDefinitionHandle(mr2), mr2);
case HandleType.ScopeReference:
if (ndData2.ParentScopeOrNamespace.HandleType != HandleType.ScopeDefinition)
return false;
return CompareScopeReferenceToDefinition(nrData1.ParentScopeOrNamespace.ToScopeReferenceHandle(mr1), mr1, ndData2.ParentScopeOrNamespace.ToScopeDefinitionHandle(mr2), mr2);
default:
Debug.Assert(false);
throw new BadImageFormatException();
}
}
public static bool CompareScopeReferenceToDefinition(ScopeReferenceHandle sr1, MetadataReader mr1, ScopeDefinitionHandle sd2, MetadataReader mr2)
{
ScopeReference srData1 = mr1.GetScopeReference(sr1);
ScopeDefinition sdData2 = mr2.GetScopeDefinition(sd2);
if (!srData1.Name.StringEquals(sdData2.Name.GetConstantStringValue(mr2).Value, mr1))
return false;
if (!srData1.Culture.StringEquals(sdData2.Culture.GetConstantStringValue(mr2).Value, mr1))
return false;
if (srData1.MajorVersion != sdData2.MajorVersion)
return false;
if (srData1.MinorVersion != sdData2.MinorVersion)
return false;
if (srData1.RevisionNumber != sdData2.RevisionNumber)
return false;
if (srData1.BuildNumber != sdData2.BuildNumber)
return false;
return ComparePublicKeyOrTokens(srData1.PublicKeyOrToken, srData1.Flags.HasFlag(AssemblyFlags.PublicKey), sdData2.PublicKey, sdData2.Flags.HasFlag(AssemblyFlags.PublicKey));
}
public static bool ComparePublicKeyOrTokens(ByteCollection keyOrToken1, bool isKey1, ByteCollection keyOrToken2, bool isKey2)
{
if (isKey1 != isKey2)
{
// Convert both to PublicKeyToken byte[] and compare
byte[] token1 = ConvertByteCollectionKeyOrTokenToPublicKeyTokenByteArray(keyOrToken1, isKey1);
byte[] token2 = ConvertByteCollectionKeyOrTokenToPublicKeyTokenByteArray(keyOrToken2, isKey2);
if (token1.Length != token2.Length)
return false;
for (int i = 0; i < token1.Length; i++)
{
if (token1[i] != token2[i])
return false;
}
return true;
}
var enum1 = keyOrToken1.GetEnumerator();
var enum2 = keyOrToken1.GetEnumerator();
while (true)
{
bool moveNext1 = enum1.MoveNext();
if (enum2.MoveNext() != moveNext1)
return false;
if (moveNext1 == false)
break;
if (enum1.Current != enum2.Current)
return false;
}
return true;
}
private static byte[] ConvertByteCollectionOfPublicKeyToByteArrayOfPublicKeyToken(ByteCollection publicKeyCollection)
{
byte[] publicKey = Internal.TypeSystem.NativeFormat.MetadataExtensions.ConvertByteCollectionToArray(publicKeyCollection);
return AssemblyNameHelpers.ComputePublicKeyToken(publicKey);
}
private static byte[] ConvertByteCollectionKeyOrTokenToPublicKeyTokenByteArray(ByteCollection publicKeyOrToken, bool isKey)
{
if (isKey)
return ConvertByteCollectionOfPublicKeyToByteArrayOfPublicKeyToken(publicKeyOrToken);
else
return Internal.TypeSystem.NativeFormat.MetadataExtensions.ConvertByteCollectionToArray(publicKeyOrToken);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using DeOps.Implementation;
using DeOps.Implementation.Dht;
using DeOps.Implementation.Protocol;
using DeOps.Implementation.Protocol.Net;
using DeOps.Implementation.Transport;
using DeOps.Services.Assist;
using DeOps.Services.Trust;
using DeOps.Services.Location;
using DeOps.Services.Share;
using NLipsum.Core;
namespace DeOps.Services.Chat
{
public delegate void RefreshHandler();
public class ChatService : OpService
{
public string Name { get { return "Chat"; } }
public uint ServiceID { get { return (uint)ServiceIDs.Chat; } }
public OpCore Core;
public DhtNetwork Network;
public TrustService Trust;
public ThreadedDictionary<ulong, ChatRoom> RoomMap = new ThreadedDictionary<ulong, ChatRoom>();
public Dictionary<ulong, bool> StatusUpdate = new Dictionary<ulong, bool>();
public RefreshHandler Refresh;
bool ChatNewsUpdate;
const uint DataTypeLocation = 0x02;
TempCache TempLocation;
public delegate void NewInviteHandler(ulong userID, ChatRoom room);
public NewInviteHandler NewInvite;
public ChatService(OpCore core)
{
Core = core;
Network = Core.Network;
Trust = core.Trust;
Network.RudpControl.SessionUpdate += new SessionUpdateHandler(Session_Update);
Network.RudpControl.SessionData[ServiceID, 0] += new SessionDataHandler(Session_Data);
Network.RudpControl.KeepActive += new KeepActiveHandler(Session_KeepActive);
Core.SecondTimerEvent += Core_SecondTimer;
Core.KeepDataCore += new KeepDataHandler(Core_KeepData);
Core.Locations.KnowOnline += new KnowOnlineHandler(Location_KnowOnline);
Core.Locations.LocationUpdate += new LocationUpdateHandler(Location_Update);
if (Trust != null)
{
Trust.LinkUpdate += new LinkUpdateHandler(Link_Update);
Link_Update(Trust.LocalTrust);
}
TempLocation = new TempCache(Network, ServiceID, DataTypeLocation);
}
public void Dispose()
{
if (Refresh != null)
throw new Exception("Chat Events not fin'd");
Network.RudpControl.SessionUpdate -= new SessionUpdateHandler(Session_Update);
Network.RudpControl.SessionData[ServiceID, 0] -= new SessionDataHandler(Session_Data);
Network.RudpControl.KeepActive -= new KeepActiveHandler(Session_KeepActive);
Core.SecondTimerEvent -= Core_SecondTimer;
Core.KeepDataCore -= new KeepDataHandler(Core_KeepData);
Core.Locations.KnowOnline -= new KnowOnlineHandler(Location_KnowOnline);
Core.Locations.LocationUpdate -= new LocationUpdateHandler(Location_Update);
if(Trust != null)
Trust.LinkUpdate -= new LinkUpdateHandler(Link_Update);
TempLocation.Dispose();
}
void Core_KeepData()
{
ForAllUsers(id => Core.KeepData.SafeAdd(id, true));
}
void Location_KnowOnline(List<ulong> users)
{
ForAllUsers(delegate(ulong id)
{
if (!users.Contains(id))
users.Add(id);
});
}
void ForAllUsers(Action<ulong> action)
{
RoomMap.LockReading(delegate()
{
foreach (ChatRoom room in RoomMap.Values)
if (room.Active && !IsCommandRoom(room.Kind))
{
room.Members.LockReading(delegate()
{
foreach (ulong id in room.Members)
action(id);
});
if (room.Invites != null)
foreach (ulong id in room.Invites.Keys)
action(id);
if (room.Verified != null)
foreach (ulong id in room.Verified.Keys)
action(id);
}
});
}
void Core_SecondTimer()
{
// send status upates once per second so we're not sending multiple updates to the same client more than
// once per second
foreach (ulong key in StatusUpdate.Keys)
foreach (RudpSession session in Network.RudpControl.GetActiveSessions(key))
SendStatus(session);
StatusUpdate.Clear();
// publish room location for public rooms hourly
RoomMap.LockReading(delegate()
{
foreach (ChatRoom room in RoomMap.Values)
if (room.Active && room.PublishRoom && Core.TimeNow > room.NextPublish)
{
TempLocation.Publish(room.RoomID, Core.Locations.LocalClient.Data.EncodeLight(Network.Protocol));
room.NextPublish = Core.TimeNow.AddHours(1);
}
});
// for sim test write random msg ever 10 secs
if (Core.Sim != null && SimTextActive && Core.RndGen.Next(10) == 0)
{
List<ChatRoom> rooms = new List<ChatRoom>();
RoomMap.LockReading(delegate()
{
foreach (ChatRoom room in RoomMap.Values)
if (room.Active)
rooms.Add(room);
});
if (rooms.Count > 0)
SendMessage(rooms[Core.RndGen.Next(rooms.Count)], Core.TextGen.GenerateSentences(1, Sentence.Short)[0], TextFormat.Plain);
}
}
bool SimTextActive = false;
public void SimTest()
{
SimTextActive = !SimTextActive;
}
public void SimCleanup()
{
}
public void Link_Update(OpTrust trust)
{
// update command/live rooms
Trust.ProjectRoots.LockReading(delegate()
{
foreach (uint project in Trust.ProjectRoots.Keys)
{
OpLink localLink = Trust.LocalTrust.GetLink(project);
OpLink remoteLink = trust.GetLink(project);
if (localLink == null || remoteLink == null)
continue;
OpLink uplink = localLink.GetHigher(true);
List<OpLink> downlinks = localLink.GetLowers(true);
// if local link updating
if (trust == Trust.LocalTrust)
{
// if we are in the project
if (localLink.Active)
{
JoinCommand(project, RoomKind.Command_High);
JoinCommand(project, RoomKind.Command_Low);
JoinCommand(project, RoomKind.Live_High);
JoinCommand(project, RoomKind.Live_Low);
}
// else leave any command/live rooms for this project
else
{
LeaveRooms(project);
}
}
// else if remote user updating
else
{
if(uplink != null)
if (uplink.Trust == trust || uplink.GetLowers(true).Contains(remoteLink))
{
RefreshCommand(project, RoomKind.Command_High);
RefreshCommand(project, RoomKind.Live_High);
}
if (downlinks.Contains(remoteLink))
{
RefreshCommand(project, RoomKind.Command_Low);
RefreshCommand(project, RoomKind.Live_Low);
}
}
Core.RunInGuiThread(Refresh);
}
});
// refresh member list of any commmand/live room this person is apart of
// link would already be added above, this ensures user is removed
foreach(ChatRoom room in FindRoom(trust.UserID))
if(IsCommandRoom(room.Kind))
RefreshCommand(room);
else if(room.Members.SafeContains(trust.UserID))
Core.RunInGuiThread(room.MembersUpdate);
}
public ChatRoom CreateRoom(string name, RoomKind kind)
{
ulong id = Utilities.RandUInt64(Core.RndGen);
if (kind == RoomKind.Public)
id = ChatService.GetPublicRoomID(name);
ChatRoom room = new ChatRoom(kind, id, name);
room.Active = true;
room.AddMember(Core.UserID);
RoomMap.SafeAdd(id, room);
if (kind == RoomKind.Secret)
{
room.Host = Core.UserID;
room.Verified[Core.UserID] = true;
SendInviteRequest(room, Core.UserID); // send invite to copies of ourself that exist
}
Core.RunInGuiThread(Refresh);
if (room.PublishRoom)
SetupPublic(room);
return room;
}
private void SetupPublic(ChatRoom room)
{
if (Core.InvokeRequired)
{
Core.RunInCoreAsync(() => SetupPublic(room));
return;
}
room.NextPublish = Core.TimeNow ;
TempLocation.Search(room.RoomID, room, Search_FoundRoom);
}
void Search_FoundRoom(byte[] data, object arg)
{
ChatRoom room = arg as ChatRoom;
if (!room.Active)
return;
// add locations to running transfer
LocationData loc = LocationData.Decode(data);
DhtClient client = new DhtClient(loc.UserID, loc.Source.ClientID);
Core.Network.LightComm.Update(loc);
if (!room.Members.SafeContains(client.UserID))
{
room.AddMember(client.UserID);
Core.Locations.Research(client.UserID);
}
// connect to new members
ConnectRoom(room);
}
public void JoinRoom(ChatRoom room)
{
if (Core.InvokeRequired)
{
Core.RunInCoreAsync(() => JoinRoom(room));
return;
}
if ( IsCommandRoom(room.Kind))
{
JoinCommand(room.ProjectID, room.Kind);
return;
}
room.Active = true;
room.AddMember(Core.UserID);
// for private rooms, send proof of invite first
if (room.Kind == RoomKind.Secret)
SendInviteProof(room);
SendStatus(room);
SendWhoRequest(room);
ConnectRoom(room);
if (room.PublishRoom)
SetupPublic(room);
Core.RunInGuiThread(Refresh);
Core.RunInGuiThread(room.MembersUpdate);
}
public void JoinCommand(uint project, RoomKind kind)
{
uint id = GetRoomID(project, kind);
// create if doesnt exist
ChatRoom room = null;
if (!RoomMap.SafeTryGetValue(id, out room))
room = new ChatRoom(kind, project);
room.Active = true;
room.AddMember(Core.UserID);
RoomMap.SafeAdd(id, room);
RefreshCommand(room);
SendStatus(room);
ConnectRoom(room);
}
private void ConnectRoom(ChatRoom room)
{
room.Members.LockReading(delegate()
{
foreach (ulong key in room.Members)
{
List<ClientInfo> clients = Core.Locations.GetClients(key);
if(clients.Count == 0)
Core.Locations.Research(key);
else
foreach (ClientInfo info in clients)
Network.RudpControl.Connect(info.Data);
if (Trust != null && Trust.GetTrust(key) == null)
Trust.Research(key, 0, false);
}
});
}
void RefreshCommand(uint project, RoomKind kind)
{
uint id = GetRoomID(project, kind);
ChatRoom room = null;
if (RoomMap.SafeTryGetValue(id, out room))
RefreshCommand(room);
}
public void RefreshCommand(ChatRoom room) // sends status updates to all members of room
{
if (!IsCommandRoom(room.Kind))
{
Debug.Assert(false);
return;
}
// remember connection status from before
// nodes we arent connected to do try connect
// if socket already active send status request
OpLink localLink = Trust.LocalTrust.GetLink(room.ProjectID);
if (localLink == null)
return;
OpLink uplink = localLink.GetHigher(true);
// updates room's member list
if (room.Kind == RoomKind.Command_High)
{
room.Members = new ThreadedList<ulong>();
if (uplink != null)
{
if (localLink.LoopRoot != null)
{
uplink = localLink.LoopRoot;
room.Host = uplink.UserID; // use loop id cause 0 is reserved for no root
room.IsLoop = true;
}
else
{
room.Host = uplink.UserID;
room.IsLoop = false;
room.AddMember(room.Host);
}
foreach (OpLink downlink in uplink.GetLowers(true))
room.AddMember(downlink.UserID);
}
}
else if (room.Kind == RoomKind.Command_Low)
{
room.Members = new ThreadedList<ulong>();
room.Host = Core.UserID;
room.AddMember(room.Host);
foreach (OpLink downlink in localLink.GetLowers(true))
room.AddMember(downlink.UserID);
}
else if (room.Kind == RoomKind.Live_High)
{
// find highest thats online and make that the host,
// if host changes, clear members
// higher should send live lowers which members are conneted to it so everyone can sync up
// location update should trigger a refresh of the live rooms
}
else if (room.Kind == RoomKind.Live_Low)
{
// just add self, dont remove members
}
// update dispaly that members has been refreshed
Core.RunInGuiThread(room.MembersUpdate);
}
void LeaveRooms(uint project)
{
LeaveRoom(project, RoomKind.Command_High);
LeaveRoom(project, RoomKind.Command_Low);
LeaveRoom(project, RoomKind.Live_High);
LeaveRoom(project, RoomKind.Live_Low);
}
public void LeaveRoom(uint project, RoomKind kind)
{
// deactivates room, let timer remove object is good once we know user no longer wants it
uint id = GetRoomID(project, kind);
ChatRoom room = null;
if (!RoomMap.SafeTryGetValue(id, out room))
return;
LeaveRoom(room);
}
public void LeaveRoom(ChatRoom room)
{
room.Active = false;
room.RemoveMember(Core.UserID);
SendStatus(room);
//update interface
Core.RunInGuiThread(Refresh);
Core.RunInGuiThread(room.MembersUpdate);
}
public static bool IsCommandRoom(RoomKind kind)
{
return (kind == RoomKind.Command_High || kind == RoomKind.Command_Low ||
kind == RoomKind.Live_High || kind == RoomKind.Live_Low);
}
public uint GetRoomID(uint project, RoomKind kind)
{
return project + (uint)kind;
}
public ChatRoom GetRoom(uint project, RoomKind kind)
{
ChatRoom room = null;
if(RoomMap.TryGetValue(GetRoomID(project, kind), out room))
return room;
return null;
}
private List<ChatRoom> FindRoom(ulong key)
{
List<ChatRoom> results = new List<ChatRoom>();
RoomMap.LockReading(delegate()
{
foreach (ChatRoom room in RoomMap.Values)
if(room.Members.SafeContains(key))
results.Add(room);
});
return results;
}
public void Location_Update(LocationData location)
{
bool connect = false;
foreach (ChatRoom room in FindRoom(location.UserID))
if (room.Active)
connect = true;
if(connect)
Network.RudpControl.Connect(location); // func checks if already connected
}
public void SendMessage(ChatRoom room, string text, TextFormat format)
{
if (Core.InvokeRequired)
{
Core.RunInCoreAsync(delegate() { SendMessage(room, text, format); });
return;
}
bool sent = false;
if (room.Active)
{
ChatText message = new ChatText();
message.ProjectID = room.ProjectID;
message.Kind = room.Kind;
message.RoomID = room.RoomID;
message.Text = text;
message.Format = format;
room.Members.LockReading(delegate()
{
// also sends to other instances of self
foreach (ulong member in room.Members)
foreach (RudpSession session in Network.RudpControl.GetActiveSessions(member))
{
sent = true;
session.SendData(ServiceID, 0, message);
}
});
}
ProcessMessage(room, new ChatMessage(Core, text, format) { Sent = sent });
//if (!sent)
// ProcessMessage(room, "Could not send message, not connected to anyone");
}
private void ReceiveMessage(ChatText message, RudpSession session)
{
if (Core.Buddies.IgnoreList.SafeContainsKey(session.UserID))
return;
// remote's command low, is my command high
// do here otherwise have to send custom roomID packets to selfs/lowers/highers
if (Trust != null && session.UserID != Core.UserID)
{
// if check fails then it is loop node sending data, keep it unchanged
if (message.Kind == RoomKind.Command_High && Trust.IsLowerDirect(session.UserID, message.ProjectID))
message.Kind = RoomKind.Command_Low;
else if (message.Kind == RoomKind.Command_Low && Trust.IsHigher(session.UserID, message.ProjectID))
message.Kind = RoomKind.Command_High;
else if (message.Kind == RoomKind.Live_High)
message.Kind = RoomKind.Live_Low;
else if (message.Kind == RoomKind.Live_Low)
message.Kind = RoomKind.Live_High;
}
ulong id = IsCommandRoom(message.Kind) ? GetRoomID(message.ProjectID, message.Kind) : message.RoomID;
ChatRoom room = null;
// if not in room let remote user know
if (!RoomMap.TryGetValue(id, out room) ||
!room.Active )
{
SendStatus(session);
return;
}
// if sender not in room
if(!room.Members.SafeContains(session.UserID))
return;
if (!ChatNewsUpdate)
{
ChatNewsUpdate = true;
Core.MakeNews(ServiceIDs.Chat, Core.GetName(session.UserID) + " is chatting", session.UserID, 0, false);
}
ProcessMessage(room, new ChatMessage(Core, session, message));
}
public void Session_Update(RudpSession session)
{
// send node rooms that we have in common
if (session.Status == SessionStatus.Active)
{
// send invites
RoomMap.LockReading(delegate()
{
// if we are host of room and connect hasn't been sent invite
foreach (ChatRoom room in RoomMap.Values)
{
if (room.NeedSendInvite(session.UserID, session.ClientID))
// invite not sent
if (room.Kind == RoomKind.Private || room.Host == Core.UserID)
{
session.SendData(ServiceID, 0, room.Invites[session.UserID].Param1);
room.Invites[session.UserID].Param2.Add(session.ClientID);
ProcessMessage(room, "Invite sent to " + GetNameAndLocation(session));
SendWhoResponse(room, session);
}
// else private room and we are not the host, send proof we belong here
else
{
SendInviteProof(room, session);
}
// ask member who else is in room
if (!IsCommandRoom(room.Kind) &&
room.Members.SafeContains(session.UserID))
SendWhoRequest(room, session);
}
});
SendStatus(session);
}
// if disconnected
if (session.Status == SessionStatus.Closed)
foreach (ChatRoom room in FindRoom(session.UserID))
if (room.Active)
// don't remove from members unless explicitly told in status
Core.RunInGuiThread(room.MembersUpdate);
}
void Session_Data(RudpSession session, byte[] data)
{
G2Header root = new G2Header(data);
if (G2Protocol.ReadPacket(root))
{
switch (root.Name)
{
case ChatPacket.Data:
ReceiveMessage(ChatText.Decode(root), session);
break;
case ChatPacket.Status:
ReceiveStatus(ChatStatus.Decode(root), session);
break;
case ChatPacket.Invite:
ReceiveInvite(ChatInvite.Decode(root), session);
break;
case ChatPacket.Who:
ReceiveWho(ChatWho.Decode(root), session);
break;
}
}
}
void Session_KeepActive(Dictionary<ulong, bool> active)
{
RoomMap.LockReading(delegate()
{
foreach (ChatRoom room in RoomMap.Values)
if(room.Active)
room.Members.LockReading(delegate()
{
foreach (ulong member in room.Members)
active[member] = true;
});
});
}
// system message
private void ProcessMessage(ChatRoom room, string text)
{
ProcessMessage(room, new ChatMessage(Core, text, TextFormat.Plain) { System = true });
}
private void ProcessMessage(ChatRoom room, ChatMessage message)
{
room.Log.SafeAdd(message);
// ask user here if invite to room
Core.RunInGuiThread(room.ChatUpdate, message);
}
void ReceiveStatus(ChatStatus status, RudpSession session)
{
// status is what nodes send to each other to tell what rooms they are active in
RoomMap.LockReading(delegate()
{
foreach (ChatRoom room in RoomMap.Values)
{
bool update = false;
// remove from room
if (!status.ActiveRooms.Contains(room.RoomID) && room.Members.SafeContains(session.UserID))
{
if (!IsCommandRoom(room.Kind))
{
if (room.Members.SafeContains(session.UserID))
ProcessMessage(room, GetNameAndLocation(session) + " left the room");
room.RemoveMember(session.UserID);
}
update = true;
}
// add member to room
if (IsCommandRoom(room.Kind) && room.Members.SafeContains(session.UserID))
update = true;
else if (status.ActiveRooms.Contains(room.RoomID))
{
// if room private check that sender is verified
if (room.Kind == RoomKind.Secret && !room.Verified.ContainsKey(session.UserID))
continue;
if (!room.Members.SafeContains(session.UserID))
ProcessMessage(room, GetNameAndLocation(session) + " joined the room");
room.AddMember(session.UserID);
update = true;
}
if (update)
Core.RunInGuiThread(room.MembersUpdate);
}
});
}
void SendStatus(ChatRoom room)
{
room.Members.LockReading(delegate()
{
foreach (ulong id in room.Members)
StatusUpdate[id] = true;
});
}
private void SendStatus(RudpSession session)
{
// send even if empty so they know to remove us
ChatStatus status = new ChatStatus();
RoomMap.LockReading(delegate()
{
foreach (ChatRoom room in RoomMap.Values)
if (room.Active && !IsCommandRoom(room.Kind))
{
if (room.Kind == RoomKind.Secret && !room.Verified.ContainsKey(session.UserID))
continue;
status.ActiveRooms.Add(room.RoomID);
}
});
session.SendData(ServiceID, 0, status);
}
public void SendInviteRequest(ChatRoom room, ulong id)
{
if (Core.InvokeRequired)
{
Core.RunInCoreAsync(delegate() { SendInviteRequest(room, id); });
return;
}
room.AddMember(id);
ChatInvite invite = null;
// if user explicitly chooses to invite users, invalidate previous recorded attempts
invite = new ChatInvite();
invite.RoomID = room.RoomID;
invite.Title = room.Title;
// if private room sign remote users id with our private key
if (room.Kind == RoomKind.Secret)
{
invite.Host = Core.KeyMap[Core.UserID];
if (!Core.KeyMap.ContainsKey(id))
return;
invite.SignedInvite = Core.User.Settings.KeyPair.SignData(Core.KeyMap[id], new SHA1CryptoServiceProvider());
room.Verified[id] = true;
}
room.Invites[id] = new Tuple<ChatInvite, List<ushort>>(invite, new List<ushort>());
// try to conncet to all of id's locations
foreach (ClientInfo loc in Core.Locations.GetClients(id))
Network.RudpControl.Connect(loc.Data);
// send invite to already connected locations
foreach (RudpSession session in Network.RudpControl.GetActiveSessions(id))
{
session.SendData(ServiceID, 0, invite);
room.Invites[id].Param2.Add(session.ClientID);
ProcessMessage(room, "Invite sent to " + GetNameAndLocation(session));
SendStatus(room); // so we get added as active to new room invitee creates
SendWhoResponse(room, session);
}
}
public string GetNameAndLocation(DhtClient client)
{
string text = Core.GetName(client.UserID);
// only show user's location if more than one are active
if (Core.Locations.ActiveClientCount(client.UserID) > 1)
text += " @" + Core.Locations.GetLocationName(client.UserID, client.ClientID);
return text;
}
void SendInviteProof(ChatRoom room)
{
room.Members.LockReading(delegate()
{
foreach (ulong id in room.Members)
foreach (RudpSession session in Network.RudpControl.GetActiveSessions(id))
if(room.NeedSendInvite(id, session.ClientID))
SendInviteProof(room, session);
});
}
void SendInviteProof(ChatRoom room, RudpSession session)
{
if (!room.Invites.ContainsKey(Core.UserID))
return;
// if already sent proof to client, return
Tuple<ChatInvite, List<ushort>> tried;
if (!room.Invites.TryGetValue(session.UserID, out tried))
{
tried = new Tuple<ChatInvite, List<ushort>>(null, new List<ushort>());
room.Invites[session.UserID] = tried;
}
if (tried.Param2.Contains(session.ClientID))
return;
tried.Param2.Add(session.ClientID);
ChatInvite invite = new ChatInvite();
invite.RoomID = room.RoomID;
invite.Title = room.Title;
invite.SignedInvite = room.Invites[Core.UserID].Param1.SignedInvite;
session.SendData(ServiceID, 0, invite);
}
void ReceiveInvite(ChatInvite invite, RudpSession session)
{
// if in global im, only allow if on buddies list
if (Core.User.Settings.GlobalIM)
if (!Core.Buddies.BuddyList.SafeContainsKey(session.UserID))
return;
if (Core.Buddies.IgnoreList.SafeContainsKey(session.UserID))
return;
bool showInvite = false;
ChatRoom room;
if (!RoomMap.TryGetValue(invite.RoomID, out room))
{
RoomKind kind = invite.SignedInvite != null ? RoomKind.Secret : RoomKind.Private;
room = new ChatRoom(kind, invite.RoomID, invite.Title);
room.RoomID = invite.RoomID;
room.Kind = kind;
room.AddMember(session.UserID);
if (invite.Host != null)
{
room.Host = Utilities.KeytoID(invite.Host);
Core.IndexKey(room.Host, ref invite.Host);
}
RoomMap.SafeAdd(room.RoomID, room);
showInvite = true;
}
// private room
if (room.Kind == RoomKind.Secret)
{
if(!Core.KeyMap.ContainsKey(room.Host))
return;
byte[] hostKey = Core.KeyMap[room.Host];
// if this is host sending us our verification
if (session.UserID == room.Host)
{
// check that host signed our public key with his private
if (!Utilities.CheckSignedData(hostKey, Core.KeyMap[Core.UserID], invite.SignedInvite))
return;
if(!room.Invites.ContainsKey(Core.UserID)) // would fail if a node's dupe on network sends invite back to itself
room.Invites.Add(Core.UserID, new Tuple<ChatInvite, List<ushort>>(invite, new List<ushort>()));
}
// else this is node in room sending us proof of being invited
else
{
if (!Core.KeyMap.ContainsKey(session.UserID))
return; // key should def be in map, it was added when session was made to sender
// check that host signed remote's key with host's private
if (!Utilities.CheckSignedData(hostKey, Core.KeyMap[session.UserID], invite.SignedInvite))
return;
}
// if not verified yet, add them and send back our own verification
if (!room.Verified.ContainsKey(session.UserID))
{
room.Verified[session.UserID] = true;
if (room.Active)
{
SendInviteProof(room, session); // someone sends us their proof, we send it back in return
SendStatus(session); // send status here because now it will include private rooms
}
}
}
if (Trust != null && !Trust.TrustMap.SafeContainsKey(session.UserID))
Trust.Research(session.UserID, 0, false);
if (showInvite)
{
Core.RunInGuiThread(NewInvite, session.UserID, room);
}
}
void SendWhoRequest(ChatRoom room)
{
Debug.Assert(!IsCommandRoom(room.Kind));
room.Members.LockReading(delegate()
{
foreach (ulong id in room.Members)
foreach (RudpSession session in Network.RudpControl.GetActiveSessions(id))
SendWhoRequest(room, session);
});
}
void SendWhoRequest(ChatRoom room, RudpSession session)
{
ChatWho whoReq = new ChatWho();
whoReq.Request = true;
whoReq.RoomID = room.RoomID;
session.SendData(ServiceID, 0, whoReq);
}
void SendWhoResponse(ChatRoom room, RudpSession session)
{
Debug.Assert(!IsCommandRoom(room.Kind));
List<ChatWho> whoPackets = new List<ChatWho>();
ChatWho who = new ChatWho();
who.RoomID = room.RoomID;
whoPackets.Add(who);
room.Members.LockReading(delegate()
{
foreach (ulong id in room.Members)
if (Network.RudpControl.GetActiveSessions(id).Count > 0) // only send members who are connected
{
who.Members.Add(id);
if (who.Members.Count > 40) // 40 * 8 = 320 bytes
{
who = new ChatWho();
who.RoomID = room.RoomID;
whoPackets.Add(who);
}
}
});
// send who to already connected locations
foreach(ChatWho packet in whoPackets)
session.SendData(ServiceID, 0, packet);
}
void ReceiveWho(ChatWho who, RudpSession session)
{
// if in room
ChatRoom room;
// if not in room, send status
if (!RoomMap.TryGetValue(who.RoomID, out room))
{
SendStatus(session);
return;
}
// if room not public, and not from verified private room member or host, igonre
if (IsCommandRoom(room.Kind) || (room.Kind == RoomKind.Secret && !room.Verified.ContainsKey(session.UserID)))
return;
if (!room.Active)
return;
// if requset
if(who.Request)
SendWhoResponse(room, session);
// if reply
else
{
// add members to our own list
foreach(ulong id in who.Members)
if (!room.Members.SafeContains(id))
{
room.AddMember(id);
if (Trust != null && Trust.GetTrust(id) == null)
Trust.Research(id, 0, false);
Core.Locations.Research(id);
}
// connect to new members
ConnectRoom(room);
}
}
public void Share_FileProcessed(SharedFile file, object arg)
{
ChatRoom room = arg as ChatRoom;
if (room == null || !room.Active)
return;
ShareService share = Core.GetService(ServiceIDs.Share) as ShareService;
string message = "File: " + file.Name +
", Size: " + Utilities.ByteSizetoDecString(file.Size) +
", Download: " + share.GetFileLink(Core.UserID, file);
SendMessage(room, message, TextFormat.Plain);
}
static ulong GetPublicRoomID(string name)
{
return BitConverter.ToUInt64(new SHA1Managed().ComputeHash(UTF8Encoding.UTF8.GetBytes(name.ToLowerInvariant())), 0);
}
}
public enum RoomKind { Command_High, Command_Low, Live_High, Live_Low, Public, Private, Secret }; // do not change order
public delegate void MembersUpdateHandler();
public delegate void ChatUpdateHandler(ChatMessage message);
public class ChatRoom
{
public ulong RoomID;
public uint ProjectID;
public string Title;
public RoomKind Kind;
public bool IsLoop;
public bool Active;
public bool PublishRoom;
public DateTime NextPublish;
public ulong Host;
// members in room by key, if online there will be elements in list for each location
public ThreadedList<ulong> Members = new ThreadedList<ulong>();
// for host this is a map of clients who have been sent invitations
// for invitee this is a map of clients who have been sent proof that we are part of the room
public Dictionary<ulong, Tuple<ChatInvite, List<ushort>>> Invites;
public Dictionary<ulong, bool> Verified;
public ThreadedList<ChatMessage> Log = new ThreadedList<ChatMessage>();
public MembersUpdateHandler MembersUpdate;
public ChatUpdateHandler ChatUpdate;
// per channel polling needs to be done because client may be still connected, leaving one channel, joining another
public ChatRoom(RoomKind kind, uint project)
{
Debug.Assert(ChatService.IsCommandRoom(kind));
Kind = kind;
RoomID = project + (uint)kind;
ProjectID = project;
}
public ChatRoom( RoomKind kind, ulong id, string title)
{
Debug.Assert( !ChatService.IsCommandRoom(kind) );
Kind = kind;
RoomID = id;
Title = title;
Invites = new Dictionary<ulong, Tuple<ChatInvite, List<ushort>>>();
// public rooms are private rooms with static room ids
if (Kind == RoomKind.Public)
{
PublishRoom = true;
Kind = RoomKind.Private;
}
if (Kind == RoomKind.Secret)
Verified = new Dictionary<ulong, bool>();
}
public int GetActiveMembers(ChatService chat)
{
int count = 0;
Members.LockReading(delegate()
{
foreach (ulong user in Members)
if (chat.Network.RudpControl.GetActiveSessions(user).Count > 0)
count++;
});
return count;
}
public bool NeedSendInvite(ulong id, ushort client)
{
return Invites != null &&
Invites.ContainsKey(id) &&
!Invites[id].Param2.Contains(client);
}
public void AddMember(ulong user)
{
if(!Members.SafeContains(user))
Members.SafeAdd(user);
}
public void RemoveMember(ulong user)
{
Members.SafeRemove(user);
}
}
public class ChatMessage : DhtClient
{
public bool System;
public DateTime TimeStamp;
public string Text;
public TextFormat Format;
public bool Sent;
public ChatMessage(OpCore core, string text, TextFormat format)
{
UserID = core.UserID;
ClientID = core.Network.Local.ClientID;
TimeStamp = core.TimeNow;
Text = text;
Format = format;
}
public ChatMessage(OpCore core, RudpSession session, ChatText text)
{
UserID = session.UserID;
ClientID = session.ClientID;
TimeStamp = core.TimeNow;
Text = text.Text;
Format = text.Format;
}
}
}
| |
// suppress "Missing XML comment for publicly visible type or member"
#pragma warning disable 1591
#region ReSharper warnings
// ReSharper disable PartialTypeWithSinglePart
// ReSharper disable RedundantNameQualifier
// ReSharper disable InconsistentNaming
// ReSharper disable CheckNamespace
// ReSharper disable UnusedParameter.Local
// ReSharper disable RedundantUsingDirective
#endregion
namespace tests
{
[System.CodeDom.Compiler.GeneratedCode("gbc", "0.5.0.0")]
public class FooProxy<TConnection> : IFoo where TConnection : global::Bond.Comm.IEventConnection, global::Bond.Comm.IRequestResponseConnection
{
private readonly TConnection m_connection;
public FooProxy(TConnection connection)
{
m_connection = connection;
}
public void foo11Async()
{
var message = new global::Bond.Comm.Message<global::Bond.Void>(new global::Bond.Void());
foo11Async(message);
}
public void foo11Async(global::Bond.Comm.IMessage<global::Bond.Void> param)
{
m_connection.FireEventAsync<global::Bond.Void>(
"tests.Foo.foo11",
param);
}
public void foo12Async()
{
var message = new global::Bond.Comm.Message<global::Bond.Void>(new global::Bond.Void());
foo12Async(message);
}
public void foo12Async(global::Bond.Comm.IMessage<global::Bond.Void> param)
{
m_connection.FireEventAsync<global::Bond.Void>(
"tests.Foo.foo12",
param);
}
public void foo13Async(BasicTypes param)
{
var message = new global::Bond.Comm.Message<BasicTypes>(param);
foo13Async(message);
}
public void foo13Async(global::Bond.Comm.IMessage<BasicTypes> param)
{
m_connection.FireEventAsync<BasicTypes>(
"tests.Foo.foo13",
param);
}
public void foo14Async(dummy param)
{
var message = new global::Bond.Comm.Message<dummy>(param);
foo14Async(message);
}
public void foo14Async(global::Bond.Comm.IMessage<dummy> param)
{
m_connection.FireEventAsync<dummy>(
"tests.Foo.foo14",
param);
}
public global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage<global::Bond.Void>> foo21Async()
{
var message = new global::Bond.Comm.Message<global::Bond.Void>(new global::Bond.Void());
return foo21Async(message, global::System.Threading.CancellationToken.None);
}
public global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage<global::Bond.Void>> foo21Async(global::Bond.Comm.IMessage<global::Bond.Void> param, global::System.Threading.CancellationToken ct)
{
return m_connection.RequestResponseAsync<global::Bond.Void, global::Bond.Void>(
"tests.Foo.foo21",
param,
ct);
}
public global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage<global::Bond.Void>> foo22Async()
{
var message = new global::Bond.Comm.Message<global::Bond.Void>(new global::Bond.Void());
return foo22Async(message, global::System.Threading.CancellationToken.None);
}
public global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage<global::Bond.Void>> foo22Async(global::Bond.Comm.IMessage<global::Bond.Void> param, global::System.Threading.CancellationToken ct)
{
return m_connection.RequestResponseAsync<global::Bond.Void, global::Bond.Void>(
"tests.Foo.foo22",
param,
ct);
}
public global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage<global::Bond.Void>> foo23Async(BasicTypes param)
{
var message = new global::Bond.Comm.Message<BasicTypes>(param);
return foo23Async(message, global::System.Threading.CancellationToken.None);
}
public global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage<global::Bond.Void>> foo23Async(global::Bond.Comm.IMessage<BasicTypes> param, global::System.Threading.CancellationToken ct)
{
return m_connection.RequestResponseAsync<BasicTypes, global::Bond.Void>(
"tests.Foo.foo23",
param,
ct);
}
public global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage<global::Bond.Void>> foo24Async(dummy param)
{
var message = new global::Bond.Comm.Message<dummy>(param);
return foo24Async(message, global::System.Threading.CancellationToken.None);
}
public global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage<global::Bond.Void>> foo24Async(global::Bond.Comm.IMessage<dummy> param, global::System.Threading.CancellationToken ct)
{
return m_connection.RequestResponseAsync<dummy, global::Bond.Void>(
"tests.Foo.foo24",
param,
ct);
}
public global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage<BasicTypes>> foo31Async()
{
var message = new global::Bond.Comm.Message<global::Bond.Void>(new global::Bond.Void());
return foo31Async(message, global::System.Threading.CancellationToken.None);
}
public global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage<BasicTypes>> foo31Async(global::Bond.Comm.IMessage<global::Bond.Void> param, global::System.Threading.CancellationToken ct)
{
return m_connection.RequestResponseAsync<global::Bond.Void, BasicTypes>(
"tests.Foo.foo31",
param,
ct);
}
public global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage<BasicTypes>> foo32Async()
{
var message = new global::Bond.Comm.Message<global::Bond.Void>(new global::Bond.Void());
return foo32Async(message, global::System.Threading.CancellationToken.None);
}
public global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage<BasicTypes>> foo32Async(global::Bond.Comm.IMessage<global::Bond.Void> param, global::System.Threading.CancellationToken ct)
{
return m_connection.RequestResponseAsync<global::Bond.Void, BasicTypes>(
"tests.Foo.foo32",
param,
ct);
}
public global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage<BasicTypes>> foo33Async(BasicTypes param)
{
var message = new global::Bond.Comm.Message<BasicTypes>(param);
return foo33Async(message, global::System.Threading.CancellationToken.None);
}
public global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage<BasicTypes>> foo33Async(global::Bond.Comm.IMessage<BasicTypes> param, global::System.Threading.CancellationToken ct)
{
return m_connection.RequestResponseAsync<BasicTypes, BasicTypes>(
"tests.Foo.foo33",
param,
ct);
}
public global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage<BasicTypes>> foo34Async(dummy param)
{
var message = new global::Bond.Comm.Message<dummy>(param);
return foo34Async(message, global::System.Threading.CancellationToken.None);
}
public global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage<BasicTypes>> foo34Async(global::Bond.Comm.IMessage<dummy> param, global::System.Threading.CancellationToken ct)
{
return m_connection.RequestResponseAsync<dummy, BasicTypes>(
"tests.Foo.foo34",
param,
ct);
}
public global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage<dummy>> foo41Async()
{
var message = new global::Bond.Comm.Message<global::Bond.Void>(new global::Bond.Void());
return foo41Async(message, global::System.Threading.CancellationToken.None);
}
public global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage<dummy>> foo41Async(global::Bond.Comm.IMessage<global::Bond.Void> param, global::System.Threading.CancellationToken ct)
{
return m_connection.RequestResponseAsync<global::Bond.Void, dummy>(
"tests.Foo.foo41",
param,
ct);
}
public global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage<dummy>> foo42Async()
{
var message = new global::Bond.Comm.Message<global::Bond.Void>(new global::Bond.Void());
return foo42Async(message, global::System.Threading.CancellationToken.None);
}
public global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage<dummy>> foo42Async(global::Bond.Comm.IMessage<global::Bond.Void> param, global::System.Threading.CancellationToken ct)
{
return m_connection.RequestResponseAsync<global::Bond.Void, dummy>(
"tests.Foo.foo42",
param,
ct);
}
public global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage<dummy>> foo43Async(BasicTypes param)
{
var message = new global::Bond.Comm.Message<BasicTypes>(param);
return foo43Async(message, global::System.Threading.CancellationToken.None);
}
public global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage<dummy>> foo43Async(global::Bond.Comm.IMessage<BasicTypes> param, global::System.Threading.CancellationToken ct)
{
return m_connection.RequestResponseAsync<BasicTypes, dummy>(
"tests.Foo.foo43",
param,
ct);
}
public global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage<dummy>> foo44Async(dummy param)
{
var message = new global::Bond.Comm.Message<dummy>(param);
return foo44Async(message, global::System.Threading.CancellationToken.None);
}
public global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage<dummy>> foo44Async(global::Bond.Comm.IMessage<dummy> param, global::System.Threading.CancellationToken ct)
{
return m_connection.RequestResponseAsync<dummy, dummy>(
"tests.Foo.foo44",
param,
ct);
}
}
} // tests
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Xml.Linq;
namespace DocumentFormat.OpenXml.Linq
{
/// <summary>
/// Declares XNamespace and XName fields for the xmlns:ap="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties" namespace.
/// </summary>
public static class AP
{
/// <summary>
/// Defines the XML namespace associated with the ap prefix.
/// </summary>
public static readonly XNamespace ap = "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties";
/// <summary>
/// Represents the ap:Application XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="Properties" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Application.</description></item>
/// </list>
/// </remarks>
public static readonly XName Application = ap + "Application";
/// <summary>
/// Represents the ap:AppVersion XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="Properties" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: ApplicationVersion.</description></item>
/// </list>
/// </remarks>
public static readonly XName AppVersion = ap + "AppVersion";
/// <summary>
/// Represents the ap:Characters XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="Properties" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Characters.</description></item>
/// </list>
/// </remarks>
public static readonly XName Characters = ap + "Characters";
/// <summary>
/// Represents the ap:CharactersWithSpaces XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="Properties" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: CharactersWithSpaces.</description></item>
/// </list>
/// </remarks>
public static readonly XName CharactersWithSpaces = ap + "CharactersWithSpaces";
/// <summary>
/// Represents the ap:Company XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="Properties" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Company.</description></item>
/// </list>
/// </remarks>
public static readonly XName Company = ap + "Company";
/// <summary>
/// Represents the ap:DigSig XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="Properties" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="VT.blob" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: DigitalSignature.</description></item>
/// </list>
/// </remarks>
public static readonly XName DigSig = ap + "DigSig";
/// <summary>
/// Represents the ap:DocSecurity XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="Properties" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: DocumentSecurity.</description></item>
/// </list>
/// </remarks>
public static readonly XName DocSecurity = ap + "DocSecurity";
/// <summary>
/// Represents the ap:HeadingPairs XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="Properties" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="VT.vector" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: HeadingPairs.</description></item>
/// </list>
/// </remarks>
public static readonly XName HeadingPairs = ap + "HeadingPairs";
/// <summary>
/// Represents the ap:HiddenSlides XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="Properties" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: HiddenSlides.</description></item>
/// </list>
/// </remarks>
public static readonly XName HiddenSlides = ap + "HiddenSlides";
/// <summary>
/// Represents the ap:HLinks XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="Properties" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="VT.vector" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: HyperlinkList.</description></item>
/// </list>
/// </remarks>
public static readonly XName HLinks = ap + "HLinks";
/// <summary>
/// Represents the ap:HyperlinkBase XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="Properties" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: HyperlinkBase.</description></item>
/// </list>
/// </remarks>
public static readonly XName HyperlinkBase = ap + "HyperlinkBase";
/// <summary>
/// Represents the ap:HyperlinksChanged XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="Properties" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: HyperlinksChanged.</description></item>
/// </list>
/// </remarks>
public static readonly XName HyperlinksChanged = ap + "HyperlinksChanged";
/// <summary>
/// Represents the ap:Lines XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="Properties" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Lines.</description></item>
/// </list>
/// </remarks>
public static readonly XName Lines = ap + "Lines";
/// <summary>
/// Represents the ap:LinksUpToDate XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="Properties" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: LinksUpToDate.</description></item>
/// </list>
/// </remarks>
public static readonly XName LinksUpToDate = ap + "LinksUpToDate";
/// <summary>
/// Represents the ap:Manager XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="Properties" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Manager.</description></item>
/// </list>
/// </remarks>
public static readonly XName Manager = ap + "Manager";
/// <summary>
/// Represents the ap:MMClips XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="Properties" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: MultimediaClips.</description></item>
/// </list>
/// </remarks>
public static readonly XName MMClips = ap + "MMClips";
/// <summary>
/// Represents the ap:Notes XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="Properties" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Notes.</description></item>
/// </list>
/// </remarks>
public static readonly XName Notes = ap + "Notes";
/// <summary>
/// Represents the ap:Pages XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="Properties" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Pages.</description></item>
/// </list>
/// </remarks>
public static readonly XName Pages = ap + "Pages";
/// <summary>
/// Represents the ap:Paragraphs XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="Properties" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Paragraphs.</description></item>
/// </list>
/// </remarks>
public static readonly XName Paragraphs = ap + "Paragraphs";
/// <summary>
/// Represents the ap:PresentationFormat XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="Properties" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: PresentationFormat.</description></item>
/// </list>
/// </remarks>
public static readonly XName PresentationFormat = ap + "PresentationFormat";
/// <summary>
/// Represents the ap:Properties XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following child XML elements: <see cref="Application" />, <see cref="AppVersion" />, <see cref="Characters" />, <see cref="CharactersWithSpaces" />, <see cref="Company" />, <see cref="DigSig" />, <see cref="DocSecurity" />, <see cref="HeadingPairs" />, <see cref="HiddenSlides" />, <see cref="HLinks" />, <see cref="HyperlinkBase" />, <see cref="HyperlinksChanged" />, <see cref="Lines" />, <see cref="LinksUpToDate" />, <see cref="Manager" />, <see cref="MMClips" />, <see cref="Notes" />, <see cref="Pages" />, <see cref="Paragraphs" />, <see cref="PresentationFormat" />, <see cref="ScaleCrop" />, <see cref="SharedDoc" />, <see cref="Slides" />, <see cref="Template" />, <see cref="TitlesOfParts" />, <see cref="TotalTime" />, <see cref="Words" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Properties.</description></item>
/// </list>
/// </remarks>
public static readonly XName Properties = ap + "Properties";
/// <summary>
/// Represents the ap:ScaleCrop XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="Properties" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: ScaleCrop.</description></item>
/// </list>
/// </remarks>
public static readonly XName ScaleCrop = ap + "ScaleCrop";
/// <summary>
/// Represents the ap:SharedDoc XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="Properties" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: SharedDocument.</description></item>
/// </list>
/// </remarks>
public static readonly XName SharedDoc = ap + "SharedDoc";
/// <summary>
/// Represents the ap:Slides XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="Properties" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Slides.</description></item>
/// </list>
/// </remarks>
public static readonly XName Slides = ap + "Slides";
/// <summary>
/// Represents the ap:Template XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="Properties" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Template.</description></item>
/// </list>
/// </remarks>
public static readonly XName Template = ap + "Template";
/// <summary>
/// Represents the ap:TitlesOfParts XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="Properties" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="VT.vector" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: TitlesOfParts.</description></item>
/// </list>
/// </remarks>
public static readonly XName TitlesOfParts = ap + "TitlesOfParts";
/// <summary>
/// Represents the ap:TotalTime XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="Properties" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: TotalTime.</description></item>
/// </list>
/// </remarks>
public static readonly XName TotalTime = ap + "TotalTime";
/// <summary>
/// Represents the ap:Words XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="Properties" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Words.</description></item>
/// </list>
/// </remarks>
public static readonly XName Words = ap + "Words";
}
}
| |
//
// Copyright (c) Microsoft and contributors. 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.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.Azure.Management.Resources;
using Microsoft.Azure.Management.Resources.Models;
namespace Microsoft.Azure.Management.Resources
{
public static partial class ManagementLockOperationsExtensions
{
/// <summary>
/// Create or update a management lock at the resource group level.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IManagementLockOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name.
/// </param>
/// <param name='lockName'>
/// Required. The lock name.
/// </param>
/// <param name='parameters'>
/// Required. The management lock parameters.
/// </param>
/// <returns>
/// Management lock information.
/// </returns>
public static ManagementLockReturnResult CreateOrUpdateAtResourceGroupLevel(this IManagementLockOperations operations, string resourceGroupName, string lockName, ManagementLockProperties parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IManagementLockOperations)s).CreateOrUpdateAtResourceGroupLevelAsync(resourceGroupName, lockName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create or update a management lock at the resource group level.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IManagementLockOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name.
/// </param>
/// <param name='lockName'>
/// Required. The lock name.
/// </param>
/// <param name='parameters'>
/// Required. The management lock parameters.
/// </param>
/// <returns>
/// Management lock information.
/// </returns>
public static Task<ManagementLockReturnResult> CreateOrUpdateAtResourceGroupLevelAsync(this IManagementLockOperations operations, string resourceGroupName, string lockName, ManagementLockProperties parameters)
{
return operations.CreateOrUpdateAtResourceGroupLevelAsync(resourceGroupName, lockName, parameters, CancellationToken.None);
}
/// <summary>
/// Create or update a management lock at the resource level or any
/// level below resource.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IManagementLockOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='identity'>
/// Required. Resource identity.
/// </param>
/// <param name='lockName'>
/// Required. The name of lock.
/// </param>
/// <param name='parameters'>
/// Required. Create or update management lock parameters.
/// </param>
/// <returns>
/// Management lock information.
/// </returns>
public static ManagementLockReturnResult CreateOrUpdateAtResourceLevel(this IManagementLockOperations operations, string resourceGroupName, ResourceIdentity identity, string lockName, ManagementLockProperties parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IManagementLockOperations)s).CreateOrUpdateAtResourceLevelAsync(resourceGroupName, identity, lockName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create or update a management lock at the resource level or any
/// level below resource.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IManagementLockOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='identity'>
/// Required. Resource identity.
/// </param>
/// <param name='lockName'>
/// Required. The name of lock.
/// </param>
/// <param name='parameters'>
/// Required. Create or update management lock parameters.
/// </param>
/// <returns>
/// Management lock information.
/// </returns>
public static Task<ManagementLockReturnResult> CreateOrUpdateAtResourceLevelAsync(this IManagementLockOperations operations, string resourceGroupName, ResourceIdentity identity, string lockName, ManagementLockProperties parameters)
{
return operations.CreateOrUpdateAtResourceLevelAsync(resourceGroupName, identity, lockName, parameters, CancellationToken.None);
}
/// <summary>
/// Create or update a management lock at the subscription level.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IManagementLockOperations.
/// </param>
/// <param name='lockName'>
/// Required. The name of lock.
/// </param>
/// <param name='parameters'>
/// Required. The management lock parameters.
/// </param>
/// <returns>
/// Management lock information.
/// </returns>
public static ManagementLockReturnResult CreateOrUpdateAtSubscriptionLevel(this IManagementLockOperations operations, string lockName, ManagementLockProperties parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IManagementLockOperations)s).CreateOrUpdateAtSubscriptionLevelAsync(lockName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create or update a management lock at the subscription level.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IManagementLockOperations.
/// </param>
/// <param name='lockName'>
/// Required. The name of lock.
/// </param>
/// <param name='parameters'>
/// Required. The management lock parameters.
/// </param>
/// <returns>
/// Management lock information.
/// </returns>
public static Task<ManagementLockReturnResult> CreateOrUpdateAtSubscriptionLevelAsync(this IManagementLockOperations operations, string lockName, ManagementLockProperties parameters)
{
return operations.CreateOrUpdateAtSubscriptionLevelAsync(lockName, parameters, CancellationToken.None);
}
/// <summary>
/// Deletes the management lock of a resource group.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IManagementLockOperations.
/// </param>
/// <param name='resourceGroup'>
/// Required. The resource group names.
/// </param>
/// <param name='lockName'>
/// Required. The name of lock.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse DeleteAtResourceGroupLevel(this IManagementLockOperations operations, string resourceGroup, string lockName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IManagementLockOperations)s).DeleteAtResourceGroupLevelAsync(resourceGroup, lockName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the management lock of a resource group.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IManagementLockOperations.
/// </param>
/// <param name='resourceGroup'>
/// Required. The resource group names.
/// </param>
/// <param name='lockName'>
/// Required. The name of lock.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> DeleteAtResourceGroupLevelAsync(this IManagementLockOperations operations, string resourceGroup, string lockName)
{
return operations.DeleteAtResourceGroupLevelAsync(resourceGroup, lockName, CancellationToken.None);
}
/// <summary>
/// Deletes the management lock of a resource or any level below
/// resource.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IManagementLockOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='identity'>
/// Required. Resource identity.
/// </param>
/// <param name='lockName'>
/// Required. The name of lock.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse DeleteAtResourceLevel(this IManagementLockOperations operations, string resourceGroupName, ResourceIdentity identity, string lockName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IManagementLockOperations)s).DeleteAtResourceLevelAsync(resourceGroupName, identity, lockName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the management lock of a resource or any level below
/// resource.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IManagementLockOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='identity'>
/// Required. Resource identity.
/// </param>
/// <param name='lockName'>
/// Required. The name of lock.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> DeleteAtResourceLevelAsync(this IManagementLockOperations operations, string resourceGroupName, ResourceIdentity identity, string lockName)
{
return operations.DeleteAtResourceLevelAsync(resourceGroupName, identity, lockName, CancellationToken.None);
}
/// <summary>
/// Deletes the management lock of a subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IManagementLockOperations.
/// </param>
/// <param name='lockName'>
/// Required. The name of lock.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse DeleteAtSubscriptionLevel(this IManagementLockOperations operations, string lockName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IManagementLockOperations)s).DeleteAtSubscriptionLevelAsync(lockName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the management lock of a subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IManagementLockOperations.
/// </param>
/// <param name='lockName'>
/// Required. The name of lock.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> DeleteAtSubscriptionLevelAsync(this IManagementLockOperations operations, string lockName)
{
return operations.DeleteAtSubscriptionLevelAsync(lockName, CancellationToken.None);
}
/// <summary>
/// Gets the management lock of a scope.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IManagementLockOperations.
/// </param>
/// <param name='lockName'>
/// Required. Name of the management lock.
/// </param>
/// <returns>
/// Management lock information.
/// </returns>
public static ManagementLockReturnResult Get(this IManagementLockOperations operations, string lockName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IManagementLockOperations)s).GetAsync(lockName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the management lock of a scope.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IManagementLockOperations.
/// </param>
/// <param name='lockName'>
/// Required. Name of the management lock.
/// </param>
/// <returns>
/// Management lock information.
/// </returns>
public static Task<ManagementLockReturnResult> GetAsync(this IManagementLockOperations operations, string lockName)
{
return operations.GetAsync(lockName, CancellationToken.None);
}
/// <summary>
/// Gets all the management locks of a resource group.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IManagementLockOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Resource group name.
/// </param>
/// <param name='parameters'>
/// Optional. Query parameters. If empty is passed returns all locks
/// at, above or below the resource group.
/// </param>
/// <returns>
/// List of management locks.
/// </returns>
public static ManagementLockListResult ListAtResourceGroupLevel(this IManagementLockOperations operations, string resourceGroupName, ManagementLockGetQueryParameter parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IManagementLockOperations)s).ListAtResourceGroupLevelAsync(resourceGroupName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets all the management locks of a resource group.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IManagementLockOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Resource group name.
/// </param>
/// <param name='parameters'>
/// Optional. Query parameters. If empty is passed returns all locks
/// at, above or below the resource group.
/// </param>
/// <returns>
/// List of management locks.
/// </returns>
public static Task<ManagementLockListResult> ListAtResourceGroupLevelAsync(this IManagementLockOperations operations, string resourceGroupName, ManagementLockGetQueryParameter parameters)
{
return operations.ListAtResourceGroupLevelAsync(resourceGroupName, parameters, CancellationToken.None);
}
/// <summary>
/// Gets all the management locks of a resource or any level below
/// resource.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IManagementLockOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group. The name is case
/// insensitive.
/// </param>
/// <param name='identity'>
/// Required. Resource identity.
/// </param>
/// <param name='parameters'>
/// Optional. Query parameters. If empty is passed returns all locks at
/// or below the resource.If atScope() is passed returns all locks at
/// the resource level.
/// </param>
/// <returns>
/// List of management locks.
/// </returns>
public static ManagementLockListResult ListAtResourceLevel(this IManagementLockOperations operations, string resourceGroupName, ResourceIdentity identity, ManagementLockGetQueryParameter parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IManagementLockOperations)s).ListAtResourceLevelAsync(resourceGroupName, identity, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets all the management locks of a resource or any level below
/// resource.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IManagementLockOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group. The name is case
/// insensitive.
/// </param>
/// <param name='identity'>
/// Required. Resource identity.
/// </param>
/// <param name='parameters'>
/// Optional. Query parameters. If empty is passed returns all locks at
/// or below the resource.If atScope() is passed returns all locks at
/// the resource level.
/// </param>
/// <returns>
/// List of management locks.
/// </returns>
public static Task<ManagementLockListResult> ListAtResourceLevelAsync(this IManagementLockOperations operations, string resourceGroupName, ResourceIdentity identity, ManagementLockGetQueryParameter parameters)
{
return operations.ListAtResourceLevelAsync(resourceGroupName, identity, parameters, CancellationToken.None);
}
/// <summary>
/// Gets all the management locks of a subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IManagementLockOperations.
/// </param>
/// <param name='parameters'>
/// Optional. Query parameters. If empty is passed returns all locks
/// at, above or below the subscription.
/// </param>
/// <returns>
/// List of management locks.
/// </returns>
public static ManagementLockListResult ListAtSubscriptionLevel(this IManagementLockOperations operations, ManagementLockGetQueryParameter parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IManagementLockOperations)s).ListAtSubscriptionLevelAsync(parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets all the management locks of a subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IManagementLockOperations.
/// </param>
/// <param name='parameters'>
/// Optional. Query parameters. If empty is passed returns all locks
/// at, above or below the subscription.
/// </param>
/// <returns>
/// List of management locks.
/// </returns>
public static Task<ManagementLockListResult> ListAtSubscriptionLevelAsync(this IManagementLockOperations operations, ManagementLockGetQueryParameter parameters)
{
return operations.ListAtSubscriptionLevelAsync(parameters, CancellationToken.None);
}
/// <summary>
/// Get a list of management locks at resource level or below.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IManagementLockOperations.
/// </param>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <returns>
/// List of management locks.
/// </returns>
public static ManagementLockListResult ListNext(this IManagementLockOperations operations, string nextLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IManagementLockOperations)s).ListNextAsync(nextLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get a list of management locks at resource level or below.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IManagementLockOperations.
/// </param>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <returns>
/// List of management locks.
/// </returns>
public static Task<ManagementLockListResult> ListNextAsync(this IManagementLockOperations operations, string nextLink)
{
return operations.ListNextAsync(nextLink, CancellationToken.None);
}
}
}
| |
/*
* 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.IO;
using System.Text;
using System.Collections;
using Lucene.Net.Analysis;
using Lucene.Net.Analysis.De;
using Lucene.Net.Analysis.Standard;
using Version = Lucene.Net.Util.Version;
namespace Lucene.Net.Analysis.Cz
{
/*
* {@link Analyzer} for Czech language.
* <p>
* Supports an external list of stopwords (words that
* will not be indexed at all).
* A default set of stopwords is used unless an alternative list is specified.
* </p>
*
* <p><b>NOTE</b>: This class uses the same {@link Version}
* dependent settings as {@link StandardAnalyzer}.</p>
*/
public sealed class CzechAnalyzer : Analyzer {
/*
* List of typical stopwords.
* @deprecated use {@link #getDefaultStopSet()} instead
*/
// TODO make this private in 3.1
public static readonly String[] CZECH_STOP_WORDS = {
"a","s","k","o","i","u","v","z","dnes","cz","t\u00edmto","bude\u0161","budem",
"byli","jse\u0161","m\u016fj","sv\u00fdm","ta","tomto","tohle","tuto","tyto",
"jej","zda","pro\u010d","m\u00e1te","tato","kam","tohoto","kdo","kte\u0159\u00ed",
"mi","n\u00e1m","tom","tomuto","m\u00edt","nic","proto","kterou","byla",
"toho","proto\u017ee","asi","ho","na\u0161i","napi\u0161te","re","co\u017e","t\u00edm",
"tak\u017ee","sv\u00fdch","jej\u00ed","sv\u00fdmi","jste","aj","tu","tedy","teto",
"bylo","kde","ke","prav\u00e9","ji","nad","nejsou","\u010di","pod","t\u00e9ma",
"mezi","p\u0159es","ty","pak","v\u00e1m","ani","kdy\u017e","v\u0161ak","neg","jsem",
"tento","\u010dl\u00e1nku","\u010dl\u00e1nky","aby","jsme","p\u0159ed","pta","jejich",
"byl","je\u0161t\u011b","a\u017e","bez","tak\u00e9","pouze","prvn\u00ed","va\u0161e","kter\u00e1",
"n\u00e1s","nov\u00fd","tipy","pokud","m\u016f\u017ee","strana","jeho","sv\u00e9","jin\u00e9",
"zpr\u00e1vy","nov\u00e9","nen\u00ed","v\u00e1s","jen","podle","zde","u\u017e","b\u00fdt","v\u00edce",
"bude","ji\u017e","ne\u017e","kter\u00fd","by","kter\u00e9","co","nebo","ten","tak",
"m\u00e1","p\u0159i","od","po","jsou","jak","dal\u0161\u00ed","ale","si","se","ve",
"to","jako","za","zp\u011bt","ze","do","pro","je","na","atd","atp",
"jakmile","p\u0159i\u010dem\u017e","j\u00e1","on","ona","ono","oni","ony","my","vy",
"j\u00ed","ji","m\u011b","mne","jemu","tomu","t\u011bm","t\u011bmu","n\u011bmu","n\u011bmu\u017e",
"jeho\u017e","j\u00ed\u017e","jeliko\u017e","je\u017e","jako\u017e","na\u010de\u017e",
};
/*
* Returns a set of default Czech-stopwords
* @return a set of default Czech-stopwords
*/
public static ISet<string> getDefaultStopSet(){
return DefaultSetHolder.DEFAULT_SET;
}
private static class DefaultSetHolder {
internal static ISet<string> DEFAULT_SET = CharArraySet.UnmodifiableSet(new CharArraySet(
(IEnumerable<string>)CZECH_STOP_WORDS, false));
}
/*
* Contains the stopwords used with the {@link StopFilter}.
*/
// TODO make this final in 3.1
private ISet<string> stoptable;
private readonly Version matchVersion;
/*
* Builds an analyzer with the default stop words ({@link #CZECH_STOP_WORDS}).
*/
public CzechAnalyzer(Version matchVersion)
: this(matchVersion, DefaultSetHolder.DEFAULT_SET)
{
}
/*
* Builds an analyzer with the given stop words and stemming exclusion words
*
* @param matchVersion
* lucene compatibility version
* @param stopwords
* a stopword set
*/
public CzechAnalyzer(Version matchVersion, ISet<string> stopwords) {
this.matchVersion = matchVersion;
this.stoptable = CharArraySet.UnmodifiableSet(CharArraySet.Copy(stopwords));
}
/*
* Builds an analyzer with the given stop words.
* @deprecated use {@link #CzechAnalyzer(Version, Set)} instead
*/
public CzechAnalyzer(Version matchVersion, params string[] stopwords)
: this(matchVersion, StopFilter.MakeStopSet( stopwords ))
{
}
/*
* Builds an analyzer with the given stop words.
*
* @deprecated use {@link #CzechAnalyzer(Version, Set)} instead
*/
public CzechAnalyzer(Version matchVersion, HashSet<string> stopwords)
: this(matchVersion, (ISet<string>)stopwords)
{
}
/*
* Builds an analyzer with the given stop words.
* @deprecated use {@link #CzechAnalyzer(Version, Set)} instead
*/
public CzechAnalyzer(Version matchVersion, FileInfo stopwords )
: this(matchVersion, WordlistLoader.GetWordSet( stopwords ))
{
}
/*
* Loads stopwords hash from resource stream (file, database...).
* @param wordfile File containing the wordlist
* @param encoding Encoding used (win-1250, iso-8859-2, ...), null for default system encoding
* @deprecated use {@link WordlistLoader#getWordSet(Reader, String) }
* and {@link #CzechAnalyzer(Version, Set)} instead
*/
public void LoadStopWords( Stream wordfile, System.Text.Encoding encoding ) {
PreviousTokenStream = null; // force a new stopfilter to be created
if ( wordfile == null )
{
stoptable = Support.Compatibility.SetFactory.CreateHashSet<string>();
return;
}
try {
// clear any previous table (if present)
stoptable = Support.Compatibility.SetFactory.CreateHashSet<string>();
StreamReader isr;
if (encoding == null)
isr = new StreamReader(wordfile);
else
isr = new StreamReader(wordfile, encoding);
stoptable = WordlistLoader.GetWordSet(isr);
} catch ( IOException) {
// clear any previous table (if present)
// TODO: throw IOException
stoptable = Support.Compatibility.SetFactory.CreateHashSet<string>();
}
}
/*
* Creates a {@link TokenStream} which tokenizes all the text in the provided {@link Reader}.
*
* @return A {@link TokenStream} built from a {@link StandardTokenizer} filtered with
* {@link StandardFilter}, {@link LowerCaseFilter}, and {@link StopFilter}
*/
public override sealed TokenStream TokenStream( String fieldName, TextReader reader ) {
TokenStream result = new StandardTokenizer( matchVersion, reader );
result = new StandardFilter( result );
result = new LowerCaseFilter( result );
result = new StopFilter( StopFilter.GetEnablePositionIncrementsVersionDefault(matchVersion),
result, stoptable );
return result;
}
private class SavedStreams {
protected internal Tokenizer source;
protected internal TokenStream result;
};
/*
* Returns a (possibly reused) {@link TokenStream} which tokenizes all the text in
* the provided {@link Reader}.
*
* @return A {@link TokenStream} built from a {@link StandardTokenizer} filtered with
* {@link StandardFilter}, {@link LowerCaseFilter}, and {@link StopFilter}
*/
public override TokenStream ReusableTokenStream(String fieldName, TextReader reader)
{
SavedStreams streams = (SavedStreams) PreviousTokenStream;
if (streams == null) {
streams = new SavedStreams();
streams.source = new StandardTokenizer(matchVersion, reader);
streams.result = new StandardFilter(streams.source);
streams.result = new LowerCaseFilter(streams.result);
streams.result = new StopFilter(StopFilter.GetEnablePositionIncrementsVersionDefault(matchVersion),
streams.result, stoptable);
PreviousTokenStream = streams;
} else {
streams.source.Reset(reader);
}
return streams.result;
}
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// 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.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using Gallio.Common;
using Gallio.Runtime.ProgressMonitoring;
using Gallio.Runtime.Security;
namespace Gallio.UI.ControlPanel.Preferences
{
internal partial class PreferenceControlPanelTab : ControlPanelTab
{
public PreferenceControlPanelTab()
{
InitializeComponent();
}
/// <summary>
/// Adds a preference pane.
/// </summary>
/// <param name="path">The preference pane path consisting of slash-delimited name segments
/// specifying tree nodes.</param>
/// <param name="icon">The preference pane icon, or null if none.</param>
/// <param name="scope">The preference pane scope, or null if none.</param>
/// <param name="paneFactory">The preference pane factory.</param>
public void AddPane(string path, Icon icon, PreferencePaneScope scope, Func<PreferencePane> paneFactory)
{
string[] pathSegments = path.Split('/');
if (pathSegments.Length == 0)
throw new ArgumentException("Preference pane path must not be empty.", "path");
TreeNode treeNode = null;
foreach (string pathSegment in pathSegments)
{
TreeNodeCollection treeNodeCollection = treeNode != null
? treeNode.Nodes
: preferencePaneTree.Nodes;
TreeNode childTreeNode = FindTreeNodeByName(treeNodeCollection, pathSegment);
if (childTreeNode == null)
{
childTreeNode = new TreeNode(pathSegment);
childTreeNode.Tag = new PaneInfo(CreatePlaceholderPreferencePane, pathSegment);
treeNodeCollection.Add(childTreeNode);
}
treeNode = childTreeNode;
}
string title = pathSegments[pathSegments.Length - 1];
if (scope == PreferencePaneScope.Machine)
title += " (machine setting)";
treeNode.Tag = new PaneInfo(paneFactory, title);
if (icon != null)
{
int imageIndex = preferencePaneIconImageList.Images.Count;
preferencePaneIconImageList.Images.Add(icon);
treeNode.ImageIndex = imageIndex;
treeNode.SelectedImageIndex = imageIndex;
}
}
/// <inheritdoc />
public override void ApplyPendingSettingsChanges(IElevationContext elevationContext, IProgressMonitor progressMonitor)
{
using (progressMonitor.BeginTask("Saving preferences.", 1))
{
var preferencePanes = new List<PreferencePane>(GetPreferencePanes());
if (preferencePanes.Count == 0)
return;
double workPerPreferencePane = 1.0 / preferencePanes.Count;
foreach (PreferencePane preferencePane in preferencePanes)
{
if (progressMonitor.IsCanceled)
return;
if (preferencePane.PendingSettingsChanges)
{
preferencePane.ApplyPendingSettingsChanges(
preferencePane.RequiresElevation ? elevationContext : null,
progressMonitor.CreateSubProgressMonitor(workPerPreferencePane));
}
else
{
progressMonitor.Worked(workPerPreferencePane);
}
}
}
}
private IEnumerable<PreferencePane> GetPreferencePanes()
{
foreach (PreferencePaneContainer preferencePaneContainer in preferencePaneSplitContainer.Panel2.Controls)
yield return preferencePaneContainer.PreferencePane;
}
private static PreferencePane CreatePlaceholderPreferencePane()
{
return new PlaceholderPreferencePane();
}
private static TreeNode FindTreeNodeByName(TreeNodeCollection collection, string name)
{
foreach (TreeNode node in collection)
if (node.Text == name)
return node;
return null;
}
private void EnsurePaneVisible()
{
TreeNode treeNode = preferencePaneTree.SelectedNode;
if (treeNode != null)
{
bool found = false;
foreach (PreferencePaneContainer preferencePaneContainer in preferencePaneSplitContainer.Panel2.Controls)
{
if (preferencePaneContainer.Tag == treeNode)
{
preferencePaneContainer.Visible = true;
found = true;
}
else
{
preferencePaneContainer.Visible = false;
}
}
if (!found)
{
PaneInfo paneInfo = (PaneInfo) treeNode.Tag;
PreferencePane preferencePane = paneInfo.Factory();
preferencePane.Dock = DockStyle.Fill;
preferencePane.Margin = new Padding(0, 0, 0, 0);
preferencePane.AutoSize = true;
preferencePane.AutoSizeMode = AutoSizeMode.GrowAndShrink;
preferencePane.PendingSettingsChangesChanged += preferencePane_PendingSettingsChangesChanged;
preferencePane.RequiresElevationChanged += preferencePane_ElevationRequiredChanged;
PreferencePaneContainer preferencePaneContainer = new PreferencePaneContainer();
preferencePaneContainer.Dock = DockStyle.Fill;
preferencePaneContainer.Margin = new Padding(0, 0, 0, 0);
preferencePaneContainer.AutoSize = true;
preferencePaneContainer.AutoSizeMode = AutoSizeMode.GrowAndShrink;
preferencePaneContainer.Tag = treeNode;
preferencePaneContainer.PreferencePane = preferencePane;
preferencePaneContainer.Title = paneInfo.Title;
preferencePaneSplitContainer.Panel2.Controls.Add(preferencePaneContainer);
RefreshPendingSettingsChangesState();
RefreshElevationRequiredState();
}
}
}
private void preferencePaneTree_AfterSelect(object sender, TreeViewEventArgs e)
{
EnsurePaneVisible();
}
private void PreferenceControlPanelTab_Load(object sender, EventArgs e)
{
if (preferencePaneTree.SelectedNode == null
&& preferencePaneTree.Nodes.Count != 0)
{
preferencePaneTree.SelectedNode = preferencePaneTree.Nodes[0];
}
preferencePaneTree.ExpandAll();
}
private void preferencePane_PendingSettingsChangesChanged(object sender, EventArgs e)
{
RefreshPendingSettingsChangesState();
}
private void preferencePane_ElevationRequiredChanged(object sender, EventArgs e)
{
RefreshElevationRequiredState();
}
private void RefreshPendingSettingsChangesState()
{
foreach (PreferencePane preferencePane in GetPreferencePanes())
{
if (preferencePane.PendingSettingsChanges)
{
PendingSettingsChanges = true;
return;
}
}
PendingSettingsChanges = false;
}
private void RefreshElevationRequiredState()
{
foreach (PreferencePane preferencePane in GetPreferencePanes())
{
if (preferencePane.RequiresElevation)
{
RequiresElevation = true;
return;
}
}
RequiresElevation = false;
}
private sealed class PaneInfo
{
public readonly Func<PreferencePane> Factory;
public readonly string Title;
public PaneInfo(Func<PreferencePane> factory, string title)
{
Factory = factory;
Title = title;
}
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class OTTextSprite : OTSprite
{
public string text;
public TextAsset textFile;
public int wordWrap = 0;
public bool justify = false;
private string _text;
private TextAsset _textFile;
private int _wordWrap = 0;
private bool _justify = false;
long _bytesLines = 0;
List<OTTextAlinea> _parsed = new List<OTTextAlinea>();
Vector3[] verts = new Vector3[] {};
Vector2[] _uv = new Vector2[] {};
int[] tris = new int[] {};
long GetBytes()
{
if (textFile!=null)
return _textFile.bytes.Length;
else
return text.Length;
}
string GetDY()
{
OTSpriteAtlas atlas = (spriteContainer as OTSpriteAtlas);
if (atlas == null) return "";
string dy = atlas.GetMeta("dy");
if (dy=="")
{
if (atlas.atlasData.Length>0)
{
OTAtlasData d = atlas.DataByName(""+((byte)'J'));
if (d==null)
d = atlas.DataByName("J");
if (d==null)
d = atlas.atlasData[0];
if (d!=null)
dy = ""+(d.offset.y + d.size.y);
}
else
dy = "50";
}
return dy;
}
void ParseText()
{
_bytesLines = GetBytes();
char[] chars = text.ToCharArray();
if (textFile!=null)
chars = textFile.text.ToCharArray();
for (int p=0; p<_parsed.Count; p++)
_parsed[p].Clean();
_parsed.Clear();
int dy = System.Convert.ToUInt16(GetDY());
int yPosition = 0;
OTSpriteAtlas atlas = (spriteContainer as OTSpriteAtlas);
OTTextAlinea alinea = new OTTextAlinea(yPosition);
foreach(char c in chars) {
if (c=='\r') continue;
if (c=='\n')
{
alinea.End();
_parsed.Add(alinea);
yPosition -= dy;
alinea = new OTTextAlinea(yPosition);
continue;
}
OTAtlasData data = atlas.DataByName(""+c);
OTContainer.Frame frame = atlas.FrameByName(""+c);
if (data==null || frame.name=="")
{
string charName = ((int)c).ToString();
data = atlas.DataByName(charName);
frame = atlas.FrameByName(charName);
}
if (data==null || frame.name=="")
{
data = atlas.DataByName(""+c+".png");
frame = atlas.FrameByName(""+c+".png");
}
if (data==null || frame.name=="")
{
byte b = System.Text.Encoding.ASCII.GetBytes("?")[0];
data = atlas.DataByName(""+b);
frame = atlas.FrameByName(""+b);
}
if (data==null || frame.name=="")
{
data = atlas.DataByName("32");
frame = atlas.FrameByName("32");
}
if (data!=null && frame.name == data.name)
{
if (data.name!="32")
{
Vector3[] verts = new Vector3[] {
new Vector3(frame.offset.x, -frame.offset.y,0),
new Vector3(frame.offset.x+frame.size.x, -frame.offset.y,0),
new Vector3(frame.offset.x+frame.size.x, -frame.offset.y-frame.size.y,0),
new Vector3(frame.offset.x, -frame.offset.y - frame.size.y,0)
};
alinea.Add(((char)c).ToString(), data, verts, frame.uv);
}
else
alinea.NextWord(data);
}
}
alinea.End();
_parsed.Add(alinea);
if (wordWrap > 0)
for (int p=0; p<_parsed.Count; p++)
{
_parsed[p].WordWrap(wordWrap, dy);
for (int pp = p+1; pp<_parsed.Count; pp++)
_parsed[pp].lines[0].yPosition -= (dy * (_parsed[p].lines.Count-1));
}
}
protected override Mesh GetMesh()
{
if (_spriteContainer==null || (_spriteContainer!=null && !_spriteContainer.isReady))
return null;
ParseText();
verts = new Vector3[] {};
_uv = new Vector2[] {};
tris = new int[] {};
Mesh mesh = InitMesh();
mesh.vertices = verts;
mesh.uv = _uv;
mesh.triangles = tris;
mesh.RecalculateBounds();
mesh.RecalculateNormals();
// calculate maximum width
int wi = 0;
for (int p = 0; p<_parsed.Count; p++)
for (int l=0; l<_parsed[p].lines.Count; l++)
if (_parsed[p].lines[l].width>wi)
wi = _parsed[p].lines[l].width;
for (int p = 0; p<_parsed.Count; p++)
for (int l=0; l<_parsed[p].lines.Count; l++)
{
Vector3[] lineVerts = _parsed[p].lines[l].GetVerts(wi,pivotPoint, (l==_parsed[p].lines.Count-1)?false:justify);
Vector2[] lineUV = _parsed[p].lines[l].uv;
int vIdx = verts.Length;
int uIdx = _uv.Length;
int tIdx = tris.Length;
System.Array.Resize<Vector3>(ref verts, verts.Length + lineVerts.Length);
lineVerts.CopyTo(verts,vIdx);
System.Array.Resize<int>(ref tris, tris.Length + (6 * _parsed[p].lines[l].charCount));
for (int tr = 0; tr< _parsed[p].lines[l].charCount; tr++)
{
new int[] {
vIdx, vIdx+1, vIdx+2,
vIdx+2, vIdx+3, vIdx
}.CopyTo(tris, tIdx);
vIdx += 4;
tIdx += 6;
}
System.Array.Resize<Vector2>(ref _uv, _uv.Length + lineUV.Length );
lineUV.CopyTo(_uv, uIdx);
}
mesh.vertices = TranslatePivotVerts(mesh, verts);
mesh.uv = _uv;
mesh.triangles = tris;
mesh.RecalculateBounds();
mesh.RecalculateNormals();
return mesh;
}
protected override void AfterMesh()
{
base.AfterMesh();
if (otTransform.parent!=null && otTransform.parent.GetComponent("OTSpriteBatch")!=null)
otTransform.parent.SendMessage("SpriteAfterMesh",this,SendMessageOptions.DontRequireReceiver);
if (otCollider!=null && otCollider is BoxCollider)
{
BoxCollider b = (otCollider as BoxCollider);
b.center = mesh.bounds.center;
b.size = mesh.bounds.extents*2;
}
}
//-----------------------------------------------------------------------------
// overridden subclass methods
//-----------------------------------------------------------------------------
protected override void CheckSettings()
{
if (_spriteContainer!=null && _spriteContainer.isReady)
{
if (_spriteContainer_ != spriteContainer)
meshDirty = true;
}
else
{
if (spriteContainer==null && _spriteContainer_!=null)
meshDirty = true;
}
base.CheckSettings();
}
protected override string GetTypeName()
{
return "Text";
}
protected override void HandleUV()
{
if (spriteContainer != null && spriteContainer.isReady)
{
}
}
protected override void Clean()
{
adjustFrameSize = false;
base.Clean();
offset = Vector2.zero;
}
//-----------------------------------------------------------------------------
// class methods
//-----------------------------------------------------------------------------
protected override void Awake()
{
base.Awake();
_text = text;
_textFile = textFile;
_wordWrap = wordWrap;
_justify = justify;
if (lastContainer!=null && _spriteContainer == null)
{
_spriteContainer = lastContainer;
_tintColor = lastColor;
_materialReference = lastMatRef;
_depth = lastDepth;
}
}
protected override void Start()
{
base.Start();
}
public static OTContainer lastContainer = null;
public static Color lastColor;
public static string lastMatRef;
public static int lastDepth;
// Update is called once per frame
protected override void Update()
{
if (spriteContainer==null || (spriteContainer!=null && !spriteContainer.isReady))
return;
if (Application.isEditor)
{
lastContainer = spriteContainer;
lastColor = tintColor;
lastMatRef = materialReference;
lastDepth = depth;
if (wordWrap<0) wordWrap = 0;
}
if (_text!=text || _textFile!=textFile || _bytesLines != GetBytes() ||
_wordWrap!=wordWrap || _justify!=justify )
{
_text = text;
_textFile = textFile;
_wordWrap = wordWrap;
_justify = justify;
meshDirty = true;
}
base.Update();
}
}
class OTTextAlinea
{
public List<OTTextLine> lines = new List<OTTextLine>();
public OTTextAlinea(int yPosition)
{
lines.Add(new OTTextLine(yPosition, true));
}
public void Clean()
{
for (int l=0; l<lines.Count; l++)
lines[l].Clean();
lines.Clear();
}
public void Add(string c, OTAtlasData data, Vector3[] verts, Vector2[] uv)
{
lines[lines.Count-1].Add(c, data, verts, uv);
}
public void NextWord(OTAtlasData space)
{
lines[lines.Count-1].NextWord(space);
}
public void End()
{
lines[lines.Count-1].End();
}
public void WordWrap(int wrapWidth, int dy)
{
List<OTTextLine> _lines = new List<OTTextLine>();
for (int l=0; l<lines.Count; l++)
_lines.AddRange(lines[l].WordWrap(wrapWidth, dy));
if (_lines.Count>1)
{
lines.Clear();
lines.AddRange(_lines);
}
}
}
class OTTextLine
{
public int charCount;
public int yPosition;
public string text
{
get
{
string res = "";
for (int w=0; w<words.Count; w++)
{
res += words[w].text;
if (w<words.Count-1)
res +=" ";
}
return res;
}
}
public Vector2[] uv
{
get
{
Vector2[] _uv = new Vector2[]{};
for (int w=0; w<words.Count; w++)
{
Vector2[] wUV = words[w].uv;
System.Array.Resize<Vector2>(ref _uv, _uv.Length + wUV.Length);
wUV.CopyTo(_uv, _uv.Length - wUV.Length);
}
return _uv;
}
}
public Vector3[] GetVerts(int maxWidth, Vector2 pivot, bool justify)
{
int tt = 0;
float twx = 0;
float spacing = 0;
if (words.Count>1)
spacing = (maxWidth - width)/(words.Count-1);
if (maxWidth>0 && !justify)
twx = (float)(maxWidth - width) * (pivot.x + 0.5f);
Vector3[] _verts = new Vector3[]{};
for (int w=0; w<words.Count; w++)
{
Vector3[] wVerts = words[w].verts;
if (tt>0 || twx > 0 || yPosition!=0)
{
Matrix4x4 mx = new Matrix4x4();
mx.SetTRS(new Vector3(tt+twx,yPosition,0), Quaternion.identity, Vector3.one);
for (int i=0; i<wVerts.Length; i++)
wVerts[i] = mx.MultiplyPoint3x4(wVerts[i]);
}
tt += words[w].width + words[w].space;
if (justify)
tt+=(int)spacing;
System.Array.Resize<Vector3>(ref _verts, _verts.Length + wVerts.Length);
wVerts.CopyTo(_verts, _verts.Length - wVerts.Length);
}
return _verts;
}
public int width = 0;
public List<OTTextWord> words = new List<OTTextWord>();
public void Clean()
{
width = 0;
charCount = 0;
for (int w=0; w<words.Count; w++)
words[w].Clean();
words.Clear();
}
OTTextWord word;
public OTTextLine(int yPosition, bool createWord)
{
this.yPosition = yPosition;
word = null;
if (createWord)
Word();
}
void Word()
{
words.Add(new OTTextWord());
word = words[words.Count-1];
}
public void NextWord(OTAtlasData space)
{
word.End(space);
Word();
}
public void End()
{
if (word!=null)
word.End(null);
width = 0;
charCount = 0;
for (int i=0; i<words.Count; i++)
{
width += (words[i].width + words[i].space);
charCount += words[i].atlasData.Count;
}
}
public void Add(string c, OTAtlasData data, Vector3[] verts, Vector2[] uv )
{
word.Add(c, data, verts, uv);
}
public List<OTTextLine> WordWrap(int wrapWidth, int dy)
{
List<OTTextLine> wLines = new List<OTTextLine>();
if (words.Count>0)
{
OTTextLine line = new OTTextLine(yPosition, false);
wLines.Add(line);
int ww = 0; int yp = yPosition;
for (int w=0; w<words.Count; w++)
{
line.words.Add(words[w]);
if (w < words.Count-1)
{
ww += words[w].width;
if (ww >= wrapWidth || ww + words[w].space >= wrapWidth || ww + words[w+1].width > wrapWidth)
{
// wrap
ww = 0;
yp -= dy;
line.End();
line = new OTTextLine(yp, false);
wLines.Add(line);
}
else
ww += words[w].space;
}
}
line.End();
}
return wLines;
}
}
class OTTextWord
{
public int width = 0;
public string text = "";
public List<OTAtlasData> atlasData = new List<OTAtlasData>();
public List<int> txList = new List<int>();
public int space = 0;
public Vector3[] verts = new Vector3[] {};
public Vector2[] uv = new Vector2[] {};
public void Clean()
{
atlasData.Clear();
txList.Clear();
System.Array.Resize(ref verts, 0);
System.Array.Resize(ref uv, 0);
}
public void Add(string c, OTAtlasData data, Vector3[] verts, Vector2[] uv)
{
text+=c;
int tx = 0;
string dx = data.GetMeta("dx");
if (dx=="")
tx = (int)(data.offset.x + data.size.x);
else
tx = System.Convert.ToUInt16(dx);
txList.Add(tx);
atlasData.Add(data);
int tt = 0;
for (int i=0; i<txList.Count-1; i++)
tt+=txList[i];
Matrix4x4 mx = new Matrix4x4();
mx.SetTRS(new Vector3(tt,0,0), Quaternion.identity, Vector3.one);
for (int i=0; i<verts.Length; i++)
verts[i] = mx.MultiplyPoint3x4(verts[i]);
System.Array.Resize<Vector3>(ref this.verts, this.verts.Length + verts.Length);
verts.CopyTo(this.verts, this.verts.Length - verts.Length);
System.Array.Resize<Vector2>(ref this.uv, this.uv.Length + uv.Length);
uv.CopyTo(this.uv, this.uv.Length - uv.Length);
}
public void End(OTAtlasData space)
{
width = 0;
string dx = "";
for (int i=0; i<atlasData.Count; i++)
{
dx = atlasData[i].GetMeta("dx");
if (dx=="")
width += (int)(atlasData[i].offset.x + atlasData[i].size.x);
else
width += System.Convert.ToUInt16(dx);
}
if (space!=null)
{
dx = space.GetMeta("dx");
if (dx=="")
this.space = (int)(space.offset.x + space.size.x);
else
this.space = System.Convert.ToUInt16(dx);
if (this.space == 0)
this.space = 30;
}
}
}
| |
// *******************************************************************************************************
// Product: DotSpatial.Symbology.DesktopRasterExt.cs
// Description: Methods for draw rasters.
// Copyright & License: See www.DotSpatial.org.
// *******************************************************************************************************
// Contributor(s): Open source contributors may list themselves and their modifications here.
// Contribution of code constitutes transferral of copyright from authors to DotSpatial copyright holders.
// *******************************************************************************************************
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using DotSpatial.Data;
using DotSpatial.NTSExtension;
namespace DotSpatial.Symbology
{
public static class DesktopRasterExt
{
#region CreateHillShade
/// <summary>
/// Create Hillshade of values ranging from 0 to 1, or -1 for no-data regions.
/// This should be a little faster since we are accessing the Data field directly instead of working
/// through a value parameter.
/// </summary>
/// <param name="raster">The raster to create the hillshade from.</param>
/// <param name="shadedRelief">An implementation of IShadedRelief describing how the hillshade should be created.</param>
/// <param name="progressHandler">An implementation of IProgressHandler for progress messages</param>
public static float[][] CreateHillShade(this IRaster raster, IShadedRelief shadedRelief, IProgressHandler progressHandler = null)
{
if (progressHandler == null) progressHandler = raster.ProgressHandler;
var pm = new ProgressMeter(progressHandler, SymbologyMessageStrings.DesktopRasterExt_CreatingShadedRelief, raster.NumRows);
Func<int, int, double> getValue;
if (raster.DataType == typeof(int))
{
var r = raster.ToRaster<int>();
getValue = (row, col) => r.Data[row][col];
}
else if (raster.DataType == typeof(float))
{
var r = raster.ToRaster<float>();
getValue = (row, col) => r.Data[row][col];
}
else if (raster.DataType == typeof(short))
{
var r = raster.ToRaster<short>();
getValue = (row, col) => r.Data[row][col];
}
else if (raster.DataType == typeof(byte))
{
var r = raster.ToRaster<byte>();
getValue = (row, col) => r.Data[row][col];
}
else if (raster.DataType == typeof(double))
{
var r = raster.ToRaster<double>();
getValue = (row, col) => r.Data[row][col];
}
else
{
getValue = (row, col) => raster.Value[row, col];
}
return CreateHillShadeT(raster, getValue, shadedRelief, pm);
}
/// <summary>
/// Create Hillshade of values ranging from 0 to 1, or -1 for no-data regions.
/// This should be a little faster since we are accessing the Data field directly instead of working
/// through a value parameter.
/// </summary>
/// <param name="raster">The raster to create the hillshade from.</param>
/// <param name="shadedRelief">An implementation of IShadedRelief describing how the hillshade should be created.</param>
/// <param name="progressMeter">An implementation of IProgressHandler for progress messages</param>
public static float[][] CreateHillShadeT<T>(this Raster<T> raster, IShadedRelief shadedRelief, ProgressMeter progressMeter) where T : IEquatable<T>, IComparable<T>
{
return CreateHillShadeT(raster, (row, col) => raster.Data[row][col], shadedRelief, progressMeter);
}
private static float[][] CreateHillShadeT<T>(this IRaster raster,
Func<int, int, T> getValue,
IShadedRelief shadedRelief, ProgressMeter progressMeter) where T : IEquatable<T>, IComparable<T>
{
if (!raster.IsInRam) return null;
int numCols = raster.NumColumns;
int numRows = raster.NumRows;
var noData = Convert.ToSingle(raster.NoDataValue);
float extrusion = shadedRelief.Extrusion;
float elevationFactor = shadedRelief.ElevationFactor;
float lightIntensity = shadedRelief.LightIntensity;
float ambientIntensity = shadedRelief.AmbientIntensity;
FloatVector3 lightDirection = shadedRelief.GetLightDirection();
float[] aff = new float[6]; // affine coefficients converted to float format
for (int i = 0; i < 6; i++)
{
aff[i] = Convert.ToSingle(raster.Bounds.AffineCoefficients[i]);
}
float[][] hillshade = new float[numRows][];
if (progressMeter != null) progressMeter.BaseMessage = "Creating Shaded Relief";
for (int row = 0; row < numRows; row++)
{
hillshade[row] = new float[numCols];
for (int col = 0; col < numCols; col++)
{
// 3D position vectors of three points to create a triangle.
FloatVector3 v1 = new FloatVector3(0f, 0f, 0f);
FloatVector3 v2 = new FloatVector3(0f, 0f, 0f);
FloatVector3 v3 = new FloatVector3(0f, 0f, 0f);
float val = Convert.ToSingle(getValue(row, col));
// Cannot compute polygon ... make the best guess)
if (col >= numCols - 1 || row <= 0)
{
if (col >= numCols - 1 && row <= 0)
{
v1.Z = val;
v2.Z = val;
v3.Z = val;
}
else if (col >= numCols - 1)
{
v1.Z = Convert.ToSingle(getValue(row, col - 1)); // 3 - 2
v2.Z = Convert.ToSingle(getValue(row - 1, col)); // | /
v3.Z = Convert.ToSingle(getValue(row - 1, col - 1)); // 1 *
}
else if (row <= 0)
{
v1.Z = Convert.ToSingle(getValue(row + 1, col)); // 3* 2
v2.Z = Convert.ToSingle(getValue(row, col + 1)); // | /
v3.Z = val; // 1
}
}
else
{
v1.Z = val; // 3 - 2
v2.Z = Convert.ToSingle(getValue(row - 1, col + 1)); // | /
v3.Z = Convert.ToSingle(getValue(row - 1, col)); // 1*
}
// Test for no-data values and don't calculate hillshade in that case
if (v1.Z == noData || v2.Z == noData || v3.Z == noData)
{
hillshade[row][col] = -1; // should never be negative otherwise.
continue;
}
// Apply the Conversion Factor to put elevation into the same range as lat/lon
v1.Z = v1.Z * elevationFactor * extrusion;
v2.Z = v2.Z * elevationFactor * extrusion;
v3.Z = v3.Z * elevationFactor * extrusion;
// Complete the vectors using the latitude/longitude coordinates
v1.X = aff[0] + aff[1] * col + aff[2] * row;
v1.Y = aff[3] + aff[4] * col + aff[5] * row;
v2.X = aff[0] + aff[1] * (col + 1) + aff[2] * (row + 1);
v2.Y = aff[3] + aff[4] * (col + 1) + aff[5] * (row + 1);
v3.X = aff[0] + aff[1] * col + aff[2] * (row + 1);
v3.Y = aff[3] + aff[4] * col + aff[5] * (row + 1);
// We need two direction vectors in order to obtain a cross product
FloatVector3 dir2 = FloatVector3.Subtract(v2, v1); // points from 1 to 2
FloatVector3 dir3 = FloatVector3.Subtract(v3, v1); // points from 1 to 3
FloatVector3 cross = FloatVector3.CrossProduct(dir3, dir2); // right hand rule - cross direction should point into page... reflecting more if light direction is in the same direction
// Normalizing this vector ensures that this vector is a pure direction and won't affect the intensity
cross.Normalize();
// Hillshade now has an "intensity" modifier that should be applied to the R, G and B values of the color found at each pixel.
hillshade[row][col] = FloatVector3.Dot(cross, lightDirection) * lightIntensity + ambientIntensity;
}
if (progressMeter != null) progressMeter.Next();
}
// Setting this indicates that a hillshade has been created more recently than characteristics have been changed.
shadedRelief.HasChanged = false;
return hillshade;
}
#endregion
#region DrawToBitmap
/// <summary>
/// Creates a bitmap from this raster using the specified rasterSymbolizer
/// </summary>
/// <param name="raster">The raster to draw to a bitmap</param>
/// <param name="rasterSymbolizer">The raster symbolizer to use for assigning colors</param>
/// <param name="bitmap">This must be an Format32bbpArgb bitmap that has already been saved to a file so that it exists.</param>
/// <param name="progressHandler">The progress handler to use.</param>
/// <exception cref="ArgumentNullException">rasterSymbolizer cannot be null</exception>
public static void DrawToBitmap(this IRaster raster, IRasterSymbolizer rasterSymbolizer, Bitmap bitmap, IProgressHandler progressHandler = null)
{
if (raster == null) throw new ArgumentNullException("raster");
if (rasterSymbolizer == null) throw new ArgumentNullException("rasterSymbolizer");
if (bitmap == null) throw new ArgumentNullException("bitmap");
if (rasterSymbolizer.Scheme.Categories == null || rasterSymbolizer.Scheme.Categories.Count == 0) return;
BitmapData bmpData;
var rect = new Rectangle(0, 0, raster.NumColumns, raster.NumRows);
try
{
bmpData = bitmap.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
}
catch (Exception)
{
// if they have not saved the bitmap yet, it can cause an exception
var ms = new MemoryStream();
bitmap.Save(ms, ImageFormat.Bmp);
ms.Position = 0;
bmpData = bitmap.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
}
var numRows = raster.NumRows;
var numColumns = raster.NumColumns;
// Prepare progress meter
if (progressHandler == null) progressHandler = raster.ProgressHandler;
var pm = new ProgressMeter(progressHandler, "Drawing to Bitmap", numRows);
if (numRows * numColumns < 100000) pm.StepPercent = 50;
if (numRows * numColumns < 500000) pm.StepPercent = 10;
if (numRows * numColumns < 1000000) pm.StepPercent = 5;
DrawToBitmap(raster, rasterSymbolizer, bmpData.Scan0, bmpData.Stride, pm);
bitmap.UnlockBits(bmpData);
rasterSymbolizer.ColorSchemeHasUpdated = true;
}
/// <summary>
/// Creates a bitmap from this raster using the specified rasterSymbolizer
/// </summary>
/// <param name="raster">The raster to draw to a bitmap</param>
/// <param name="rasterSymbolizer">The raster symbolizer to use for assigning colors</param>
/// <param name="rgbData">Byte values representing the ARGB image bytes</param>
/// <param name="stride">The stride</param>
/// <param name="pm">The progress meter to use.</param>
/// <exception cref="ArgumentNullException">rasterSymbolizer cannot be null</exception>
public static void DrawToBitmapT<T>(Raster<T> raster, IRasterSymbolizer rasterSymbolizer, byte[] rgbData, int stride, ProgressMeter pm)
where T : struct, IEquatable<T>, IComparable<T>
{
DrawToBitmapT(raster, GetNoData(raster), (row, col) => raster.Data[row][col],
i => rgbData[i], (i, b) => rgbData[i] = b, rasterSymbolizer, stride, pm);
if (rasterSymbolizer.IsSmoothed)
{
var mySmoother = new Smoother(stride, raster.NumColumns, raster.NumRows, rgbData, pm.ProgressHandler);
mySmoother.Smooth();
}
}
private static void DrawToBitmapT<T>(Raster<T> raster, IRasterSymbolizer rasterSymbolizer, IntPtr rgbData, int stride, ProgressMeter pm)
where T : struct, IEquatable<T>, IComparable<T>
{
DrawToBitmapT(raster, GetNoData(raster), (row, col) => raster.Data[row][col],
i => Marshal.ReadByte(rgbData, i), (i, b) => Marshal.WriteByte(rgbData, i, b), rasterSymbolizer, stride, pm);
if (rasterSymbolizer.IsSmoothed)
{
var mySmoother = new Smoother(stride, raster.NumColumns, raster.NumRows, rgbData, pm.ProgressHandler);
mySmoother.Smooth();
}
}
public static void DrawToBitmap(this IRaster raster, IRasterSymbolizer rasterSymbolizer, byte[] rgbData, int stride, ProgressMeter pm)
{
if (raster.DataType == typeof(int))
{
DrawToBitmapT(raster.ToRaster<int>(), rasterSymbolizer, rgbData, stride, pm);
}
else if (raster.DataType == typeof(float))
{
DrawToBitmapT(raster.ToRaster<float>(), rasterSymbolizer, rgbData, stride, pm);
}
else if (raster.DataType == typeof(short))
{
DrawToBitmapT(raster.ToRaster<short>(), rasterSymbolizer, rgbData, stride, pm);
}
else if (raster.DataType == typeof(byte))
{
DrawToBitmapT(raster.ToRaster<byte>(), rasterSymbolizer, rgbData, stride, pm);
}
else if (raster.DataType == typeof(double))
{
DrawToBitmapT(raster.ToRaster<double>(), rasterSymbolizer, rgbData, stride, pm);
}
else
{
DrawToBitmapT(raster, raster.NoDataValue, (row, col) => raster.Value[row, col],
i => rgbData[i], (i, b) => rgbData[i] = b, rasterSymbolizer, stride, pm);
if (rasterSymbolizer.IsSmoothed)
{
var mySmoother = new Smoother(stride, raster.NumColumns, raster.NumRows, rgbData, pm.ProgressHandler);
mySmoother.Smooth();
}
}
}
private static void DrawToBitmap(IRaster raster, IRasterSymbolizer rasterSymbolizer, IntPtr rgbData, int stride, ProgressMeter pm)
{
if (raster.DataType == typeof(int))
{
DrawToBitmapT(raster.ToRaster<int>(), rasterSymbolizer, rgbData, stride, pm);
}
else if (raster.DataType == typeof(float))
{
DrawToBitmapT(raster.ToRaster<float>(), rasterSymbolizer, rgbData, stride, pm);
}
else if (raster.DataType == typeof(short))
{
DrawToBitmapT(raster.ToRaster<short>(), rasterSymbolizer, rgbData, stride, pm);
}
else if (raster.DataType == typeof(byte))
{
DrawToBitmapT(raster.ToRaster<byte>(), rasterSymbolizer, rgbData, stride, pm);
}
else if (raster.DataType == typeof(double))
{
DrawToBitmapT(raster.ToRaster<double>(), rasterSymbolizer, rgbData, stride, pm);
}
else
{
DrawToBitmapT(raster, raster.NoDataValue, (row, col) => raster.Value[row, col],
i => Marshal.ReadByte(rgbData, i), (i, b) => Marshal.WriteByte(rgbData, i, b), rasterSymbolizer, stride, pm);
if (rasterSymbolizer.IsSmoothed)
{
var mySmoother = new Smoother(stride, raster.NumColumns, raster.NumRows, rgbData, pm.ProgressHandler);
mySmoother.Smooth();
}
}
}
private static void DrawToBitmapT<T>(IRaster raster, T noData, Func<int, int, T> getValue, Func<int, byte> getByte,
Action<int, byte> setByte, IRasterSymbolizer rasterSymbolizer, int stride, ProgressMeter pm)
where T : struct, IEquatable<T>, IComparable<T>
{
if (raster == null) throw new ArgumentNullException("raster");
if (rasterSymbolizer == null) throw new ArgumentNullException("rasterSymbolizer");
if (rasterSymbolizer.Scheme.Categories == null || rasterSymbolizer.Scheme.Categories.Count == 0) return;
float[][] hillshade = null;
if (rasterSymbolizer.ShadedRelief.IsUsed)
{
pm.BaseMessage = "Calculating Shaded Relief";
hillshade = rasterSymbolizer.HillShade ?? raster.CreateHillShadeT(getValue, rasterSymbolizer.ShadedRelief, pm);
}
pm.BaseMessage = "Calculating Colors";
var sets = GetColorSets<T>(rasterSymbolizer.Scheme.Categories);
var noDataColor = Argb.FromColor(rasterSymbolizer.NoDataColor);
for (int row = 0; row < raster.NumRows; row++)
{
for (int col = 0; col < raster.NumColumns; col++)
{
var value = getValue(row, col);
Argb argb;
if (value.Equals(noData))
{
argb = noDataColor;
}
else
{
// Usually values are not random, so check neighboring previous cells for same color
int? srcOffset = null;
if (col > 0)
{
if (value.Equals(getValue(row, col - 1)))
{
srcOffset = Offset(row, col - 1, stride);
}
}
if (srcOffset == null && row > 0)
{
if (value.Equals(getValue(row - 1, col)))
{
srcOffset = Offset(row - 1, col, stride);
}
}
if (srcOffset != null)
{
argb = new Argb(getByte((int)srcOffset + 3),
getByte((int)srcOffset + 2),
getByte((int)srcOffset + 1),
getByte((int)srcOffset));
}
else
{
argb = GetColor(sets, value);
}
}
if (hillshade != null)
{
if (hillshade[row][col] == -1 || float.IsNaN(hillshade[row][col]))
{
argb = new Argb(argb.A, noDataColor.R, noDataColor.G, noDataColor.B);
}
else
{
var red = (int)(argb.R * hillshade[row][col]);
var green = (int)(argb.G * hillshade[row][col]);
var blue = (int)(argb.B * hillshade[row][col]);
argb = new Argb(argb.A, red, green, blue);
}
}
var offset = Offset(row, col, stride);
setByte(offset, argb.B);
setByte(offset + 1, argb.G);
setByte(offset + 2, argb.R);
setByte(offset + 3, argb.A);
}
pm.Next();
}
}
#endregion
#region PaintColorSchemeToBitmap
/// <summary>
/// Creates a bitmap using only the colorscheme, even if a hillshade was specified.
/// </summary>
/// <param name="raster">The Raster containing values that need to be drawn to the bitmap as a color scheme.</param>
/// <param name="rasterSymbolizer">The raster symbolizer to use.</param>
/// <param name="bitmap">The bitmap to edit. Ensure that this has been created and saved at least once.</param>
/// <param name="progressHandler">An IProgressHandler implementation to receive progress updates.</param>
/// <exception cref="ArgumentNullException">rasterSymbolizer cannot be null.</exception>
public static void PaintColorSchemeToBitmap(this IRaster raster, IRasterSymbolizer rasterSymbolizer, Bitmap bitmap, IProgressHandler progressHandler)
{
if (raster.DataType == typeof(int))
{
PaintColorSchemeToBitmapT(raster.ToRaster<int>(), rasterSymbolizer, bitmap, progressHandler);
}
else if (raster.DataType == typeof(float))
{
PaintColorSchemeToBitmapT(raster.ToRaster<float>(), rasterSymbolizer, bitmap, progressHandler);
}
else if (raster.DataType == typeof(short))
{
PaintColorSchemeToBitmapT(raster.ToRaster<short>(), rasterSymbolizer, bitmap, progressHandler);
}
else if (raster.DataType == typeof(byte))
{
PaintColorSchemeToBitmapT(raster.ToRaster<byte>(), rasterSymbolizer, bitmap, progressHandler);
}
else if (raster.DataType == typeof(double))
{
PaintColorSchemeToBitmapT(raster.ToRaster<double>(), rasterSymbolizer, bitmap, progressHandler);
}
else
{
PaintColorSchemeToBitmapT(raster, raster.NoDataValue, (row, col) => raster.Value[row, col], rasterSymbolizer, bitmap, progressHandler);
}
}
/// <summary>
/// Creates a bitmap using only the colorscheme, even if a hillshade was specified.
/// </summary>
/// <param name="raster">The Raster containing values that need to be drawn to the bitmap as a color scheme.</param>
/// <param name="rasterSymbolizer">The raster symbolizer to use.</param>
/// <param name="bitmap">The bitmap to edit. Ensure that this has been created and saved at least once.</param>
/// <param name="progressHandler">An IProgressHandler implementation to receive progress updates.</param>
/// <exception cref="ArgumentNullException"><see cref="rasterSymbolizer"/> cannot be null, <see cref="raster"/> cannot be null, <see cref="bitmap"/> cannot be null</exception>
public static void PaintColorSchemeToBitmapT<T>(this Raster<T> raster, IRasterSymbolizer rasterSymbolizer, Bitmap bitmap, IProgressHandler progressHandler)
where T : struct, IEquatable<T>, IComparable<T>
{
PaintColorSchemeToBitmapT(raster, GetNoData(raster), (row, col) => raster.Data[row][col],
rasterSymbolizer, bitmap, progressHandler);
}
private static void PaintColorSchemeToBitmapT<T>(this IRaster raster,
T noData, Func<int, int, T> getValue,
IRasterSymbolizer rasterSymbolizer, Bitmap bitmap, IProgressHandler progressHandler)
where T : struct, IEquatable<T>, IComparable<T>
{
if (raster == null) throw new ArgumentNullException("raster");
if (rasterSymbolizer == null) throw new ArgumentNullException("rasterSymbolizer");
if (bitmap == null) throw new ArgumentNullException("bitmap");
if (rasterSymbolizer.Scheme.Categories == null || rasterSymbolizer.Scheme.Categories.Count == 0) return;
BitmapData bmpData;
var numRows = raster.NumRows;
var numColumns = raster.NumColumns;
var rect = new Rectangle(0, 0, numColumns, numRows);
try
{
bmpData = bitmap.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
}
catch
{
var ms = new MemoryStream();
bitmap.Save(ms, ImageFormat.MemoryBmp);
ms.Position = 0;
bmpData = bitmap.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
}
// Prepare progress meter
var pm = new ProgressMeter(progressHandler, SymbologyMessageStrings.DesktopRasterExt_PaintingColorScheme, numRows);
if (numRows * numColumns < 100000) pm.StepPercent = 50;
if (numRows * numColumns < 500000) pm.StepPercent = 10;
if (numRows * numColumns < 1000000) pm.StepPercent = 5;
var sets = GetColorSets<T>(rasterSymbolizer.Scheme.Categories);
var noDataColor = Argb.FromColor(rasterSymbolizer.NoDataColor);
var alpha = Argb.ByteRange(Convert.ToInt32(rasterSymbolizer.Opacity * 255));
var ptr = bmpData.Scan0;
for (var row = 0; row < numRows; row++)
{
for (var col = 0; col < numColumns; col++)
{
var val = getValue(row, col);
Argb argb;
if (val.Equals(noData))
{
argb = noDataColor;
}
else
{
// Usually values are not random, so check neighboring previous cells for same color
int? srcOffset = null;
if (col > 0)
{
if (val.Equals(getValue(row, col - 1)))
{
srcOffset = Offset(row, col - 1, bmpData.Stride);
}
}
if (srcOffset == null && row > 0)
{
if (val.Equals(getValue(row - 1, col)))
{
srcOffset = Offset(row - 1, col, bmpData.Stride);
}
}
if (srcOffset != null)
{
argb = new Argb(
Marshal.ReadByte(ptr, (int)srcOffset + 3),
Marshal.ReadByte(ptr, (int)srcOffset + 2),
Marshal.ReadByte(ptr, (int)srcOffset + 1),
Marshal.ReadByte(ptr, (int)srcOffset));
}
else
{
var color = GetColor(sets, val);
argb = new Argb(alpha, color.R, color.G, color.B);
}
}
var offset = Offset(row, col, bmpData.Stride);
Marshal.WriteByte(ptr, offset, argb.B);
Marshal.WriteByte(ptr, offset + 1, argb.G);
Marshal.WriteByte(ptr, offset + 2, argb.R);
Marshal.WriteByte(ptr, offset + 3, argb.A);
}
pm.CurrentValue = row;
}
pm.Reset();
if (rasterSymbolizer.IsSmoothed)
{
var mySmoother = new Smoother(bmpData.Stride, bmpData.Width, bmpData.Height, bmpData.Scan0, progressHandler);
mySmoother.Smooth();
}
bitmap.UnlockBits(bmpData);
rasterSymbolizer.ColorSchemeHasUpdated = true;
}
#endregion
private static List<ColorSet<T>> GetColorSets<T>(IEnumerable<IColorCategory> categories) where T : struct, IComparable<T>
{
var result = new List<ColorSet<T>>();
foreach (var c in categories)
{
var cs = new ColorSet<T>();
Color high = c.HighColor;
Color low = c.LowColor;
cs.Color = Argb.FromColor(low);
if (high != low)
{
cs.GradientModel = c.GradientModel;
cs.Gradient = true;
cs.MinA = low.A;
cs.MinR = low.R;
cs.MinG = low.G;
cs.MinB = low.B;
cs.RangeA = high.A - cs.MinA;
cs.RangeR = high.R - cs.MinR;
cs.RangeG = high.G - cs.MinG;
cs.RangeB = high.B - cs.MinB;
}
cs.Max = Global.MaximumValue<T>();
var testMax = Convert.ToDouble(cs.Max);
cs.Min = Global.MinimumValue<T>();
var testMin = Convert.ToDouble(cs.Min);
if (c.Range.Maximum != null && c.Range.Maximum < testMax)
{
if (c.Range.Maximum < testMin)
cs.Max = cs.Min;
else
cs.Max = (T)Convert.ChangeType(c.Range.Maximum.Value, typeof(T));
}
if (c.Range.Minimum != null && c.Range.Minimum > testMin)
{
if (c.Range.Minimum > testMax)
cs.Min = Global.MaximumValue<T>();
else
cs.Min = (T)Convert.ChangeType(c.Range.Minimum.Value, typeof(T));
}
cs.MinInclusive = c.Range.MinIsInclusive;
cs.MaxInclusive = c.Range.MaxIsInclusive;
result.Add(cs);
}
// The normal order uses "overwrite" behavior, so that each color is drawn
// if it qualifies until all the ranges are tested, overwriting previous.
// This can be mimicked by going through the sets in reverse and choosing
// the first that qualifies. For lots of color ranges, opting out of
// a large portion of the range testing should be faster.
result.Reverse();
return result;
}
private static Argb GetColor<T>(IEnumerable<ColorSet<T>> sets, T value) where T : struct, IComparable<T>
{
foreach (var set in sets)
{
if (set.Contains(value))
{
if (!set.Gradient) return set.Color;
if (set.Min == null || set.Max == null) return set.Color;
double lowVal = Convert.ToDouble(set.Min.Value);
double range = Math.Abs(Convert.ToDouble(set.Max.Value) - lowVal);
double p = 0; // the portion of the range, where 0 is LowValue & 1 is HighValue
double ht;
double dVal = Convert.ToDouble(value);
switch (set.GradientModel)
{
case GradientModel.Linear:
p = (dVal - lowVal) / range;
break;
case GradientModel.Exponential:
ht = dVal;
if (ht < 1) ht = 1.0;
if (range > 1)
p = (Math.Pow(ht - lowVal, 2) / Math.Pow(range, 2));
else
return set.Color;
break;
case GradientModel.Logarithmic:
ht = dVal;
if (ht < 1) ht = 1.0;
if (range > 1.0 && ht - lowVal > 1.0)
p = Math.Log(ht - lowVal) / Math.Log(range);
else
return set.Color;
break;
}
return new Argb(
set.MinA + (int)(set.RangeA * p),
set.MinR + (int)(set.RangeR * p),
set.MinG + (int)(set.RangeG * p),
set.MinB + (int)(set.RangeB * p));
}
}
return Argb.FromColor(Color.Transparent);
}
private static T GetNoData<T>(Raster<T> raster) where T : IEquatable<T>, IComparable<T>
{
// Get nodata value.
var noData = default(T);
try
{
noData = (T)Convert.ChangeType(raster.NoDataValue, typeof(T));
}
catch (OverflowException)
{
// For whatever reason, GDAL occasionally is reporting noDataValues
// That will not fit in the specified band type. Is this due to a
// malformed GeoTiff file?
// http://dotspatial.codeplex.com/workitem/343
Trace.WriteLine("OverflowException while getting NoDataValue");
}
return noData;
}
private static int Offset(int row, int col, int stride)
{
return row * stride + col * 4;
}
/// <summary>
/// Obtains an set of unique values. If there are more than maxCount values, the process stops and overMaxCount is set to true.
/// </summary>
/// <param name="raster">the raster to obtain the unique values from.</param>
/// <param name="maxCount">An integer specifying the maximum number of values to add to the list of unique values</param>
/// <param name="overMaxCount">A boolean that will be true if the process was halted prematurely.</param>
/// <returns>A set of doubles representing the independant values.</returns>
public static ISet<double> GetUniqueValues(this IRaster raster, int maxCount, out bool overMaxCount)
{
overMaxCount = false;
var result = new HashSet<double>();
var totalPossibleCount = int.MaxValue;
// Optimization for integer types
if (raster.DataType == typeof(byte) ||
raster.DataType == typeof(int) ||
raster.DataType == typeof(sbyte) ||
raster.DataType == typeof(uint) ||
raster.DataType == typeof(short) ||
raster.DataType == typeof(ushort))
{
totalPossibleCount = (int)(raster.Maximum - raster.Minimum + 1);
}
// NumRows and NumColumns - virtual properties, so copy them local variables for faster access
var numRows = raster.NumRows;
var numCols = raster.NumColumns;
var valueGrid = raster.Value;
for (var row = 0; row < numRows; row++)
for (var col = 0; col < numCols; col++)
{
double val = valueGrid[row, col];
if (result.Add(val))
{
if (result.Count > maxCount)
{
overMaxCount = true;
goto fin;
}
if (result.Count == totalPossibleCount)
goto fin;
}
}
fin:
return result;
}
/// <summary>
/// This will sample randomly from the raster, preventing duplicates.
/// If the sampleSize is larger than this raster, this returns all of the
/// values from the raster. If a "Sample" has been prefetched and stored
/// in the Sample array, then this will return that.
/// </summary>
/// <param name="raster"></param>
/// <param name="sampleSize"></param>
/// <returns></returns>
public static List<double> GetRandomValues(this IRaster raster, int sampleSize)
{
if (raster.Sample != null) return raster.Sample.ToList();
int numRows = raster.NumRows;
int numCols = raster.NumColumns;
List<double> result = new List<double>();
double noData = raster.NoDataValue;
if (numRows * numCols < sampleSize)
{
for (int row = 0; row < numRows; row++)
{
for (int col = 0; col < numCols; col++)
{
double val = raster.Value[row, col];
if (val != noData) result.Add(raster.Value[row, col]);
}
}
return result;
}
Random rnd = new Random(DateTime.Now.Millisecond);
if (numRows * (long)numCols < (long)sampleSize * 5 && numRows * (long)numCols < int.MaxValue)
{
// When the raster is only just barely larger than the sample size,
// we want to prevent lots of repeat guesses that fail (hit the same previously sampled values).
// We create a copy of all the values and sample from this reservoir while removing sampled values.
List<double> resi = new List<double>();
for (int row = 0; row < numRows; row++)
{
for (int col = 0; col < numCols; col++)
{
double val = raster.Value[row, col];
if (val != noData) resi.Add(val);
}
}
//int count = numRows * numCols; //this could failed if there's lot of noDataValues
long longcount = raster.NumValueCells;
int count = numRows * numCols;
if (count < int.MaxValue)
count = (int)longcount;
for (int i = 0; i < sampleSize; i++)
{
if (resi.Count == 0) break;
int indx = rnd.Next(count);
result.Add(resi[indx]);
resi.RemoveAt(indx);
count--;
}
raster.Sample = result;
return result;
}
// Use a HashSet here, because it has O(1) lookup for preventing duplicates
HashSet<long> exclusiveResults = new HashSet<long>();
int remaining = sampleSize;
while (remaining > 0)
{
int row = rnd.Next(numRows);
int col = rnd.Next(numCols);
long index = row * numCols + col;
if (exclusiveResults.Contains(index)) continue;
exclusiveResults.Add(index);
remaining--;
}
// Sorting is O(n ln(n)), but sorting once is better than using a SortedSet for previous lookups.
List<long> sorted = exclusiveResults.ToList();
sorted.Sort();
// Sorted values are much faster to read than reading values in at random, since the file actually
// is reading in a whole line at a time. If we can get more than one value from a line, then that
// is better than getting one value, discarding the cache and then comming back later for the value
// next to it.
result = raster.GetValues(sorted);
raster.Sample = result;
return result;
}
#region HelperClass: ColorSet
private class ColorSet<T>
where T : struct, IComparable<T>
{
public Argb Color; // for non bivalue case.
public bool Gradient;
public GradientModel GradientModel;
public T? Max;
public bool MaxInclusive;
public T? Min;
public int MinA;
public int MinB;
public int MinG;
public bool MinInclusive;
public int MinR;
public int RangeA;
public int RangeB;
public int RangeG;
public int RangeR;
public bool Contains(T value)
{
// Checking for nulls
if (Max == null && Min == null) return true;
if (Min == null)
return MaxInclusive ? value.CompareTo(Max.Value) <= 0 : value.CompareTo(Max.Value) < 0;
if (Max == null)
return MinInclusive ? value.CompareTo(Min.Value) >= 0 : value.CompareTo(Min.Value) > 0;
// Normal checking
double cMax = value.CompareTo(Max.Value);
if (cMax > 0 || (!MaxInclusive && cMax == 0)) return false; //value bigger than max or max excluded
double cMin = value.CompareTo(Min.Value);
if (cMin < 0 || (cMin == 0 && !MinInclusive)) return false; //value smaller than min or min excluded
return true;
}
}
#endregion
}
}
| |
/**
* FreeRDP: A Remote Desktop Protocol Client
* Time Zone Redirection Table Generator
*
* Copyright 2012 Marc-Andre Moreau <[email protected]>
*
* 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.Globalization;
using System.Collections.ObjectModel;
namespace TimeZones
{
struct SYSTEM_TIME_ENTRY
{
public UInt16 wYear;
public UInt16 wMonth;
public UInt16 wDayOfWeek;
public UInt16 wDay;
public UInt16 wHour;
public UInt16 wMinute;
public UInt16 wSecond;
public UInt16 wMilliseconds;
};
struct TIME_ZONE_RULE_ENTRY
{
public long TicksStart;
public long TicksEnd;
public Int32 DaylightDelta;
public SYSTEM_TIME_ENTRY StandardDate;
public SYSTEM_TIME_ENTRY DaylightDate;
};
struct TIME_ZONE_ENTRY
{
public string Id;
public UInt32 Bias;
public bool SupportsDST;
public string DisplayName;
public string StandardName;
public string DaylightName;
public string RuleTable;
public UInt32 RuleTableCount;
};
class TimeZones
{
static void Main(string[] args)
{
int i;
UInt32 index;
const string file = @"TimeZones.txt";
TimeZoneInfo.AdjustmentRule[] rules;
StreamWriter stream = new StreamWriter(file, false);
ReadOnlyCollection<TimeZoneInfo> timeZones = TimeZoneInfo.GetSystemTimeZones();
stream.WriteLine();
stream.WriteLine("struct _SYSTEM_TIME_ENTRY");
stream.WriteLine("{");
stream.WriteLine("\tuint16 wYear;");
stream.WriteLine("\tuint16 wMonth;");
stream.WriteLine("\tuint16 wDayOfWeek;");
stream.WriteLine("\tuint16 wDay;");
stream.WriteLine("\tuint16 wHour;");
stream.WriteLine("\tuint16 wMinute;");
stream.WriteLine("\tuint16 wSecond;");
stream.WriteLine("\tuint16 wMilliseconds;");
stream.WriteLine("};");
stream.WriteLine("typedef struct _SYSTEM_TIME_ENTRY SYSTEM_TIME_ENTRY;");
stream.WriteLine();
stream.WriteLine("struct _TIME_ZONE_RULE_ENTRY");
stream.WriteLine("{");
stream.WriteLine("\tuint64 TicksStart;");
stream.WriteLine("\tuint64 TicksEnd;");
stream.WriteLine("\tsint32 DaylightDelta;");
stream.WriteLine("\tSYSTEM_TIME_ENTRY StandardDate;");
stream.WriteLine("\tSYSTEM_TIME_ENTRY DaylightDate;");
stream.WriteLine("};");
stream.WriteLine("typedef struct _TIME_ZONE_RULE_ENTRY TIME_ZONE_RULE_ENTRY;");
stream.WriteLine();
stream.WriteLine("struct _TIME_ZONE_ENTRY");
stream.WriteLine("{");
stream.WriteLine("\tconst char* Id;");
stream.WriteLine("\tuint32 Bias;");
stream.WriteLine("\tboolean SupportsDST;");
stream.WriteLine("\tconst char* DisplayName;");
stream.WriteLine("\tconst char* StandardName;");
stream.WriteLine("\tconst char* DaylightName;");
stream.WriteLine("\tTIME_ZONE_RULE_ENTRY* RuleTable;");
stream.WriteLine("\tuint32 RuleTableCount;");
stream.WriteLine("};");
stream.WriteLine("typedef struct _TIME_ZONE_ENTRY TIME_ZONE_ENTRY;");
stream.WriteLine();
index = 0;
foreach (TimeZoneInfo timeZone in timeZones)
{
rules = timeZone.GetAdjustmentRules();
if ((!timeZone.SupportsDaylightSavingTime) || (rules.Length < 1))
{
index++;
continue;
}
stream.WriteLine("static const TIME_ZONE_RULE_ENTRY TimeZoneRuleTable_{0}[] =", index);
stream.WriteLine("{");
i = 0;
foreach (TimeZoneInfo.AdjustmentRule rule in rules)
{
DateTime time;
TIME_ZONE_RULE_ENTRY tzr;
TimeZoneInfo.TransitionTime transition;
tzr.TicksStart = rule.DateEnd.ToUniversalTime().Ticks;
tzr.TicksEnd = rule.DateStart.ToUniversalTime().Ticks;
tzr.DaylightDelta = (Int32)rule.DaylightDelta.TotalMinutes;
transition = rule.DaylightTransitionEnd;
time = transition.TimeOfDay;
tzr.StandardDate.wYear = (UInt16)0;
tzr.StandardDate.wMonth = (UInt16)transition.Month;
tzr.StandardDate.wDayOfWeek = (UInt16)transition.DayOfWeek;
tzr.StandardDate.wDay = (UInt16)transition.Day;
tzr.StandardDate.wHour = (UInt16)time.Hour;
tzr.StandardDate.wMinute = (UInt16)time.Minute;
tzr.StandardDate.wSecond = (UInt16)time.Second;
tzr.StandardDate.wMilliseconds = (UInt16)time.Millisecond;
transition = rule.DaylightTransitionStart;
time = transition.TimeOfDay;
tzr.DaylightDate.wYear = (UInt16)0;
tzr.DaylightDate.wMonth = (UInt16)transition.Month;
tzr.DaylightDate.wDayOfWeek = (UInt16)transition.DayOfWeek;
tzr.DaylightDate.wDay = (UInt16)transition.Day;
tzr.DaylightDate.wHour = (UInt16)time.Hour;
tzr.DaylightDate.wMinute = (UInt16)time.Minute;
tzr.DaylightDate.wSecond = (UInt16)time.Second;
tzr.DaylightDate.wMilliseconds = (UInt16)time.Millisecond;
stream.Write("\t{");
stream.Write(" {0}ULL, {1}ULL, {2},", tzr.TicksStart, tzr.TicksEnd, tzr.DaylightDelta);
stream.Write(" { ");
stream.Write("{0}, {1}, {2}, {3}, {4}, {5}",
tzr.StandardDate.wYear, tzr.StandardDate.wMonth, tzr.StandardDate.wDayOfWeek,
tzr.StandardDate.wDay, tzr.StandardDate.wHour, tzr.StandardDate.wMinute,
tzr.StandardDate.wSecond, tzr.StandardDate.wMilliseconds);
stream.Write(" }, ");
stream.Write("{ ");
stream.Write("{0}, {1}, {2}, {3}, {4}, {5}",
tzr.DaylightDate.wYear, tzr.DaylightDate.wMonth, tzr.DaylightDate.wDayOfWeek,
tzr.DaylightDate.wDay, tzr.DaylightDate.wHour, tzr.DaylightDate.wMinute,
tzr.DaylightDate.wSecond, tzr.DaylightDate.wMilliseconds);
stream.Write(" },");
if (++i < rules.Length)
stream.WriteLine(" },");
else
stream.WriteLine(" }");
}
stream.WriteLine("};");
stream.WriteLine();
index++;
}
index = 0;
stream.WriteLine("static const TIME_ZONE_ENTRY TimeZoneTable[] =");
stream.WriteLine("{");
foreach (TimeZoneInfo timeZone in timeZones)
{
Int32 sbias;
TIME_ZONE_ENTRY tz;
TimeSpan offset = timeZone.BaseUtcOffset;
rules = timeZone.GetAdjustmentRules();
tz.Id = timeZone.Id;
if (offset.Hours >= 0)
{
sbias = (offset.Hours * 60) + offset.Minutes;
tz.Bias = (UInt32) sbias;
}
else
{
sbias = (offset.Hours * 60) + offset.Minutes;
tz.Bias = (UInt32) (1440 + sbias);
}
tz.SupportsDST = timeZone.SupportsDaylightSavingTime;
tz.DisplayName = timeZone.DisplayName;
tz.StandardName = timeZone.StandardName;
tz.DaylightName = timeZone.DaylightName;
if ((!tz.SupportsDST) || (rules.Length < 1))
{
tz.RuleTableCount = 0;
tz.RuleTable = "NULL";
}
else
{
tz.RuleTableCount = (UInt32)rules.Length;
tz.RuleTable = "&TimeZoneRuleTable_" + index;
tz.RuleTable = "(TIME_ZONE_RULE_ENTRY*) &TimeZoneRuleTable_" + index;
}
stream.WriteLine("\t{");
stream.WriteLine("\t\t\"{0}\", {1}, {2}, \"{3}\",",
tz.Id, tz.Bias, tz.SupportsDST ? "true" : "false", tz.DisplayName);
stream.WriteLine("\t\t\"{0}\", \"{1}\",", tz.StandardName, tz.DaylightName);
stream.WriteLine("\t\t{0}, {1}", tz.RuleTable, tz.RuleTableCount);
index++;
if ((int)index < timeZones.Count)
stream.WriteLine("\t},");
else
stream.WriteLine("\t}");
}
stream.WriteLine("};");
stream.WriteLine();
stream.Close();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.Extensions.Logging;
using NPoco;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Cache;
using Umbraco.Cms.Core.IO;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Models.Entities;
using Umbraco.Cms.Core.Persistence.Querying;
using Umbraco.Cms.Core.Persistence.Repositories;
using Umbraco.Cms.Core.Scoping;
using Umbraco.Cms.Core.Strings;
using Umbraco.Cms.Infrastructure.Persistence.Dtos;
using Umbraco.Cms.Infrastructure.Persistence.Factories;
using Umbraco.Cms.Infrastructure.Persistence.Querying;
using Umbraco.Extensions;
namespace Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement
{
/// <summary>
/// Represents the Template Repository
/// </summary>
internal class TemplateRepository : EntityRepositoryBase<int, ITemplate>, ITemplateRepository
{
private readonly IIOHelper _ioHelper;
private readonly IShortStringHelper _shortStringHelper;
private readonly IFileSystem _viewsFileSystem;
private readonly IViewHelper _viewHelper;
public TemplateRepository(IScopeAccessor scopeAccessor, AppCaches cache, ILogger<TemplateRepository> logger, FileSystems fileSystems, IIOHelper ioHelper, IShortStringHelper shortStringHelper, IViewHelper viewHelper)
: base(scopeAccessor, cache, logger)
{
_ioHelper = ioHelper;
_shortStringHelper = shortStringHelper;
_viewsFileSystem = fileSystems.MvcViewsFileSystem;
_viewHelper = viewHelper;
}
protected override IRepositoryCachePolicy<ITemplate, int> CreateCachePolicy() =>
new FullDataSetRepositoryCachePolicy<ITemplate, int>(GlobalIsolatedCache, ScopeAccessor, GetEntityId, /*expires:*/ false);
#region Overrides of RepositoryBase<int,ITemplate>
protected override ITemplate PerformGet(int id) =>
//use the underlying GetAll which will force cache all templates
base.GetMany().FirstOrDefault(x => x.Id == id);
protected override IEnumerable<ITemplate> PerformGetAll(params int[] ids)
{
Sql<ISqlContext> sql = GetBaseQuery(false);
if (ids.Any())
{
sql.Where("umbracoNode.id in (@ids)", new { ids });
}
else
{
sql.Where<NodeDto>(x => x.NodeObjectType == NodeObjectTypeId);
}
List<TemplateDto> dtos = Database.Fetch<TemplateDto>(sql);
if (dtos.Count == 0)
{
return Enumerable.Empty<ITemplate>();
}
//look up the simple template definitions that have a master template assigned, this is used
// later to populate the template item's properties
IUmbracoEntity[] childIds = (ids.Any()
? GetAxisDefinitions(dtos.ToArray())
: dtos.Select(x => new EntitySlim
{
Id = x.NodeId,
ParentId = x.NodeDto.ParentId,
Name = x.Alias
})).ToArray();
return dtos.Select(d => MapFromDto(d, childIds));
}
protected override IEnumerable<ITemplate> PerformGetByQuery(IQuery<ITemplate> query)
{
Sql<ISqlContext> sqlClause = GetBaseQuery(false);
var translator = new SqlTranslator<ITemplate>(sqlClause, query);
Sql<ISqlContext> sql = translator.Translate();
List<TemplateDto> dtos = Database.Fetch<TemplateDto>(sql);
if (dtos.Count == 0)
{
return Enumerable.Empty<ITemplate>();
}
//look up the simple template definitions that have a master template assigned, this is used
// later to populate the template item's properties
IUmbracoEntity[] childIds = GetAxisDefinitions(dtos.ToArray()).ToArray();
return dtos.Select(d => MapFromDto(d, childIds));
}
#endregion
#region Overrides of EntityRepositoryBase<int,ITemplate>
protected override Sql<ISqlContext> GetBaseQuery(bool isCount)
{
Sql<ISqlContext> sql = SqlContext.Sql();
sql = isCount
? sql.SelectCount()
: sql.Select<TemplateDto>(r => r.Select(x => x.NodeDto));
sql
.From<TemplateDto>()
.InnerJoin<NodeDto>()
.On<TemplateDto, NodeDto>(left => left.NodeId, right => right.NodeId)
.Where<NodeDto>(x => x.NodeObjectType == NodeObjectTypeId);
return sql;
}
protected override string GetBaseWhereClause() => $"{Constants.DatabaseSchema.Tables.Node}.id = @id";
protected override IEnumerable<string> GetDeleteClauses()
{
var list = new List<string>
{
"DELETE FROM " + Cms.Core.Constants.DatabaseSchema.Tables.User2NodeNotify + " WHERE nodeId = @id",
"DELETE FROM " + Cms.Core.Constants.DatabaseSchema.Tables.UserGroup2Node + " WHERE nodeId = @id",
"DELETE FROM " + Cms.Core.Constants.DatabaseSchema.Tables.UserGroup2NodePermission + " WHERE nodeId = @id",
"UPDATE " + Cms.Core.Constants.DatabaseSchema.Tables.DocumentVersion + " SET templateId = NULL WHERE templateId = @id",
"DELETE FROM " + Cms.Core.Constants.DatabaseSchema.Tables.DocumentType + " WHERE templateNodeId = @id",
"DELETE FROM " + Cms.Core.Constants.DatabaseSchema.Tables.Template + " WHERE nodeId = @id",
"DELETE FROM " + Cms.Core.Constants.DatabaseSchema.Tables.Node + " WHERE id = @id"
};
return list;
}
protected Guid NodeObjectTypeId => Cms.Core.Constants.ObjectTypes.Template;
protected override void PersistNewItem(ITemplate entity)
{
EnsureValidAlias(entity);
//Save to db
var template = (Template)entity;
template.AddingEntity();
TemplateDto dto = TemplateFactory.BuildDto(template, NodeObjectTypeId, template.Id);
//Create the (base) node data - umbracoNode
NodeDto nodeDto = dto.NodeDto;
nodeDto.Path = "-1," + dto.NodeDto.NodeId;
int o = Database.IsNew<NodeDto>(nodeDto) ? Convert.ToInt32(Database.Insert(nodeDto)) : Database.Update(nodeDto);
//Update with new correct path
ITemplate parent = Get(template.MasterTemplateId.Value);
if (parent != null)
{
nodeDto.Path = string.Concat(parent.Path, ",", nodeDto.NodeId);
}
else
{
nodeDto.Path = "-1," + dto.NodeDto.NodeId;
}
Database.Update(nodeDto);
//Insert template dto
dto.NodeId = nodeDto.NodeId;
Database.Insert(dto);
//Update entity with correct values
template.Id = nodeDto.NodeId; //Set Id on entity to ensure an Id is set
template.Path = nodeDto.Path;
//now do the file work
SaveFile(template);
template.ResetDirtyProperties();
// ensure that from now on, content is lazy-loaded
if (template.GetFileContent == null)
{
template.GetFileContent = file => GetFileContent((Template) file, false);
}
}
protected override void PersistUpdatedItem(ITemplate entity)
{
EnsureValidAlias(entity);
//store the changed alias if there is one for use with updating files later
string originalAlias = entity.Alias;
if (entity.IsPropertyDirty("Alias"))
{
//we need to check what it currently is before saving and remove that file
ITemplate current = Get(entity.Id);
originalAlias = current.Alias;
}
var template = (Template)entity;
if (entity.IsPropertyDirty("MasterTemplateId"))
{
ITemplate parent = Get(template.MasterTemplateId.Value);
if (parent != null)
{
entity.Path = string.Concat(parent.Path, ",", entity.Id);
}
else
{
//this means that the master template has been removed, so we need to reset the template's
//path to be at the root
entity.Path = string.Concat("-1,", entity.Id);
}
}
//Get TemplateDto from db to get the Primary key of the entity
TemplateDto templateDto = Database.SingleOrDefault<TemplateDto>("WHERE nodeId = @Id", new { entity.Id });
//Save updated entity to db
template.UpdateDate = DateTime.Now;
TemplateDto dto = TemplateFactory.BuildDto(template, NodeObjectTypeId, templateDto.PrimaryKey);
Database.Update(dto.NodeDto);
Database.Update(dto);
//re-update if this is a master template, since it could have changed!
IEnumerable<IUmbracoEntity> axisDefs = GetAxisDefinitions(dto);
template.IsMasterTemplate = axisDefs.Any(x => x.ParentId == dto.NodeId);
//now do the file work
SaveFile((Template) entity, originalAlias);
entity.ResetDirtyProperties();
// ensure that from now on, content is lazy-loaded
if (template.GetFileContent == null)
{
template.GetFileContent = file => GetFileContent((Template) file, false);
}
}
private void SaveFile(Template template, string originalAlias = null)
{
string content;
if (template is TemplateOnDisk templateOnDisk && templateOnDisk.IsOnDisk)
{
// if "template on disk" load content from disk
content = _viewHelper.GetFileContents(template);
}
else
{
// else, create or write template.Content to disk
content = originalAlias == null
? _viewHelper.CreateView(template, true)
: _viewHelper.UpdateViewFile(template, originalAlias);
}
// once content has been set, "template on disk" are not "on disk" anymore
template.Content = content;
SetVirtualPath(template);
}
protected override void PersistDeletedItem(ITemplate entity)
{
string[] deletes = GetDeleteClauses().ToArray();
var descendants = GetDescendants(entity.Id).ToList();
//change the order so it goes bottom up! (deepest level first)
descendants.Reverse();
//delete the hierarchy
foreach (ITemplate descendant in descendants)
{
foreach (string delete in deletes)
{
Database.Execute(delete, new { id = GetEntityId(descendant) });
}
}
//now we can delete this one
foreach (string delete in deletes)
{
Database.Execute(delete, new { id = GetEntityId(entity) });
}
string viewName = string.Concat(entity.Alias, ".cshtml");
_viewsFileSystem.DeleteFile(viewName);
entity.DeleteDate = DateTime.Now;
}
#endregion
private IEnumerable<IUmbracoEntity> GetAxisDefinitions(params TemplateDto[] templates)
{
//look up the simple template definitions that have a master template assigned, this is used
// later to populate the template item's properties
Sql<ISqlContext> childIdsSql = SqlContext.Sql()
.Select("nodeId,alias,parentID")
.From<TemplateDto>()
.InnerJoin<NodeDto>()
.On<TemplateDto, NodeDto>(dto => dto.NodeId, dto => dto.NodeId)
//lookup axis's
.Where("umbracoNode." + SqlContext.SqlSyntax.GetQuotedColumnName("id") + " IN (@parentIds) OR umbracoNode.parentID IN (@childIds)",
new {parentIds = templates.Select(x => x.NodeDto.ParentId), childIds = templates.Select(x => x.NodeId)});
var childIds = Database.Fetch<AxisDefintionDto>(childIdsSql)
.Select(x => new EntitySlim
{
Id = x.NodeId,
ParentId = x.ParentId,
Name = x.Alias
});
return childIds;
}
/// <summary>
/// Maps from a dto to an ITemplate
/// </summary>
/// <param name="dto"></param>
/// <param name="axisDefinitions">
/// This is a collection of template definitions ... either all templates, or the collection of child templates and it's parent template
/// </param>
/// <returns></returns>
private ITemplate MapFromDto(TemplateDto dto, IUmbracoEntity[] axisDefinitions)
{
Template template = TemplateFactory.BuildEntity(_shortStringHelper, dto, axisDefinitions, file => GetFileContent((Template) file, false));
if (dto.NodeDto.ParentId > 0)
{
IUmbracoEntity masterTemplate = axisDefinitions.FirstOrDefault(x => x.Id == dto.NodeDto.ParentId);
if (masterTemplate != null)
{
template.MasterTemplateAlias = masterTemplate.Name;
template.MasterTemplateId = new Lazy<int>(() => dto.NodeDto.ParentId);
}
}
// get the infos (update date and virtual path) that will change only if
// path changes - but do not get content, will get loaded only when required
GetFileContent(template, true);
// reset dirty initial properties (U4-1946)
template.ResetDirtyProperties(false);
return template;
}
private void SetVirtualPath(ITemplate template)
{
string path = template.OriginalPath;
if (string.IsNullOrWhiteSpace(path))
{
// we need to discover the path
path = string.Concat(template.Alias, ".cshtml");
if (_viewsFileSystem.FileExists(path))
{
template.VirtualPath = _viewsFileSystem.GetUrl(path);
return;
}
path = string.Concat(template.Alias, ".vbhtml");
if (_viewsFileSystem.FileExists(path))
{
template.VirtualPath = _viewsFileSystem.GetUrl(path);
return;
}
}
else
{
// we know the path already
template.VirtualPath = _viewsFileSystem.GetUrl(path);
}
template.VirtualPath = string.Empty; // file not found...
}
private string GetFileContent(ITemplate template, bool init)
{
string path = template.OriginalPath;
if (string.IsNullOrWhiteSpace(path))
{
// we need to discover the path
path = string.Concat(template.Alias, ".cshtml");
if (_viewsFileSystem.FileExists(path))
{
return GetFileContent(template, _viewsFileSystem, path, init);
}
path = string.Concat(template.Alias, ".vbhtml");
if (_viewsFileSystem.FileExists(path))
{
return GetFileContent(template, _viewsFileSystem, path, init);
}
}
else
{
// we know the path already
return GetFileContent(template, _viewsFileSystem, path, init);
}
template.VirtualPath = string.Empty; // file not found...
return string.Empty;
}
private string GetFileContent(ITemplate template, IFileSystem fs, string filename, bool init)
{
// do not update .UpdateDate as that would make it dirty (side-effect)
// unless initializing, because we have to do it once
if (init)
{
template.UpdateDate = fs.GetLastModified(filename).UtcDateTime;
}
// TODO: see if this could enable us to update UpdateDate without messing with change tracking
// and then we'd want to do it for scripts, stylesheets and partial views too (ie files)
// var xtemplate = template as Template;
// xtemplate.DisableChangeTracking();
// template.UpdateDate = fs.GetLastModified(filename).UtcDateTime;
// xtemplate.EnableChangeTracking();
template.VirtualPath = fs.GetUrl(filename);
return init ? null : GetFileContent(fs, filename);
}
private string GetFileContent(IFileSystem fs, string filename)
{
using (Stream stream = fs.OpenFile(filename))
using (var reader = new StreamReader(stream, Encoding.UTF8, true))
{
return reader.ReadToEnd();
}
}
public Stream GetFileContentStream(string filepath)
{
IFileSystem fileSystem = GetFileSystem(filepath);
if (fileSystem.FileExists(filepath) == false)
{
return null;
}
try
{
return fileSystem.OpenFile(filepath);
}
catch
{
return null; // deal with race conds
}
}
public void SetFileContent(string filepath, Stream content) => GetFileSystem(filepath).AddFile(filepath, content, true);
public long GetFileSize(string filename)
{
IFileSystem fileSystem = GetFileSystem(filename);
if (fileSystem.FileExists(filename) == false)
{
return -1;
}
try
{
return fileSystem.GetSize(filename);
}
catch
{
return -1; // deal with race conds
}
}
private IFileSystem GetFileSystem(string filepath)
{
string ext = Path.GetExtension(filepath);
IFileSystem fs;
switch (ext)
{
case ".cshtml":
case ".vbhtml":
fs = _viewsFileSystem;
break;
default:
throw new Exception("Unsupported extension " + ext + ".");
}
return fs;
}
#region Implementation of ITemplateRepository
public ITemplate Get(string alias) => GetAll(alias).FirstOrDefault();
public IEnumerable<ITemplate> GetAll(params string[] aliases)
{
//We must call the base (normal) GetAll method
// which is cached. This is a specialized method and unfortunately with the params[] it
// overlaps with the normal GetAll method.
if (aliases.Any() == false)
{
return base.GetMany();
}
//return from base.GetAll, this is all cached
return base.GetMany().Where(x => aliases.InvariantContains(x.Alias));
}
public IEnumerable<ITemplate> GetChildren(int masterTemplateId)
{
//return from base.GetAll, this is all cached
ITemplate[] all = base.GetMany().ToArray();
if (masterTemplateId <= 0)
{
return all.Where(x => x.MasterTemplateAlias.IsNullOrWhiteSpace());
}
ITemplate parent = all.FirstOrDefault(x => x.Id == masterTemplateId);
if (parent == null)
{
return Enumerable.Empty<ITemplate>();
}
IEnumerable<ITemplate> children = all.Where(x => x.MasterTemplateAlias.InvariantEquals(parent.Alias));
return children;
}
public IEnumerable<ITemplate> GetDescendants(int masterTemplateId)
{
//return from base.GetAll, this is all cached
ITemplate[] all = base.GetMany().ToArray();
var descendants = new List<ITemplate>();
if (masterTemplateId > 0)
{
ITemplate parent = all.FirstOrDefault(x => x.Id == masterTemplateId);
if (parent == null)
{
return Enumerable.Empty<ITemplate>();
}
//recursively add all children with a level
AddChildren(all, descendants, parent.Alias);
}
else
{
descendants.AddRange(all.Where(x => x.MasterTemplateAlias.IsNullOrWhiteSpace()));
foreach (ITemplate parent in descendants)
{
//recursively add all children with a level
AddChildren(all, descendants, parent.Alias);
}
}
//return the list - it will be naturally ordered by level
return descendants;
}
private void AddChildren(ITemplate[] all, List<ITemplate> descendants, string masterAlias)
{
ITemplate[] c = all.Where(x => x.MasterTemplateAlias.InvariantEquals(masterAlias)).ToArray();
descendants.AddRange(c);
if (c.Any() == false)
{
return;
}
//recurse through all children
foreach (ITemplate child in c)
{
AddChildren(all, descendants, child.Alias);
}
}
#endregion
/// <summary>
/// Ensures that there are not duplicate aliases and if so, changes it to be a numbered version and also verifies the length
/// </summary>
/// <param name="template"></param>
private void EnsureValidAlias(ITemplate template)
{
//ensure unique alias
template.Alias = template.Alias.ToCleanString(_shortStringHelper, CleanStringType.UnderscoreAlias);
if (template.Alias.Length > 100)
{
template.Alias = template.Alias.Substring(0, 95);
}
if (AliasAlreadExists(template))
{
template.Alias = EnsureUniqueAlias(template, 1);
}
}
private bool AliasAlreadExists(ITemplate template)
{
Sql<ISqlContext> sql = GetBaseQuery(true).Where<TemplateDto>(x => x.Alias.InvariantEquals(template.Alias) && x.NodeId != template.Id);
int count = Database.ExecuteScalar<int>(sql);
return count > 0;
}
private string EnsureUniqueAlias(ITemplate template, int attempts)
{
// TODO: This is ported from the old data layer... pretty crap way of doing this but it works for now.
if (AliasAlreadExists(template))
{
return template.Alias + attempts;
}
attempts++;
return EnsureUniqueAlias(template, attempts);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Tests.Compute
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Compute;
using Apache.Ignite.Core.Resource;
using NUnit.Framework;
/// <summary>
/// Tests for exception handling on various task execution stages.
/// </summary>
public class IgniteExceptionTaskSelfTest : AbstractTaskTest
{
/** Error mode. */
public static ErrorMode Mode;
/** Observed job errors. */
public static readonly ICollection<Exception> JobErrs = new List<Exception>();
/// <summary>
/// Constructor.
/// </summary>
public IgniteExceptionTaskSelfTest() : base(false) { }
/// <summary>
/// Constructor.
/// </summary>
/// <param name="fork">Fork flag.</param>
protected IgniteExceptionTaskSelfTest(bool fork) : base(fork) { }
/// <summary>
/// Test error occurred during map step.
/// </summary>
[Test]
public void TestMapError()
{
Mode = ErrorMode.MapErr;
GoodException e = ExecuteWithError() as GoodException;
Assert.IsNotNull(e);
Assert.AreEqual(ErrorMode.MapErr, e.Mode);
}
/// <summary>
/// Test not-marshalable error occurred during map step.
/// </summary>
[Test]
public void TestMapNotMarshalableError()
{
Mode = ErrorMode.MapErrNotMarshalable;
BadException e = ExecuteWithError() as BadException;
Assert.IsNotNull(e);
Assert.AreEqual(ErrorMode.MapErrNotMarshalable, e.Mode);
}
/// <summary>
/// Test task behavior when job produced by mapper is not marshalable.
/// </summary>
[Test]
public void TestMapNotMarshalableJob()
{
Mode = ErrorMode.MapJobNotMarshalable;
Assert.IsInstanceOf<BinaryObjectException>(ExecuteWithError());
}
/// <summary>
/// Test local job error.
/// </summary>
[Test]
public void TestLocalJobError()
{
Mode = ErrorMode.LocJobErr;
int res = Execute();
Assert.AreEqual(1, res);
Assert.AreEqual(4, JobErrs.Count);
Assert.IsNotNull(JobErrs.First() as GoodException);
Assert.AreEqual(ErrorMode.LocJobErr, ((GoodException) JobErrs.First()).Mode);
}
/// <summary>
/// Test local not-marshalable job error.
/// </summary>
[Test]
public void TestLocalJobErrorNotMarshalable()
{
Mode = ErrorMode.LocJobErrNotMarshalable;
int res = Execute();
Assert.AreEqual(1, res);
Assert.AreEqual(4, JobErrs.Count);
Assert.IsNotNull(JobErrs.First() as BadException); // Local job exception is not marshalled.
}
/// <summary>
/// Test local not-marshalable job result.
/// </summary>
[Test]
public void TestLocalJobResultNotMarshalable()
{
Mode = ErrorMode.LocJobResNotMarshalable;
int res = Execute();
Assert.AreEqual(2, res); // Local job result is not marshalled.
Assert.AreEqual(0, JobErrs.Count);
}
/// <summary>
/// Test remote job error.
/// </summary>
[Test]
public void TestRemoteJobError()
{
Mode = ErrorMode.RmtJobErr;
int res = Execute();
Assert.AreEqual(1, res);
Assert.AreEqual(4, JobErrs.Count);
Assert.IsNotNull(JobErrs.ElementAt(0) as GoodException);
Assert.AreEqual(ErrorMode.RmtJobErr, ((GoodException) JobErrs.ElementAt(0)).Mode);
}
/// <summary>
/// Test remote not-marshalable job error.
/// </summary>
[Test]
public void TestRemoteJobErrorNotMarshalable()
{
Mode = ErrorMode.RmtJobErrNotMarshalable;
Assert.Throws<SerializationException>(() => Execute());
}
/// <summary>
/// Test local not-marshalable job result.
/// </summary>
[Test]
public void TestRemoteJobResultNotMarshalable()
{
Mode = ErrorMode.RmtJobResNotMarshalable;
int res = Execute();
Assert.AreEqual(1, res);
Assert.AreEqual(4, JobErrs.Count);
Assert.IsNotNull(JobErrs.ElementAt(0) as IgniteException);
}
/// <summary>
/// Test local result error.
/// </summary>
[Test]
public void TestLocalResultError()
{
Mode = ErrorMode.LocResErr;
GoodException e = ExecuteWithError() as GoodException;
Assert.IsNotNull(e);
Assert.AreEqual(ErrorMode.LocResErr, e.Mode);
}
/// <summary>
/// Test local result not-marshalable error.
/// </summary>
[Test]
public void TestLocalResultErrorNotMarshalable()
{
Mode = ErrorMode.LocResErrNotMarshalable;
BadException e = ExecuteWithError() as BadException;
Assert.IsNotNull(e);
Assert.AreEqual(ErrorMode.LocResErrNotMarshalable, e.Mode);
}
/// <summary>
/// Test remote result error.
/// </summary>
[Test]
public void TestRemoteResultError()
{
Mode = ErrorMode.RmtResErr;
GoodException e = ExecuteWithError() as GoodException;
Assert.IsNotNull(e);
Assert.AreEqual(ErrorMode.RmtResErr, e.Mode);
}
/// <summary>
/// Test remote result not-marshalable error.
/// </summary>
[Test]
public void TestRemoteResultErrorNotMarshalable()
{
Mode = ErrorMode.RmtResErrNotMarshalable;
BadException e = ExecuteWithError() as BadException;
Assert.IsNotNull(e);
Assert.AreEqual(ErrorMode.RmtResErrNotMarshalable, e.Mode);
}
/// <summary>
/// Test reduce with error.
/// </summary>
[Test]
public void TestReduceError()
{
Mode = ErrorMode.ReduceErr;
GoodException e = ExecuteWithError() as GoodException;
Assert.IsNotNull(e);
Assert.AreEqual(ErrorMode.ReduceErr, e.Mode);
}
/// <summary>
/// Test reduce with not-marshalable error.
/// </summary>
[Test]
public void TestReduceErrorNotMarshalable()
{
Mode = ErrorMode.ReduceErrNotMarshalable;
BadException e = ExecuteWithError() as BadException;
Assert.IsNotNull(e);
Assert.AreEqual(ErrorMode.ReduceErrNotMarshalable, e.Mode);
}
/// <summary>
/// Test reduce with not-marshalable result.
/// </summary>
[Test]
public void TestReduceResultNotMarshalable()
{
Mode = ErrorMode.ReduceResNotMarshalable;
int res = Execute();
Assert.AreEqual(2, res);
}
/// <summary>
/// Execute task successfully.
/// </summary>
/// <returns>Task result.</returns>
private int Execute()
{
JobErrs.Clear();
Func<object, int> getRes = r => r is GoodTaskResult ? ((GoodTaskResult) r).Res : ((BadTaskResult) r).Res;
var res1 = getRes(Grid1.GetCompute().Execute(new Task()));
var res2 = getRes(Grid1.GetCompute().Execute<object, object>(typeof(Task)));
var resAsync1 = getRes(Grid1.GetCompute().ExecuteAsync(new Task()).Result);
var resAsync2 = getRes(Grid1.GetCompute().ExecuteAsync<object, object>(typeof(Task)).Result);
Assert.AreEqual(res1, res2);
Assert.AreEqual(res2, resAsync1);
Assert.AreEqual(resAsync1, resAsync2);
return res1;
}
/// <summary>
/// Execute task with error.
/// </summary>
/// <returns>Task</returns>
private Exception ExecuteWithError()
{
JobErrs.Clear();
return Assert.Catch(() => Grid1.GetCompute().Execute(new Task()));
}
/// <summary>
/// Error modes.
/// </summary>
public enum ErrorMode
{
/** Error during map step. */
MapErr,
/** Error during map step which is not marshalable. */
MapErrNotMarshalable,
/** Job created by mapper is not marshalable. */
MapJobNotMarshalable,
/** Error occurred in local job. */
LocJobErr,
/** Error occurred in local job and is not marshalable. */
LocJobErrNotMarshalable,
/** Local job result is not marshalable. */
LocJobResNotMarshalable,
/** Error occurred in remote job. */
RmtJobErr,
/** Error occurred in remote job and is not marshalable. */
RmtJobErrNotMarshalable,
/** Remote job result is not marshalable. */
RmtJobResNotMarshalable,
/** Error occurred during local result processing. */
LocResErr,
/** Error occurred during local result processing and is not marshalable. */
LocResErrNotMarshalable,
/** Error occurred during remote result processing. */
RmtResErr,
/** Error occurred during remote result processing and is not marshalable. */
RmtResErrNotMarshalable,
/** Error during reduce step. */
ReduceErr,
/** Error during reduce step and is not marshalable. */
ReduceErrNotMarshalable,
/** Reduce result is not marshalable. */
ReduceResNotMarshalable
}
/// <summary>
/// Task.
/// </summary>
private class Task : IComputeTask<object, object>
{
/** Grid. */
[InstanceResource]
private readonly IIgnite _grid = null;
/** Result. */
private int _res;
/** <inheritDoc /> */
public IDictionary<IComputeJob<object>, IClusterNode> Map(IList<IClusterNode> subgrid, object arg)
{
switch (Mode)
{
case ErrorMode.MapErr:
throw new GoodException(ErrorMode.MapErr);
case ErrorMode.MapErrNotMarshalable:
throw new BadException(ErrorMode.MapErrNotMarshalable);
case ErrorMode.MapJobNotMarshalable:
{
var badJobs = new Dictionary<IComputeJob<object>, IClusterNode>();
foreach (IClusterNode node in subgrid)
badJobs.Add(new BadJob(), node);
return badJobs;
}
}
// Map completes sucessfully and we spread jobs to all nodes.
var jobs = new Dictionary<IComputeJob<object>, IClusterNode>();
foreach (IClusterNode node in subgrid)
jobs.Add(new GoodJob(!_grid.GetCluster().GetLocalNode().Id.Equals(node.Id)), node);
return jobs;
}
/** <inheritDoc /> */
public ComputeJobResultPolicy OnResult(IComputeJobResult<object> res, IList<IComputeJobResult<object>> rcvd)
{
if (res.Exception != null)
JobErrs.Add(res.Exception);
else
{
object res0 = res.Data;
bool rmt = res0 is GoodJobResult ? ((GoodJobResult)res0).Rmt : ((BadJobResult)res0).Rmt;
if (rmt)
{
switch (Mode)
{
case ErrorMode.RmtResErr:
throw new GoodException(ErrorMode.RmtResErr);
case ErrorMode.RmtResErrNotMarshalable:
throw new BadException(ErrorMode.RmtResErrNotMarshalable);
}
}
else
{
switch (Mode)
{
case ErrorMode.LocResErr:
throw new GoodException(ErrorMode.LocResErr);
case ErrorMode.LocResErrNotMarshalable:
throw new BadException(ErrorMode.LocResErrNotMarshalable);
}
}
_res += 1;
}
return ComputeJobResultPolicy.Wait;
}
/** <inheritDoc /> */
public object Reduce(IList<IComputeJobResult<object>> results)
{
switch (Mode)
{
case ErrorMode.ReduceErr:
throw new GoodException(ErrorMode.ReduceErr);
case ErrorMode.ReduceErrNotMarshalable:
throw new BadException(ErrorMode.ReduceErrNotMarshalable);
case ErrorMode.ReduceResNotMarshalable:
return new BadTaskResult(_res);
}
return new GoodTaskResult(_res);
}
}
/// <summary>
///
/// </summary>
[Serializable]
public class GoodJob : IComputeJob<object>
{
/** Whether the job is remote. */
private bool _rmt;
/// <summary>
///
/// </summary>
/// <param name="rmt"></param>
public GoodJob(bool rmt)
{
_rmt = rmt;
}
/// <summary>
///
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
public GoodJob(SerializationInfo info, StreamingContext context)
{
_rmt = info.GetBoolean("rmt");
}
/** <inheritDoc /> */
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("rmt", _rmt);
}
/** <inheritDoc /> */
public object Execute()
{
if (_rmt)
{
switch (Mode)
{
case ErrorMode.RmtJobErr:
throw new GoodException(ErrorMode.RmtJobErr);
case ErrorMode.RmtJobErrNotMarshalable:
throw new BadException(ErrorMode.RmtJobErr);
case ErrorMode.RmtJobResNotMarshalable:
return new BadJobResult(_rmt);
}
}
else
{
switch (Mode)
{
case ErrorMode.LocJobErr:
throw new GoodException(ErrorMode.LocJobErr);
case ErrorMode.LocJobErrNotMarshalable:
throw new BadException(ErrorMode.LocJobErr);
case ErrorMode.LocJobResNotMarshalable:
return new BadJobResult(_rmt);
}
}
return new GoodJobResult(_rmt);
}
/** <inheritDoc /> */
public void Cancel()
{
// No-op.
}
}
/// <summary>
///
/// </summary>
public class BadJob : IComputeJob<object>, IBinarizable
{
[InstanceResource]
/** <inheritDoc /> */
public object Execute()
{
throw new NotImplementedException();
}
/** <inheritDoc /> */
public void Cancel()
{
// No-op.
}
/** <inheritDoc /> */
public void WriteBinary(IBinaryWriter writer)
{
throw new BinaryObjectException("Expected");
}
/** <inheritDoc /> */
public void ReadBinary(IBinaryReader reader)
{
throw new BinaryObjectException("Expected");
}
}
/// <summary>
///
/// </summary>
[Serializable]
public class GoodJobResult
{
/** */
public bool Rmt;
/// <summary>
///
/// </summary>
/// <param name="rmt"></param>
public GoodJobResult(bool rmt)
{
Rmt = rmt;
}
/// <summary>
///
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
public GoodJobResult(SerializationInfo info, StreamingContext context)
{
Rmt = info.GetBoolean("rmt");
}
/** <inheritDoc /> */
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("rmt", Rmt);
}
}
/// <summary>
///
/// </summary>
public class BadJobResult : IBinarizable
{
/** */
public bool Rmt;
/// <summary>
///
/// </summary>
/// <param name="rmt"></param>
public BadJobResult(bool rmt)
{
Rmt = rmt;
}
/** <inheritDoc /> */
public void WriteBinary(IBinaryWriter writer)
{
throw new BinaryObjectException("Expected");
}
/** <inheritDoc /> */
public void ReadBinary(IBinaryReader reader)
{
throw new BinaryObjectException("Expected");
}
}
/// <summary>
///
/// </summary>
[Serializable]
public class GoodTaskResult
{
/** */
public int Res;
/// <summary>
///
/// </summary>
/// <param name="res"></param>
public GoodTaskResult(int res)
{
Res = res;
}
/// <summary>
///
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
public GoodTaskResult(SerializationInfo info, StreamingContext context)
{
Res = info.GetInt32("res");
}
/** <inheritDoc /> */
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("res", Res);
}
}
/// <summary>
///
/// </summary>
public class BadTaskResult
{
/** */
public int Res;
/// <summary>
///
/// </summary>
/// <param name="res"></param>
public BadTaskResult(int res)
{
Res = res;
}
}
/// <summary>
/// Marshalable exception.
/// </summary>
[Serializable]
public class GoodException : Exception
{
/** */
public ErrorMode Mode;
/// <summary>
///
/// </summary>
/// <param name="mode"></param>
public GoodException(ErrorMode mode)
{
Mode = mode;
}
/// <summary>
///
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
public GoodException(SerializationInfo info, StreamingContext context)
{
Mode = (ErrorMode)info.GetInt32("mode");
}
/** <inheritDoc /> */
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("mode", (int)Mode);
base.GetObjectData(info, context);
}
}
/// <summary>
/// Not marshalable exception.
/// </summary>
public class BadException : Exception
{
/** */
public ErrorMode Mode;
/// <summary>
///
/// </summary>
/// <param name="mode"></param>
public BadException(ErrorMode mode)
{
Mode = mode;
}
}
}
}
| |
// Copyright 2014 The Rector & Visitors of the University of Virginia
//
// 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 Xamarin;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using Sensus.UI;
using Sensus.Probes;
using Sensus.Context;
using Sensus.Exceptions;
using Sensus.iOS.Context;
using UIKit;
using Foundation;
using Syncfusion.SfChart.XForms.iOS.Renderers;
using Sensus.iOS.Callbacks;
using UserNotifications;
using Sensus.iOS.Notifications.UNUserNotifications;
using Sensus.iOS.Concurrent;
using Sensus.Encryption;
using System.Threading;
using Sensus.iOS.Notifications;
using Sensus.Notifications;
using System.Collections.Generic;
using System.Linq;
using Sensus.Probes.Location;
namespace Sensus.iOS
{
// The UIApplicationDelegate for the application. This class is responsible for launching the
// User Interface of the application, as well as listening (and optionally responding) to
// application events from iOS.
[Register("AppDelegate")]
public class AppDelegate : FormsApplicationDelegate
{
public override bool FinishedLaunching(UIApplication uiApplication, NSDictionary launchOptions)
{
DateTime finishLaunchStartTime = DateTime.Now;
UIDevice.CurrentDevice.BatteryMonitoringEnabled = true;
SensusContext.Current = new iOSSensusContext
{
Platform = Sensus.Context.Platform.iOS,
MainThreadSynchronizer = new MainConcurrent(),
SymmetricEncryption = new SymmetricEncryption(SensusServiceHelper.ENCRYPTION_KEY),
PowerConnectionChangeListener = new iOSPowerConnectionChangeListener()
};
SensusContext.Current.CallbackScheduler = new iOSTimerCallbackScheduler(); // new UNUserNotificationCallbackScheduler();
SensusContext.Current.Notifier = new UNUserNotificationNotifier();
UNUserNotificationCenter.Current.Delegate = new UNUserNotificationDelegate();
// we've seen cases where previously terminated runs of the app leave behind
// local notifications. clear these out now. any callbacks these notifications
// would have triggered are about to be rescheduled when the app is actived.
(SensusContext.Current.Notifier as iOSNotifier).RemoveAllNotifications();
// initialize stuff prior to app load
Forms.Init();
FormsMaps.Init();
// initialize the syncfusion charting system
#pragma warning disable RECS0026 // Possible unassigned object created by 'new'
new SfChartRenderer();
#pragma warning restore RECS0026 // Possible unassigned object created by 'new'
ZXing.Net.Mobile.Forms.iOS.Platform.Init();
// load the app, which starts crash reporting and analytics telemetry.
LoadApplication(new App());
// we have observed that, if the app is in the background and a push notification arrives,
// then ios may attempt to launch the app and call this method but only provide a few (~5)
// seconds for this method to return. exceeding this time results in a fored termination by
// ios. as we're about to deserialize a large JSON object below when initializing the service
// helper, we need to be careful about taking up too much time. start a background task to
// obtain as much background time as possible and report timeouts. needs to be after app load
// in case we need to report a timeout exception.
nint finishLaunchingTaskId = uiApplication.BeginBackgroundTask(() =>
{
string message = "Ran out of time while finishing app launch.";
SensusException.Report(message);
Console.Error.WriteLine(message);
});
// initialize service helper. must come after context initialization. desirable to come
// after app loading, in case we crash. crash reporting is initialized when the app
// object is created. nothing in the app creating and loading loop will depend on having
// an initialized service helper, so we should be fine.
SensusServiceHelper.Initialize(() => new iOSSensusServiceHelper());
// register for push notifications. must come after service helper initialization as we use
// the serivce helper below to submit the remote notification token to the backends. if the
// user subsequently denies authorization to display notifications, then all remote notifications
// will simply be delivered to the app silently, per the following:
//
// https://developer.apple.com/documentation/uikit/uiapplication/1623078-registerforremotenotifications
//
UIApplication.SharedApplication.RegisterForRemoteNotifications();
#if UI_TESTING
Forms.ViewInitialized += (sender, e) =>
{
if (!string.IsNullOrWhiteSpace(e.View.StyleId))
{
e.NativeView.AccessibilityIdentifier = e.View.StyleId;
}
};
Calabash.Start();
#endif
uiApplication.EndBackgroundTask(finishLaunchingTaskId);
// must come after app load
base.FinishedLaunching(uiApplication, launchOptions);
// record how long we took to launch. ios is eager to kill apps that don't start fast enough, so log information
// to help with debugging.
DateTime finishLaunchEndTime = DateTime.Now;
SensusServiceHelper.Get().Logger.Log("Took " + (finishLaunchEndTime - finishLaunchStartTime) + " to finish launching.", LoggingLevel.Normal, GetType());
return true;
}
public override async void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
{
// hang on to the token. we register for remote notifications after initializing the helper,
// so this should be fine.
iOSSensusServiceHelper serviceHelper = SensusServiceHelper.Get() as iOSSensusServiceHelper;
serviceHelper.PushNotificationTokenData = deviceToken;
// update push notification registrations. this depends on internet connectivity to S3
// so it might hang if connectivity is poor. ensure we don't violate execution limits.
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
nint updatePushNotificationRegistrationsTaskId = application.BeginBackgroundTask(cancellationTokenSource.Cancel);
await serviceHelper.UpdatePushNotificationRegistrationsAsync(cancellationTokenSource.Token);
application.EndBackgroundTask(updatePushNotificationRegistrationsTaskId);
}
public override bool OpenUrl(UIApplication app, NSUrl url, NSDictionary options)
{
if (url?.PathExtension == "json")
{
System.Threading.Tasks.Task.Run(async () =>
{
try
{
Protocol protocol = null;
if (url.Scheme == "sensuss")
{
protocol = await Protocol.DeserializeAsync(new Uri("https://" + url.AbsoluteString.Substring(url.AbsoluteString.IndexOf('/') + 2).Trim()), true);
}
else
{
protocol = await Protocol.DeserializeAsync(File.ReadAllBytes(url.Path), true);
}
await Protocol.DisplayAndStartAsync(protocol);
}
catch (Exception ex)
{
InvokeOnMainThread(() =>
{
string message = "Failed to get study: " + ex.Message;
SensusServiceHelper.Get().Logger.Log(message, LoggingLevel.Normal, GetType());
new UIAlertView("Error", message, default(IUIAlertViewDelegate), "Close").Show();
});
}
});
return true;
}
else
{
return false;
}
}
public override async void OnActivated(UIApplication uiApplication)
{
base.OnActivated(uiApplication);
try
{
await SensusContext.Current.MainThreadSynchronizer.ExecuteThreadSafe(async () =>
{
// request authorization to show notifications to the user for data/survey requests.
bool notificationsAuthorized = false;
// if notifications were previously authorized and configured, there's nothing more to do.
UNNotificationSettings settings = await UNUserNotificationCenter.Current.GetNotificationSettingsAsync();
if (settings.BadgeSetting == UNNotificationSetting.Enabled &&
settings.SoundSetting == UNNotificationSetting.Enabled &&
settings.AlertSetting == UNNotificationSetting.Enabled)
{
notificationsAuthorized = true;
}
else
{
// request authorization for notifications. if the user previously denied authorization, this will simply return non-granted.
Tuple<bool, NSError> grantedError = await UNUserNotificationCenter.Current.RequestAuthorizationAsync(UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound | UNAuthorizationOptions.Alert);
notificationsAuthorized = grantedError.Item1;
}
// reset the badge number before starting. it appears that badge numbers from previous installations
// and instantiations of the app hang around.
if (notificationsAuthorized)
{
UIApplication.SharedApplication.ApplicationIconBadgeNumber = 0;
}
// ensure service helper is running. it is okay to call the following line multiple times, as repeats have no effect.
// per apple guidelines, sensus will run without notifications being authorized above, but the user's ability to
// participate will certainly be reduced, as they won't be made aware of probe requests, surveys, etc.
await SensusServiceHelper.Get().StartAsync();
// update/run all callbacks
await (SensusContext.Current.CallbackScheduler as iOSCallbackScheduler).UpdateCallbacksOnActivationAsync();
// disabling notifications will greatly impair the user's studies. let the user know.
if (!notificationsAuthorized)
{
// warn the user and help them to enable notifications
UIAlertView warning = new UIAlertView("Warning", "Notifications are disabled. Please enable notifications to participate fully in your studies. Tap the button below to do this now.", default(IUIAlertViewDelegate), "Close", "Open Notification Settings");
warning.Dismissed += async (sender, e) =>
{
if (e.ButtonIndex == 1)
{
NSUrl notificationSettingsURL = new NSUrl(UIApplication.OpenSettingsUrlString.ToString());
await uiApplication.OpenUrlAsync(notificationSettingsURL, new UIApplicationOpenUrlOptions());
}
};
warning.Show();
}
#if UI_TESTING
// load and run the UI testing protocol
string filePath = NSBundle.MainBundle.PathForResource("UiTestingProtocol", "json");
using (Stream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
await Protocol.RunUiTestingProtocolAsync(file);
}
#endif
});
}
catch (Exception ex)
{
SensusException.Report("Exception while activating: " + ex.Message, ex);
}
}
public override void FailedToRegisterForRemoteNotifications(UIApplication application, NSError error)
{
SensusException.Report("Failed to register for remote notifications.", error == null ? null : new Exception(error.ToString()));
}
public override async void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)
{
UIBackgroundFetchResult remoteNotificationResult;
// set up a cancellation token for processing within limits. the token will be cancelled
// if we run out of time or an exception is thrown in this method.
CancellationTokenSource cancellationTokenSource = null;
nint? receiveRemoteNotificationTaskId = null;
try
{
cancellationTokenSource = new CancellationTokenSource();
// we have limited time to process remote notifications: https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/pushing_updates_to_your_app_silently
// start background task to (1) obtain any possible background processing time and (2) get
// notified when background time is about to expire. we used to hard code a fixed amount
// of time (~30 seconds per above link), but this might change without us knowing about it.
SensusServiceHelper.Get().Logger.Log("Starting background task for remote notification processing.", LoggingLevel.Normal, GetType());
receiveRemoteNotificationTaskId = application.BeginBackgroundTask(() =>
{
SensusServiceHelper.Get().Logger.Log("Cancelling token for remote notification processing due to iOS background processing limitations.", LoggingLevel.Normal, GetType());
cancellationTokenSource.Cancel();
});
NSDictionary aps = userInfo[new NSString("aps")] as NSDictionary;
NSDictionary alert = aps[new NSString("alert")] as NSDictionary;
PushNotification pushNotification = new PushNotification
{
Id = (userInfo[new NSString("id")] as NSString).ToString(),
ProtocolId = (userInfo[new NSString("protocol")] as NSString).ToString(),
Update = bool.Parse((userInfo[new NSString("update")] as NSString).ToString()),
Title = (alert[new NSString("title")] as NSString).ToString(),
Body = (alert[new NSString("body")] as NSString).ToString(),
Sound = (aps[new NSString("sound")] as NSString).ToString()
};
// backend key might be blank
string backendKeyString = (userInfo[new NSString("backend-key")] as NSString).ToString();
if (!string.IsNullOrWhiteSpace(backendKeyString))
{
pushNotification.BackendKey = new Guid(backendKeyString);
}
await SensusContext.Current.Notifier.ProcessReceivedPushNotificationAsync(pushNotification, cancellationTokenSource.Token);
// even if the cancellation token was cancelled, we were still successful at downloading the updates.
// any amount of update application we were able to do in addition to the download is bonus. updates
// will continue to be applied on subsequent push notifications and health tests.
remoteNotificationResult = UIBackgroundFetchResult.NewData;
}
catch (Exception ex)
{
SensusException.Report("Exception while processing remote notification: " + ex.Message + ". Push notification dictionary content: " + userInfo, ex);
// we might have already cancelled the token, but we might have also just hit a bug. in
// either case, cancel the token and set the result accordingly.
try
{
cancellationTokenSource.Cancel();
}
catch (Exception)
{ }
remoteNotificationResult = UIBackgroundFetchResult.Failed;
}
finally
{
// we're done. ensure that the cancellation token cannot be cancelled any
// longer (e.g., due to background time expiring above) by disposing it.
if (cancellationTokenSource != null)
{
try
{
cancellationTokenSource.Dispose();
}
catch (Exception)
{ }
}
// end the background task
if (receiveRemoteNotificationTaskId.HasValue)
{
try
{
SensusServiceHelper.Get().Logger.Log("Ending background task for remote notification processing.", LoggingLevel.Normal, GetType());
application.EndBackgroundTask(receiveRemoteNotificationTaskId.Value);
}
catch (Exception)
{ }
}
}
// invoke the completion handler to let ios know that, and how, we have finished.
completionHandler?.Invoke(remoteNotificationResult);
}
// This method should be used to release shared resources and it should store the application state.
// If your application supports background exection this method is called instead of WillTerminate
// when the user quits.
public async override void DidEnterBackground(UIApplication uiApplication)
{
nint enterBackgroundTaskId = uiApplication.BeginBackgroundTask(() =>
{
// not much to do if we run out of time. just report it.
string message = "Ran out of background time while entering background.";
SensusServiceHelper.Get().Logger.Log(message, LoggingLevel.Normal, GetType());
SensusException.Report(message);
});
iOSSensusServiceHelper serviceHelper = SensusServiceHelper.Get() as iOSSensusServiceHelper;
// if the callback scheduler is timer-based and gps is not running then we need to request remote notifications
if (SensusContext.Current.CallbackScheduler is iOSTimerCallbackScheduler scheduler)
{
bool gpsIsRunning = SensusServiceHelper.Get().GetRunningProtocols().SelectMany(x => x.Probes).OfType<ListeningLocationProbe>().Any(x => x.Enabled);
await scheduler.RequestNotificationsAsync(gpsIsRunning);
}
// save app state
await serviceHelper.SaveAsync();
uiApplication.EndBackgroundTask(enterBackgroundTaskId);
}
// This method is called when the application is about to terminate. Save data, if needed.
public override void WillTerminate(UIApplication uiApplication)
{
// this method won't be called when the user kills the app using multitasking; however,
// it should be called if the system kills the app when it's running in the background.
// it should also be called if the system shuts down due to loss of battery power.
// there doesn't appear to be a way to gracefully stop the app when the user kills it
// via multitasking...we'll have to live with that.
SensusServiceHelper serviceHelper = SensusServiceHelper.Get();
// we're not going to stop the service helper before termination, so that -- if and when
// the app relaunches -- protocols that are currently running will be restarted. therefore,
// we need to manually add a stop time to each running probe to ensure participation
// rates are calculated correctly.
foreach (Protocol protocol in serviceHelper.RegisteredProtocols)
{
if (protocol.State == ProtocolState.Running)
{
foreach (Probe probe in protocol.Probes)
{
if (probe.State == ProbeState.Running)
{
lock (probe.StartStopTimes)
{
probe.StartStopTimes.Add(new Tuple<bool, DateTime>(false, DateTime.Now));
}
}
}
}
}
// some online resources indicate that no background time can be requested from within this
// method. so, instead of beginning a background task, just wait for the call to finish.
serviceHelper.SaveAsync().Wait();
}
}
}
| |
/*******************************************************************************
* Copyright (c) 2013, Daniel Murphy
* 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.
******************************************************************************/
/**
* Created at 2:51:18 PM Jan 23, 2011
*/
using System;
using System.Collections.Generic;
using SharpBox2D.Callbacks;
using SharpBox2D.Collision;
using SharpBox2D.Collision.Shapes;
using SharpBox2D.Common;
using SharpBox2D.Dynamics;
using SharpBox2D.Dynamics.Contacts;
using SharpBox2D.Dynamics.Joints;
using SharpBox2D.TestBed.Framework;
namespace SharpBox2D.TestBed.Tests
{
/**
* @author Daniel Murphy
*/
public class CollisionProcessing : TestbedTest
{
public override bool isSaveLoadEnabled()
{
return true;
}
public override void initTest(bool deserialized)
{
if (deserialized)
{
return;
}
// Ground body
{
EdgeShape shape = new EdgeShape();
shape.set(new Vec2(-50.0f, 0.0f), new Vec2(50.0f, 0.0f));
FixtureDef sd = new FixtureDef();
sd.shape = shape;
BodyDef bd = new BodyDef();
Body ground = getWorld().createBody(bd);
ground.createFixture(sd);
}
float xLo = -5.0f, xHi = 5.0f;
float yLo = 2.0f, yHi = 35.0f;
// Small triangle
Vec2[] vertices = new Vec2[3];
vertices[0] = new Vec2(-1.0f, 0.0f);
vertices[1] = new Vec2(1.0f, 0.0f);
vertices[2] = new Vec2(0.0f, 2.0f);
PolygonShape polygon = new PolygonShape();
polygon.set(vertices, 3);
FixtureDef triangleShapeDef = new FixtureDef();
triangleShapeDef.shape = polygon;
triangleShapeDef.density = 1.0f;
BodyDef triangleBodyDef = new BodyDef();
triangleBodyDef.type = BodyType.DYNAMIC;
triangleBodyDef.position.set(MathUtils.randomFloat(xLo, xHi), MathUtils.randomFloat(yLo, yHi));
Body body1 = getWorld().createBody(triangleBodyDef);
body1.createFixture(triangleShapeDef);
// Large triangle (recycle definitions)
vertices[0].mulLocal(2.0f);
vertices[1].mulLocal(2.0f);
vertices[2].mulLocal(2.0f);
polygon.set(vertices, 3);
triangleBodyDef.position.set(MathUtils.randomFloat(xLo, xHi), MathUtils.randomFloat(yLo, yHi));
Body body2 = getWorld().createBody(triangleBodyDef);
body2.createFixture(triangleShapeDef);
// Small box
polygon.setAsBox(1.0f, 0.5f);
FixtureDef boxShapeDef = new FixtureDef();
boxShapeDef.shape = polygon;
boxShapeDef.density = 1.0f;
BodyDef boxBodyDef = new BodyDef();
boxBodyDef.type = BodyType.DYNAMIC;
boxBodyDef.position.set(MathUtils.randomFloat(xLo, xHi), MathUtils.randomFloat(yLo, yHi));
Body body3 = getWorld().createBody(boxBodyDef);
body3.createFixture(boxShapeDef);
// Large box (recycle definitions)
polygon.setAsBox(2.0f, 1.0f);
boxBodyDef.position.set(MathUtils.randomFloat(xLo, xHi), MathUtils.randomFloat(yLo, yHi));
Body body4 = getWorld().createBody(boxBodyDef);
body4.createFixture(boxShapeDef);
// Small circle
CircleShape circle = new CircleShape();
circle.m_radius = 1.0f;
FixtureDef circleShapeDef = new FixtureDef();
circleShapeDef.shape = circle;
circleShapeDef.density = 1.0f;
BodyDef circleBodyDef = new BodyDef();
circleBodyDef.type = BodyType.DYNAMIC;
circleBodyDef.position.set(MathUtils.randomFloat(xLo, xHi), MathUtils.randomFloat(yLo, yHi));
Body body5 = getWorld().createBody(circleBodyDef);
body5.createFixture(circleShapeDef);
// Large circle
circle.m_radius *= 2.0f;
circleBodyDef.position.set(MathUtils.randomFloat(xLo, xHi), MathUtils.randomFloat(yLo, yHi));
Body body6 = getWorld().createBody(circleBodyDef);
body6.createFixture(circleShapeDef);
}
public override void step(TestbedSettings settings)
{
base.step(settings);
// We are going to destroy some bodies according to contact
// points. We must buffer the bodies that should be destroyed
// because they may belong to multiple contact points.
HashSet<Body> nuke = new HashSet<Body>();
// Traverse the contact results. Destroy bodies that
// are touching heavier bodies.
for (int i = 0; i < getPointCount(); ++i)
{
ContactPoint point = points[i];
Body body1 = point.fixtureA.getBody();
Body body2 = point.fixtureB.getBody();
float mass1 = body1.getMass();
float mass2 = body2.getMass();
if (mass1 > 0.0f && mass2 > 0.0f)
{
if (mass2 > mass1)
{
nuke.Add(body1);
}
else
{
nuke.Add(body2);
}
}
}
// Sort the nuke array to group duplicates.
// Arrays.sort(nuke);
// Destroy the bodies, skipping duplicates.
foreach (Body b in nuke)
{
if (b != getBomb())
{
getWorld().destroyBody(b);
}
}
}
public override string getTestName()
{
return "Collision Processing";
}
}
}
| |
/* Generated SBE (Simple Binary Encoding) message codec */
using System;
using System.Text;
using System.Collections.Generic;
using Adaptive.Agrona;
namespace Adaptive.Cluster.Codecs {
public class BackupQueryDecoder
{
public const ushort BLOCK_LENGTH = 16;
public const ushort TEMPLATE_ID = 77;
public const ushort SCHEMA_ID = 111;
public const ushort SCHEMA_VERSION = 7;
private BackupQueryDecoder _parentMessage;
private IDirectBuffer _buffer;
protected int _offset;
protected int _limit;
protected int _actingBlockLength;
protected int _actingVersion;
public BackupQueryDecoder()
{
_parentMessage = this;
}
public ushort SbeBlockLength()
{
return BLOCK_LENGTH;
}
public ushort SbeTemplateId()
{
return TEMPLATE_ID;
}
public ushort SbeSchemaId()
{
return SCHEMA_ID;
}
public ushort SbeSchemaVersion()
{
return SCHEMA_VERSION;
}
public string SbeSemanticType()
{
return "";
}
public IDirectBuffer Buffer()
{
return _buffer;
}
public int Offset()
{
return _offset;
}
public BackupQueryDecoder Wrap(
IDirectBuffer buffer, int offset, int actingBlockLength, int actingVersion)
{
this._buffer = buffer;
this._offset = offset;
this._actingBlockLength = actingBlockLength;
this._actingVersion = actingVersion;
Limit(offset + actingBlockLength);
return this;
}
public int EncodedLength()
{
return _limit - _offset;
}
public int Limit()
{
return _limit;
}
public void Limit(int limit)
{
this._limit = limit;
}
public static int CorrelationIdId()
{
return 1;
}
public static int CorrelationIdSinceVersion()
{
return 0;
}
public static int CorrelationIdEncodingOffset()
{
return 0;
}
public static int CorrelationIdEncodingLength()
{
return 8;
}
public static string CorrelationIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long CorrelationIdNullValue()
{
return -9223372036854775808L;
}
public static long CorrelationIdMinValue()
{
return -9223372036854775807L;
}
public static long CorrelationIdMaxValue()
{
return 9223372036854775807L;
}
public long CorrelationId()
{
return _buffer.GetLong(_offset + 0, ByteOrder.LittleEndian);
}
public static int ResponseStreamIdId()
{
return 2;
}
public static int ResponseStreamIdSinceVersion()
{
return 0;
}
public static int ResponseStreamIdEncodingOffset()
{
return 8;
}
public static int ResponseStreamIdEncodingLength()
{
return 4;
}
public static string ResponseStreamIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int ResponseStreamIdNullValue()
{
return -2147483648;
}
public static int ResponseStreamIdMinValue()
{
return -2147483647;
}
public static int ResponseStreamIdMaxValue()
{
return 2147483647;
}
public int ResponseStreamId()
{
return _buffer.GetInt(_offset + 8, ByteOrder.LittleEndian);
}
public static int VersionId()
{
return 3;
}
public static int VersionSinceVersion()
{
return 2;
}
public static int VersionEncodingOffset()
{
return 12;
}
public static int VersionEncodingLength()
{
return 4;
}
public static string VersionMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "optional";
}
return "";
}
public static int VersionNullValue()
{
return 0;
}
public static int VersionMinValue()
{
return 1;
}
public static int VersionMaxValue()
{
return 16777215;
}
public int Version()
{
return _buffer.GetInt(_offset + 12, ByteOrder.LittleEndian);
}
public static int ResponseChannelId()
{
return 4;
}
public static int ResponseChannelSinceVersion()
{
return 0;
}
public static string ResponseChannelCharacterEncoding()
{
return "US-ASCII";
}
public static string ResponseChannelMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int ResponseChannelHeaderLength()
{
return 4;
}
public int ResponseChannelLength()
{
int limit = _parentMessage.Limit();
return (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
}
public int GetResponseChannel(IMutableDirectBuffer dst, int dstOffset, int length)
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit(limit + headerLength + dataLength);
_buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public int GetResponseChannel(byte[] dst, int dstOffset, int length)
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit(limit + headerLength + dataLength);
_buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public string ResponseChannel()
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
_parentMessage.Limit(limit + headerLength + dataLength);
byte[] tmp = new byte[dataLength];
_buffer.GetBytes(limit + headerLength, tmp, 0, dataLength);
return Encoding.ASCII.GetString(tmp);
}
public static int EncodedCredentialsId()
{
return 5;
}
public static int EncodedCredentialsSinceVersion()
{
return 0;
}
public static string EncodedCredentialsMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int EncodedCredentialsHeaderLength()
{
return 4;
}
public int EncodedCredentialsLength()
{
int limit = _parentMessage.Limit();
return (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
}
public int GetEncodedCredentials(IMutableDirectBuffer dst, int dstOffset, int length)
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit(limit + headerLength + dataLength);
_buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public int GetEncodedCredentials(byte[] dst, int dstOffset, int length)
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit(limit + headerLength + dataLength);
_buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public override string ToString()
{
return AppendTo(new StringBuilder(100)).ToString();
}
public StringBuilder AppendTo(StringBuilder builder)
{
int originalLimit = Limit();
Limit(_offset + _actingBlockLength);
builder.Append("[BackupQuery](sbeTemplateId=");
builder.Append(TEMPLATE_ID);
builder.Append("|sbeSchemaId=");
builder.Append(SCHEMA_ID);
builder.Append("|sbeSchemaVersion=");
if (_parentMessage._actingVersion != SCHEMA_VERSION)
{
builder.Append(_parentMessage._actingVersion);
builder.Append('/');
}
builder.Append(SCHEMA_VERSION);
builder.Append("|sbeBlockLength=");
if (_actingBlockLength != BLOCK_LENGTH)
{
builder.Append(_actingBlockLength);
builder.Append('/');
}
builder.Append(BLOCK_LENGTH);
builder.Append("):");
//Token{signal=BEGIN_FIELD, name='correlationId', referencedName='null', description='null', id=1, version=0, deprecated=0, encodedLength=0, offset=0, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=0, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("CorrelationId=");
builder.Append(CorrelationId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='responseStreamId', referencedName='null', description='null', id=2, version=0, deprecated=0, encodedLength=0, offset=8, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int32', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=4, offset=8, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("ResponseStreamId=");
builder.Append(ResponseStreamId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='version', referencedName='null', description='null', id=3, version=2, deprecated=0, encodedLength=0, offset=12, componentTokenCount=3, encoding=Encoding{presence=OPTIONAL, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='version_t', referencedName='null', description='Protocol or application suite version.', id=-1, version=0, deprecated=0, encodedLength=4, offset=12, componentTokenCount=1, encoding=Encoding{presence=OPTIONAL, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=1, maxValue=16777215, nullValue=0, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("Version=");
builder.Append(Version());
builder.Append('|');
//Token{signal=BEGIN_VAR_DATA, name='responseChannel', referencedName='null', description='null', id=4, version=0, deprecated=0, encodedLength=0, offset=16, componentTokenCount=6, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("ResponseChannel=");
builder.Append(ResponseChannel());
builder.Append('|');
//Token{signal=BEGIN_VAR_DATA, name='encodedCredentials', referencedName='null', description='null', id=5, version=0, deprecated=0, encodedLength=0, offset=-1, componentTokenCount=6, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("EncodedCredentials=");
builder.Append(EncodedCredentialsLength() + " raw bytes");
Limit(originalLimit);
return builder;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace CloudConfVarnaEdition4._0_RestAPI.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
/* 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 Moq;
using NUnit.Framework;
using XenAdmin.Alerts;
using XenAdmin.Core;
using XenAdmin.Network;
using XenAdminTests.UnitTests.UnitTestHelper;
using XenAPI;
namespace XenAdminTests.UnitTests.AlertTests
{
[TestFixture, Category(TestCategories.Unit), Category(TestCategories.SmokeTest)]
public class XenServerPatchAlertTests
{
private Mock<IXenConnection> connA;
private Mock<IXenConnection> connB;
private Mock<Host> hostA;
private Mock<Host> hostB;
protected Cache cacheA;
protected Cache cacheB;
[Test]
public void TestAlertWithConnectionAndHosts()
{
XenServerPatch p = new XenServerPatch("uuid", "name", "My description", "guidance", string.Empty, "6.0.1", "http://url", "http://patchUrl", new DateTime(2011, 4, 1).ToString(), "", "");
XenServerPatchAlert alert = new XenServerPatchAlert(p);
alert.IncludeConnection(connA.Object);
alert.IncludeConnection(connB.Object);
alert.IncludeHosts(new List<Host> { hostA.Object, hostB.Object });
IUnitTestVerifier validator = new VerifyGetters(alert);
validator.Verify(new AlertClassUnitTestData
{
AppliesTo = "HostAName, HostBName, ConnAName, ConnBName",
FixLinkText = "Go to Web Page",
HelpID = "XenServerPatchAlert",
Description = "My description",
HelpLinkText = "Help",
Title = "New Update Available - name",
Priority = "Priority2"
});
Assert.IsFalse(alert.CanIgnore);
VerifyConnExpectations(Times.Once);
VerifyHostsExpectations(Times.Once);
}
[Test]
public void TestAlertWithHostsAndNoConnection()
{
XenServerPatch p = new XenServerPatch("uuid", "name", "My description", "guidance", string.Empty, "6.0.1", "http://url", "http://patchUrl", new DateTime(2011, 4, 1).ToString(), "1", "");
XenServerPatchAlert alert = new XenServerPatchAlert(p);
alert.IncludeHosts(new List<Host>() { hostA.Object, hostB.Object });
IUnitTestVerifier validator = new VerifyGetters(alert);
validator.Verify(new AlertClassUnitTestData
{
AppliesTo = "HostAName, HostBName",
FixLinkText = "Go to Web Page",
HelpID = "XenServerPatchAlert",
Description = "My description",
HelpLinkText = "Help",
Title = "New Update Available - name",
Priority = "Priority1"
});
Assert.IsFalse(alert.CanIgnore);
VerifyConnExpectations(Times.Never);
VerifyHostsExpectations(Times.Once);
}
[Test]
public void TestAlertWithConnectionAndNoHosts()
{
XenServerPatch p = new XenServerPatch("uuid", "name", "My description", "guidance", string.Empty, "6.0.1", "http://url", "http://patchUrl", new DateTime(2011, 4, 1).ToString(), "0", "");
XenServerPatchAlert alert = new XenServerPatchAlert(p);
alert.IncludeConnection(connA.Object);
alert.IncludeConnection(connB.Object);
IUnitTestVerifier validator = new VerifyGetters(alert);
validator.Verify(new AlertClassUnitTestData
{
AppliesTo = "ConnAName, ConnBName",
FixLinkText = "Go to Web Page",
HelpID = "XenServerPatchAlert",
Description = "My description",
HelpLinkText = "Help",
Title = "New Update Available - name",
Priority = "Unknown"
});
Assert.IsFalse(alert.CanIgnore);
VerifyConnExpectations(Times.Once);
VerifyHostsExpectations(Times.Never);
}
[Test]
public void TestAlertWithNoConnectionAndNoHosts()
{
XenServerPatch p = new XenServerPatch("uuid", "name", "My description", "guidance", string.Empty, "6.0.1", "http://url", "http://patchUrl", new DateTime(2011, 4, 1).ToString(), "5", "");
XenServerPatchAlert alert = new XenServerPatchAlert(p);
IUnitTestVerifier validator = new VerifyGetters(alert);
validator.Verify(new AlertClassUnitTestData
{
AppliesTo = string.Empty,
FixLinkText = "Go to Web Page",
HelpID = "XenServerPatchAlert",
Description = "My description",
HelpLinkText = "Help",
Title = "New Update Available - name",
Priority = "Priority5"
});
Assert.IsTrue(alert.CanIgnore);
VerifyConnExpectations(Times.Never);
VerifyHostsExpectations(Times.Never);
}
[Test, ExpectedException(typeof(NullReferenceException))]
public void TestAlertWithNullPatch()
{
XenServerPatchAlert alert = new XenServerPatchAlert(null);
}
private void VerifyConnExpectations(Func<Times> times)
{
connA.VerifyGet(n => n.Name, times());
connB.VerifyGet(n => n.Name, times());
}
private void VerifyHostsExpectations(Func<Times> times)
{
hostA.VerifyGet(n => n.Name, times());
hostB.VerifyGet(n => n.Name, times());
}
[SetUp]
public void TestSetUp()
{
connA = new Mock<IXenConnection>(MockBehavior.Strict);
connA.Setup(n => n.Name).Returns("ConnAName");
cacheA = new Cache();
connA.Setup(x => x.Cache).Returns(cacheA);
connB = new Mock<IXenConnection>(MockBehavior.Strict);
connB.Setup(n => n.Name).Returns("ConnBName");
cacheB = new Cache();
connB.Setup(x => x.Cache).Returns(cacheB);
hostA = new Mock<Host>(MockBehavior.Strict);
hostA.Setup(n => n.Name).Returns("HostAName");
hostA.Setup(n => n.Equals(It.IsAny<object>())).Returns((object o) => ReferenceEquals(o, hostA.Object));
hostB = new Mock<Host>(MockBehavior.Strict);
hostB.Setup(n => n.Name).Returns("HostBName");
hostB.Setup(n => n.Equals(It.IsAny<object>())).Returns((object o) => ReferenceEquals(o, hostB.Object));
}
[TearDown]
public void TestTearDown()
{
cacheA = null;
cacheB = null;
connA = null;
connB = null;
hostA = null;
hostB = null;
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="X509CertificateStoreTokenResolver.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace System.IdentityModel.Tokens
{
using System;
using System.Collections.Generic;
using System.IdentityModel.Selectors;
using System.Security.Cryptography.X509Certificates;
using System.Text;
/// <summary>
/// Token Resolver that can resolve X509SecurityTokens against a given X.509 Certificate Store.
/// </summary>
public class X509CertificateStoreTokenResolver : SecurityTokenResolver
{
private string storeName;
private StoreLocation storeLocation;
/// <summary>
/// Initializes an instance of <see cref="X509CertificateStoreTokenResolver"/>
/// </summary>
public X509CertificateStoreTokenResolver()
: this(System.Security.Cryptography.X509Certificates.StoreName.My, StoreLocation.LocalMachine)
{
}
/// <summary>
/// Initializes an instance of <see cref="X509CertificateStoreTokenResolver"/>
/// </summary>
/// <param name="storeName">StoreName of the X.509 Certificate Store.</param>
/// <param name="storeLocation">StoreLocation of the X.509 Certificate store.</param>
public X509CertificateStoreTokenResolver(StoreName storeName, StoreLocation storeLocation)
: this(Enum.GetName(typeof(System.Security.Cryptography.X509Certificates.StoreName), storeName), storeLocation)
{
}
/// <summary>
/// Initializes an instance of <see cref="X509CertificateStoreTokenResolver"/>
/// </summary>
/// <param name="storeName">StoreName of the X.509 Certificate Store.</param>
/// <param name="storeLocation">StoreLocation of the X.509 Certificate store.</param>
public X509CertificateStoreTokenResolver(string storeName, StoreLocation storeLocation)
{
if (string.IsNullOrEmpty(storeName))
{
throw DiagnosticUtility.ThrowHelperArgumentNullOrEmptyString("storeName");
}
this.storeName = storeName;
this.storeLocation = storeLocation;
}
/// <summary>
/// Gets the StoreName used by this TokenResolver.
/// </summary>
public string StoreName
{
get { return this.storeName; }
}
/// <summary>
/// Gets the StoreLocation used by this TokenResolver.
/// </summary>
public StoreLocation StoreLocation
{
get { return this.storeLocation; }
}
/// <summary>
/// Resolves the given SecurityKeyIdentifierClause to a SecurityKey.
/// </summary>
/// <param name="keyIdentifierClause">SecurityKeyIdentifierClause to resolve</param>
/// <param name="key">The resolved SecurityKey.</param>
/// <returns>True if successfully resolved.</returns>
/// <exception cref="ArgumentNullException">The input argument 'keyIdentifierClause' is null.</exception>
protected override bool TryResolveSecurityKeyCore(SecurityKeyIdentifierClause keyIdentifierClause, out SecurityKey key)
{
if (keyIdentifierClause == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("keyIdentifierClause");
}
key = null;
EncryptedKeyIdentifierClause encryptedKeyIdentifierClause = keyIdentifierClause as EncryptedKeyIdentifierClause;
if (encryptedKeyIdentifierClause != null)
{
SecurityKeyIdentifier keyIdentifier = encryptedKeyIdentifierClause.EncryptingKeyIdentifier;
if (keyIdentifier != null && keyIdentifier.Count > 0)
{
for (int i = 0; i < keyIdentifier.Count; i++)
{
SecurityKey unwrappingSecurityKey = null;
if (TryResolveSecurityKey(keyIdentifier[i], out unwrappingSecurityKey))
{
byte[] wrappedKey = encryptedKeyIdentifierClause.GetEncryptedKey();
string wrappingAlgorithm = encryptedKeyIdentifierClause.EncryptionMethod;
byte[] unwrappedKey = unwrappingSecurityKey.DecryptKey(wrappingAlgorithm, wrappedKey);
key = new InMemorySymmetricSecurityKey(unwrappedKey, false);
return true;
}
}
}
}
else
{
SecurityToken token = null;
if (TryResolveToken(keyIdentifierClause, out token))
{
if (token.SecurityKeys.Count > 0)
{
key = token.SecurityKeys[0];
return true;
}
}
}
return false;
}
/// <summary>
/// Resolves the given SecurityKeyIdentifier to a SecurityToken.
/// </summary>
/// <param name="keyIdentifier">SecurityKeyIdentifier to resolve.</param>
/// <param name="token">The resolved SecurityToken.</param>
/// <returns>True if successfully resolved.</returns>
/// <exception cref="ArgumentNullException">The input argument 'keyIdentifier' is null.</exception>
protected override bool TryResolveTokenCore(SecurityKeyIdentifier keyIdentifier, out SecurityToken token)
{
if (keyIdentifier == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("keyIdentifier");
}
token = null;
foreach (SecurityKeyIdentifierClause clause in keyIdentifier)
{
if (TryResolveToken(clause, out token))
{
return true;
}
}
return false;
}
/// <summary>
/// Resolves the given SecurityKeyIdentifierClause to a SecurityToken.
/// </summary>
/// <param name="keyIdentifierClause">SecurityKeyIdentifierClause to resolve.</param>
/// <param name="token">The resolved SecurityToken.</param>
/// <returns>True if successfully resolved.</returns>
/// <exception cref="ArgumentNullException">The input argument 'keyIdentifierClause' is null.</exception>
protected override bool TryResolveTokenCore(SecurityKeyIdentifierClause keyIdentifierClause, out SecurityToken token)
{
if (keyIdentifierClause == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("keyIdentifierClause");
}
token = null;
X509Store store = null;
X509Certificate2Collection certs = null;
try
{
store = new X509Store(this.storeName, this.storeLocation);
store.Open(OpenFlags.ReadOnly);
certs = store.Certificates;
foreach (X509Certificate2 cert in certs)
{
X509ThumbprintKeyIdentifierClause thumbprintKeyIdentifierClause = keyIdentifierClause as X509ThumbprintKeyIdentifierClause;
if (thumbprintKeyIdentifierClause != null && thumbprintKeyIdentifierClause.Matches(cert))
{
token = new X509SecurityToken(cert);
return true;
}
X509IssuerSerialKeyIdentifierClause issuerSerialKeyIdentifierClause = keyIdentifierClause as X509IssuerSerialKeyIdentifierClause;
if (issuerSerialKeyIdentifierClause != null && issuerSerialKeyIdentifierClause.Matches(cert))
{
token = new X509SecurityToken(cert);
return true;
}
X509SubjectKeyIdentifierClause subjectKeyIdentifierClause = keyIdentifierClause as X509SubjectKeyIdentifierClause;
if (subjectKeyIdentifierClause != null && subjectKeyIdentifierClause.Matches(cert))
{
token = new X509SecurityToken(cert);
return true;
}
X509RawDataKeyIdentifierClause rawDataKeyIdentifierClause = keyIdentifierClause as X509RawDataKeyIdentifierClause;
if (rawDataKeyIdentifierClause != null && rawDataKeyIdentifierClause.Matches(cert))
{
token = new X509SecurityToken(cert);
return true;
}
}
}
finally
{
if (certs != null)
{
for (int i = 0; i < certs.Count; i++)
{
certs[i].Reset();
}
}
if (store != null)
{
store.Close();
}
}
return false;
}
}
}
| |
// 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 Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Roslyn.Utilities;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Threading;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
internal sealed class CompilationContext
{
private static readonly SymbolDisplayFormat s_fullNameFormat =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
internal readonly CSharpCompilation Compilation;
internal readonly Binder NamespaceBinder; // Internal for test purposes.
private readonly MetadataDecoder _metadataDecoder;
private readonly MethodSymbol _currentFrame;
private readonly ImmutableArray<LocalSymbol> _locals;
private readonly ImmutableDictionary<string, DisplayClassVariable> _displayClassVariables;
private readonly ImmutableHashSet<string> _hoistedParameterNames;
private readonly ImmutableArray<LocalSymbol> _localsForBinding;
private readonly CSharpSyntaxNode _syntax;
private readonly bool _methodNotType;
/// <summary>
/// Create a context to compile expressions within a method scope.
/// </summary>
internal CompilationContext(
CSharpCompilation compilation,
MetadataDecoder metadataDecoder,
MethodSymbol currentFrame,
ImmutableArray<LocalSymbol> locals,
InScopeHoistedLocals inScopeHoistedLocals,
MethodDebugInfo methodDebugInfo,
CSharpSyntaxNode syntax)
{
Debug.Assert(string.IsNullOrEmpty(methodDebugInfo.DefaultNamespaceName));
Debug.Assert((syntax == null) || (syntax is ExpressionSyntax) || (syntax is LocalDeclarationStatementSyntax));
// TODO: syntax.SyntaxTree should probably be added to the compilation,
// but it isn't rooted by a CompilationUnitSyntax so it doesn't work (yet).
_currentFrame = currentFrame;
_syntax = syntax;
_methodNotType = !locals.IsDefault;
// NOTE: Since this is done within CompilationContext, it will not be cached.
// CONSIDER: The values should be the same everywhere in the module, so they
// could be cached.
// (Catch: what happens in a type context without a method def?)
this.Compilation = GetCompilationWithExternAliases(compilation, methodDebugInfo.ExternAliasRecords);
_metadataDecoder = metadataDecoder;
// Each expression compile should use a unique compilation
// to ensure expression-specific synthesized members can be
// added (anonymous types, for instance).
Debug.Assert(this.Compilation != compilation);
this.NamespaceBinder = CreateBinderChain(
this.Compilation,
(PEModuleSymbol)currentFrame.ContainingModule,
currentFrame.ContainingNamespace,
methodDebugInfo.ImportRecordGroups,
_metadataDecoder);
if (_methodNotType)
{
_locals = locals;
ImmutableArray<string> displayClassVariableNamesInOrder;
GetDisplayClassVariables(
currentFrame,
_locals,
inScopeHoistedLocals,
out displayClassVariableNamesInOrder,
out _displayClassVariables,
out _hoistedParameterNames);
Debug.Assert(displayClassVariableNamesInOrder.Length == _displayClassVariables.Count);
_localsForBinding = GetLocalsForBinding(_locals, displayClassVariableNamesInOrder, _displayClassVariables);
}
else
{
_locals = ImmutableArray<LocalSymbol>.Empty;
_displayClassVariables = ImmutableDictionary<string, DisplayClassVariable>.Empty;
_localsForBinding = ImmutableArray<LocalSymbol>.Empty;
}
// Assert that the cheap check for "this" is equivalent to the expensive check for "this".
Debug.Assert(
_displayClassVariables.ContainsKey(GeneratedNames.ThisProxyFieldName()) ==
_displayClassVariables.Values.Any(v => v.Kind == DisplayClassVariableKind.This));
}
internal CommonPEModuleBuilder CompileExpression(
string typeName,
string methodName,
ImmutableArray<Alias> aliases,
Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData,
DiagnosticBag diagnostics,
out ResultProperties resultProperties)
{
var properties = default(ResultProperties);
var objectType = this.Compilation.GetSpecialType(SpecialType.System_Object);
var synthesizedType = new EENamedTypeSymbol(
this.Compilation.SourceModule.GlobalNamespace,
objectType,
_syntax,
_currentFrame,
typeName,
methodName,
this,
(method, diags) =>
{
var hasDisplayClassThis = _displayClassVariables.ContainsKey(GeneratedNames.ThisProxyFieldName());
var binder = ExtendBinderChain(
_syntax,
aliases,
method,
this.NamespaceBinder,
hasDisplayClassThis,
_methodNotType);
var statementSyntax = _syntax as StatementSyntax;
return (statementSyntax == null) ?
BindExpression(binder, (ExpressionSyntax)_syntax, diags, out properties) :
BindStatement(binder, statementSyntax, diags, out properties);
});
var module = CreateModuleBuilder(
this.Compilation,
synthesizedType.Methods,
additionalTypes: ImmutableArray.Create((NamedTypeSymbol)synthesizedType),
testData: testData,
diagnostics: diagnostics);
Debug.Assert(module != null);
this.Compilation.Compile(
module,
win32Resources: null,
xmlDocStream: null,
generateDebugInfo: false,
diagnostics: diagnostics,
filterOpt: null,
cancellationToken: CancellationToken.None);
if (diagnostics.HasAnyErrors())
{
resultProperties = default(ResultProperties);
return null;
}
// Should be no name mangling since the caller provided explicit names.
Debug.Assert(synthesizedType.MetadataName == typeName);
Debug.Assert(synthesizedType.GetMembers()[0].MetadataName == methodName);
resultProperties = properties;
return module;
}
internal CommonPEModuleBuilder CompileAssignment(
string typeName,
string methodName,
ImmutableArray<Alias> aliases,
Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData,
DiagnosticBag diagnostics,
out ResultProperties resultProperties)
{
var objectType = this.Compilation.GetSpecialType(SpecialType.System_Object);
var synthesizedType = new EENamedTypeSymbol(
Compilation.SourceModule.GlobalNamespace,
objectType,
_syntax,
_currentFrame,
typeName,
methodName,
this,
(method, diags) =>
{
var hasDisplayClassThis = _displayClassVariables.ContainsKey(GeneratedNames.ThisProxyFieldName());
var binder = ExtendBinderChain(
_syntax,
aliases,
method,
this.NamespaceBinder,
hasDisplayClassThis,
methodNotType: true);
return BindAssignment(binder, (ExpressionSyntax)_syntax, diags);
});
var module = CreateModuleBuilder(
this.Compilation,
synthesizedType.Methods,
additionalTypes: ImmutableArray.Create((NamedTypeSymbol)synthesizedType),
testData: testData,
diagnostics: diagnostics);
Debug.Assert(module != null);
this.Compilation.Compile(
module,
win32Resources: null,
xmlDocStream: null,
generateDebugInfo: false,
diagnostics: diagnostics,
filterOpt: null,
cancellationToken: CancellationToken.None);
if (diagnostics.HasAnyErrors())
{
resultProperties = default(ResultProperties);
return null;
}
// Should be no name mangling since the caller provided explicit names.
Debug.Assert(synthesizedType.MetadataName == typeName);
Debug.Assert(synthesizedType.GetMembers()[0].MetadataName == methodName);
resultProperties = new ResultProperties(DkmClrCompilationResultFlags.PotentialSideEffect);
return module;
}
private static string GetNextMethodName(ArrayBuilder<MethodSymbol> builder)
{
return string.Format("<>m{0}", builder.Count);
}
/// <summary>
/// Generate a class containing methods that represent
/// the set of arguments and locals at the current scope.
/// </summary>
internal CommonPEModuleBuilder CompileGetLocals(
string typeName,
ArrayBuilder<LocalAndMethod> localBuilder,
bool argumentsOnly,
ImmutableArray<Alias> aliases,
Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData,
DiagnosticBag diagnostics)
{
var objectType = this.Compilation.GetSpecialType(SpecialType.System_Object);
var allTypeParameters = _currentFrame.GetAllTypeParameters();
var additionalTypes = ArrayBuilder<NamedTypeSymbol>.GetInstance();
EENamedTypeSymbol typeVariablesType = null;
if (!argumentsOnly && (allTypeParameters.Length > 0))
{
// Generate a generic type with matching type parameters.
// A null instance of the type will be used to represent the
// "Type variables" local.
typeVariablesType = new EENamedTypeSymbol(
this.Compilation.SourceModule.GlobalNamespace,
objectType,
_syntax,
_currentFrame,
ExpressionCompilerConstants.TypeVariablesClassName,
(m, t) => ImmutableArray.Create<MethodSymbol>(new EEConstructorSymbol(t)),
allTypeParameters,
(t1, t2) => allTypeParameters.SelectAsArray((tp, i, t) => (TypeParameterSymbol)new SimpleTypeParameterSymbol(t, i, tp.Name), t2));
additionalTypes.Add(typeVariablesType);
}
var synthesizedType = new EENamedTypeSymbol(
Compilation.SourceModule.GlobalNamespace,
objectType,
_syntax,
_currentFrame,
typeName,
(m, container) =>
{
var methodBuilder = ArrayBuilder<MethodSymbol>.GetInstance();
if (!argumentsOnly)
{
// Pseudo-variables: $exception, $ReturnValue, etc.
if (aliases.Length > 0)
{
var sourceAssembly = Compilation.SourceAssembly;
var typeNameDecoder = new EETypeNameDecoder(Compilation, (PEModuleSymbol)_currentFrame.ContainingModule);
foreach (var alias in aliases)
{
var local = PlaceholderLocalSymbol.Create(
typeNameDecoder,
_currentFrame,
sourceAssembly,
alias);
var methodName = GetNextMethodName(methodBuilder);
var syntax = SyntaxFactory.IdentifierName(SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken));
var aliasMethod = this.CreateMethod(container, methodName, syntax, (method, diags) =>
{
var expression = new BoundLocal(syntax, local, constantValueOpt: null, type: local.Type);
return new BoundReturnStatement(syntax, expression) { WasCompilerGenerated = true };
});
var flags = local.IsWritable ? DkmClrCompilationResultFlags.None : DkmClrCompilationResultFlags.ReadOnlyResult;
localBuilder.Add(MakeLocalAndMethod(local, aliasMethod, flags));
methodBuilder.Add(aliasMethod);
}
}
// "this" for non-static methods that are not display class methods or
// display class methods where the display class contains "<>4__this".
if (!m.IsStatic && (!IsDisplayClassType(m.ContainingType) || _displayClassVariables.ContainsKey(GeneratedNames.ThisProxyFieldName())))
{
var methodName = GetNextMethodName(methodBuilder);
var method = this.GetThisMethod(container, methodName);
localBuilder.Add(new CSharpLocalAndMethod("this", "this", method, DkmClrCompilationResultFlags.None)); // Note: writable in dev11.
methodBuilder.Add(method);
}
}
// Hoisted method parameters (represented as locals in the EE).
if (!_hoistedParameterNames.IsEmpty)
{
int localIndex = 0;
foreach (var local in _localsForBinding)
{
// Since we are showing hoisted method parameters first, the parameters may appear out of order
// in the Locals window if only some of the parameters are hoisted. This is consistent with the
// behavior of the old EE.
if (_hoistedParameterNames.Contains(local.Name))
{
AppendLocalAndMethod(localBuilder, methodBuilder, local, container, localIndex, GetLocalResultFlags(local));
}
localIndex++;
}
}
// Method parameters (except those that have been hoisted).
int parameterIndex = m.IsStatic ? 0 : 1;
foreach (var parameter in m.Parameters)
{
var parameterName = parameter.Name;
if (!_hoistedParameterNames.Contains(parameterName) && GeneratedNames.GetKind(parameterName) == GeneratedNameKind.None)
{
AppendParameterAndMethod(localBuilder, methodBuilder, parameter, container, parameterIndex);
}
parameterIndex++;
}
if (!argumentsOnly)
{
// Locals.
int localIndex = 0;
foreach (var local in _localsForBinding)
{
if (!_hoistedParameterNames.Contains(local.Name))
{
AppendLocalAndMethod(localBuilder, methodBuilder, local, container, localIndex, GetLocalResultFlags(local));
}
localIndex++;
}
// "Type variables".
if ((object)typeVariablesType != null)
{
var methodName = GetNextMethodName(methodBuilder);
var returnType = typeVariablesType.Construct(allTypeParameters.Cast<TypeParameterSymbol, TypeSymbol>());
var method = this.GetTypeVariablesMethod(container, methodName, returnType);
localBuilder.Add(new CSharpLocalAndMethod(
ExpressionCompilerConstants.TypeVariablesLocalName,
ExpressionCompilerConstants.TypeVariablesLocalName,
method,
DkmClrCompilationResultFlags.ReadOnlyResult));
methodBuilder.Add(method);
}
}
return methodBuilder.ToImmutableAndFree();
});
additionalTypes.Add(synthesizedType);
var module = CreateModuleBuilder(
this.Compilation,
synthesizedType.Methods,
additionalTypes: additionalTypes.ToImmutableAndFree(),
testData: testData,
diagnostics: diagnostics);
Debug.Assert(module != null);
this.Compilation.Compile(
module,
win32Resources: null,
xmlDocStream: null,
generateDebugInfo: false,
diagnostics: diagnostics,
filterOpt: null,
cancellationToken: CancellationToken.None);
return diagnostics.HasAnyErrors() ? null : module;
}
private void AppendLocalAndMethod(
ArrayBuilder<LocalAndMethod> localBuilder,
ArrayBuilder<MethodSymbol> methodBuilder,
LocalSymbol local,
EENamedTypeSymbol container,
int localIndex,
DkmClrCompilationResultFlags resultFlags)
{
var methodName = GetNextMethodName(methodBuilder);
var method = this.GetLocalMethod(container, methodName, local.Name, localIndex);
localBuilder.Add(MakeLocalAndMethod(local, method, resultFlags));
methodBuilder.Add(method);
}
private void AppendParameterAndMethod(
ArrayBuilder<LocalAndMethod> localBuilder,
ArrayBuilder<MethodSymbol> methodBuilder,
ParameterSymbol parameter,
EENamedTypeSymbol container,
int parameterIndex)
{
// Note: The native EE doesn't do this, but if we don't escape keyword identifiers,
// the ResultProvider needs to be able to disambiguate cases like "this" and "@this",
// which it can't do correctly without semantic information.
var name = SyntaxHelpers.EscapeKeywordIdentifiers(parameter.Name);
var methodName = GetNextMethodName(methodBuilder);
var method = this.GetParameterMethod(container, methodName, name, parameterIndex);
localBuilder.Add(new CSharpLocalAndMethod(name, name, method, DkmClrCompilationResultFlags.None));
methodBuilder.Add(method);
}
private static LocalAndMethod MakeLocalAndMethod(LocalSymbol local, MethodSymbol method, DkmClrCompilationResultFlags flags)
{
// Note: The native EE doesn't do this, but if we don't escape keyword identifiers,
// the ResultProvider needs to be able to disambiguate cases like "this" and "@this",
// which it can't do correctly without semantic information.
var escapedName = SyntaxHelpers.EscapeKeywordIdentifiers(local.Name);
var displayName = (local as PlaceholderLocalSymbol)?.DisplayName ?? escapedName;
return new CSharpLocalAndMethod(escapedName, displayName, method, flags);
}
private static EEAssemblyBuilder CreateModuleBuilder(
CSharpCompilation compilation,
ImmutableArray<MethodSymbol> methods,
ImmutableArray<NamedTypeSymbol> additionalTypes,
Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData,
DiagnosticBag diagnostics)
{
// Each assembly must have a unique name.
var emitOptions = new EmitOptions(outputNameOverride: ExpressionCompilerUtilities.GenerateUniqueName());
string runtimeMetadataVersion = compilation.GetRuntimeMetadataVersion(emitOptions, diagnostics);
var serializationProperties = compilation.ConstructModuleSerializationProperties(emitOptions, runtimeMetadataVersion);
return new EEAssemblyBuilder(compilation.SourceAssembly, emitOptions, methods, serializationProperties, additionalTypes, testData);
}
internal EEMethodSymbol CreateMethod(
EENamedTypeSymbol container,
string methodName,
CSharpSyntaxNode syntax,
GenerateMethodBody generateMethodBody)
{
return new EEMethodSymbol(
container,
methodName,
syntax.Location,
_currentFrame,
_locals,
_localsForBinding,
_displayClassVariables,
generateMethodBody);
}
private EEMethodSymbol GetLocalMethod(EENamedTypeSymbol container, string methodName, string localName, int localIndex)
{
var syntax = SyntaxFactory.IdentifierName(localName);
return this.CreateMethod(container, methodName, syntax, (method, diagnostics) =>
{
var local = method.LocalsForBinding[localIndex];
var expression = new BoundLocal(syntax, local, constantValueOpt: local.GetConstantValue(null, null, diagnostics), type: local.Type);
return new BoundReturnStatement(syntax, expression) { WasCompilerGenerated = true };
});
}
private EEMethodSymbol GetParameterMethod(EENamedTypeSymbol container, string methodName, string parameterName, int parameterIndex)
{
var syntax = SyntaxFactory.IdentifierName(parameterName);
return this.CreateMethod(container, methodName, syntax, (method, diagnostics) =>
{
var parameter = method.Parameters[parameterIndex];
var expression = new BoundParameter(syntax, parameter);
return new BoundReturnStatement(syntax, expression) { WasCompilerGenerated = true };
});
}
private EEMethodSymbol GetThisMethod(EENamedTypeSymbol container, string methodName)
{
var syntax = SyntaxFactory.ThisExpression();
return this.CreateMethod(container, methodName, syntax, (method, diagnostics) =>
{
var expression = new BoundThisReference(syntax, GetNonDisplayClassContainer(container.SubstitutedSourceType));
return new BoundReturnStatement(syntax, expression) { WasCompilerGenerated = true };
});
}
private EEMethodSymbol GetTypeVariablesMethod(EENamedTypeSymbol container, string methodName, NamedTypeSymbol typeVariablesType)
{
var syntax = SyntaxFactory.IdentifierName(SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken));
return this.CreateMethod(container, methodName, syntax, (method, diagnostics) =>
{
var type = method.TypeMap.SubstituteNamedType(typeVariablesType);
var expression = new BoundObjectCreationExpression(syntax, type.InstanceConstructors[0]);
var statement = new BoundReturnStatement(syntax, expression) { WasCompilerGenerated = true };
return statement;
});
}
private static BoundStatement BindExpression(Binder binder, ExpressionSyntax syntax, DiagnosticBag diagnostics, out ResultProperties resultProperties)
{
var flags = DkmClrCompilationResultFlags.None;
// In addition to C# expressions, the native EE also supports
// type names which are bound to a representation of the type
// (but not System.Type) that the user can expand to see the
// base type. Instead, we only allow valid C# expressions.
var expression = binder.BindValue(syntax, diagnostics, Binder.BindValueKind.RValue);
if (diagnostics.HasAnyErrors())
{
resultProperties = default(ResultProperties);
return null;
}
if (MayHaveSideEffectsVisitor.MayHaveSideEffects(expression))
{
flags |= DkmClrCompilationResultFlags.PotentialSideEffect;
}
var expressionType = expression.Type;
if ((object)expressionType == null)
{
expression = binder.CreateReturnConversion(
syntax,
diagnostics,
expression,
binder.Compilation.GetSpecialType(SpecialType.System_Object));
if (diagnostics.HasAnyErrors())
{
resultProperties = default(ResultProperties);
return null;
}
}
else if (expressionType.SpecialType == SpecialType.System_Void)
{
flags |= DkmClrCompilationResultFlags.ReadOnlyResult;
Debug.Assert(expression.ConstantValue == null);
resultProperties = expression.ExpressionSymbol.GetResultProperties(flags, isConstant: false);
return new BoundExpressionStatement(syntax, expression) { WasCompilerGenerated = true };
}
else if (expressionType.SpecialType == SpecialType.System_Boolean)
{
flags |= DkmClrCompilationResultFlags.BoolResult;
}
if (!IsAssignableExpression(binder, expression))
{
flags |= DkmClrCompilationResultFlags.ReadOnlyResult;
}
resultProperties = expression.ExpressionSymbol.GetResultProperties(flags, expression.ConstantValue != null);
return new BoundReturnStatement(syntax, expression) { WasCompilerGenerated = true };
}
private static BoundStatement BindStatement(Binder binder, StatementSyntax syntax, DiagnosticBag diagnostics, out ResultProperties properties)
{
properties = new ResultProperties(DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult);
return binder.BindStatement(syntax, diagnostics);
}
private static bool IsAssignableExpression(Binder binder, BoundExpression expression)
{
// NOTE: Surprisingly, binder.CheckValueKind will return true (!) for readonly fields
// in contexts where they cannot be assigned - it simply reports a diagnostic.
// Presumably, this is done to avoid producing a confusing error message about the
// field not being an lvalue.
var diagnostics = DiagnosticBag.GetInstance();
var result = binder.CheckValueKind(expression, Binder.BindValueKind.Assignment, diagnostics) &&
!diagnostics.HasAnyErrors();
diagnostics.Free();
return result;
}
private static BoundStatement BindAssignment(Binder binder, ExpressionSyntax syntax, DiagnosticBag diagnostics)
{
var expression = binder.BindValue(syntax, diagnostics, Binder.BindValueKind.RValue);
if (diagnostics.HasAnyErrors())
{
return null;
}
return new BoundExpressionStatement(expression.Syntax, expression) { WasCompilerGenerated = true };
}
private static Binder CreateBinderChain(
CSharpCompilation compilation,
PEModuleSymbol module,
NamespaceSymbol @namespace,
ImmutableArray<ImmutableArray<ImportRecord>> importRecordGroups,
MetadataDecoder metadataDecoder)
{
var stack = ArrayBuilder<string>.GetInstance();
while ((object)@namespace != null)
{
stack.Push(@namespace.Name);
@namespace = @namespace.ContainingNamespace;
}
var binder = (new BuckStopsHereBinder(compilation)).WithAdditionalFlags(
BinderFlags.SuppressObsoleteChecks |
BinderFlags.IgnoreAccessibility |
BinderFlags.UnsafeRegion |
BinderFlags.UncheckedRegion |
BinderFlags.AllowManagedAddressOf |
BinderFlags.AllowAwaitInUnsafeContext);
var hasImports = !importRecordGroups.IsDefaultOrEmpty;
var numImportStringGroups = hasImports ? importRecordGroups.Length : 0;
var currentStringGroup = numImportStringGroups - 1;
// PERF: We used to call compilation.GetCompilationNamespace on every iteration,
// but that involved walking up to the global namespace, which we have to do
// anyway. Instead, we'll inline the functionality into our own walk of the
// namespace chain.
@namespace = compilation.GlobalNamespace;
while (stack.Count > 0)
{
var namespaceName = stack.Pop();
if (namespaceName.Length > 0)
{
// We're re-getting the namespace, rather than using the one containing
// the current frame method, because we want the merged namespace.
@namespace = @namespace.GetNestedNamespace(namespaceName);
Debug.Assert((object)@namespace != null,
$"We worked backwards from symbols to names, but no symbol exists for name '{namespaceName}'");
}
else
{
Debug.Assert((object)@namespace == (object)compilation.GlobalNamespace);
}
Imports imports = null;
if (hasImports)
{
if (currentStringGroup < 0)
{
Debug.WriteLine($"No import string group for namespace '{@namespace}'");
break;
}
var importsBinder = new InContainerBinder(@namespace, binder);
imports = BuildImports(compilation, module, importRecordGroups[currentStringGroup], importsBinder, metadataDecoder);
currentStringGroup--;
}
binder = new InContainerBinder(@namespace, binder, imports);
}
stack.Free();
if (currentStringGroup >= 0)
{
// CONSIDER: We could lump these into the outermost namespace. It's probably not worthwhile since
// the usings are already for the wrong method.
Debug.WriteLine($"Found {currentStringGroup + 1} import string groups without corresponding namespaces");
}
return binder;
}
private static CSharpCompilation GetCompilationWithExternAliases(CSharpCompilation compilation, ImmutableArray<ExternAliasRecord> externAliasRecords)
{
if (externAliasRecords.IsDefaultOrEmpty)
{
return compilation.Clone();
}
var updatedReferences = ArrayBuilder<MetadataReference>.GetInstance();
var assembliesAndModulesBuilder = ArrayBuilder<Symbol>.GetInstance();
foreach (var reference in compilation.References)
{
updatedReferences.Add(reference);
assembliesAndModulesBuilder.Add(compilation.GetAssemblyOrModuleSymbol(reference));
}
Debug.Assert(assembliesAndModulesBuilder.Count == updatedReferences.Count);
var assembliesAndModules = assembliesAndModulesBuilder.ToImmutableAndFree();
foreach (var externAliasRecord in externAliasRecords)
{
int index = externAliasRecord.GetIndexOfTargetAssembly(assembliesAndModules, compilation.Options.AssemblyIdentityComparer);
if (index < 0)
{
Debug.WriteLine($"Unable to find corresponding assembly reference for extern alias '{externAliasRecord}'");
continue;
}
var externAlias = externAliasRecord.Alias;
var assemblyReference = updatedReferences[index];
var oldAliases = assemblyReference.Properties.Aliases;
var newAliases = oldAliases.IsEmpty
? ImmutableArray.Create(MetadataReferenceProperties.GlobalAlias, externAlias)
: oldAliases.Concat(ImmutableArray.Create(externAlias));
// NOTE: Dev12 didn't emit custom debug info about "global", so we don't have
// a good way to distinguish between a module aliased with both (e.g.) "X" and
// "global" and a module aliased with only "X". As in Dev12, we assume that
// "global" is a valid alias to remain at least as permissive as source.
// NOTE: In the event that this introduces ambiguities between two assemblies
// (e.g. because one was "global" in source and the other was "X"), it should be
// possible to disambiguate as long as each assembly has a distinct extern alias,
// not necessarily used in source.
Debug.Assert(newAliases.Contains(MetadataReferenceProperties.GlobalAlias));
// Replace the value in the map with the updated reference.
updatedReferences[index] = assemblyReference.WithAliases(newAliases);
}
compilation = compilation.WithReferences(updatedReferences);
updatedReferences.Free();
return compilation;
}
private static Binder ExtendBinderChain(
CSharpSyntaxNode syntax,
ImmutableArray<Alias> aliases,
EEMethodSymbol method,
Binder binder,
bool hasDisplayClassThis,
bool methodNotType)
{
var substitutedSourceMethod = GetSubstitutedSourceMethod(method.SubstitutedSourceMethod, hasDisplayClassThis);
var substitutedSourceType = substitutedSourceMethod.ContainingType;
var stack = ArrayBuilder<NamedTypeSymbol>.GetInstance();
for (var type = substitutedSourceType; (object)type != null; type = type.ContainingType)
{
stack.Add(type);
}
while (stack.Count > 0)
{
substitutedSourceType = stack.Pop();
binder = new InContainerBinder(substitutedSourceType, binder);
if (substitutedSourceType.Arity > 0)
{
binder = new WithTypeArgumentsBinder(substitutedSourceType.TypeArguments, binder);
}
}
stack.Free();
if (substitutedSourceMethod.Arity > 0)
{
binder = new WithTypeArgumentsBinder(substitutedSourceMethod.TypeArguments, binder);
}
if (methodNotType)
{
// Method locals and parameters shadow pseudo-variables.
var typeNameDecoder = new EETypeNameDecoder(binder.Compilation, (PEModuleSymbol)substitutedSourceMethod.ContainingModule);
binder = new PlaceholderLocalBinder(
syntax,
aliases,
method,
typeNameDecoder,
binder);
}
binder = new EEMethodBinder(method, substitutedSourceMethod, binder);
if (methodNotType)
{
binder = new SimpleLocalScopeBinder(method.LocalsForBinding, binder);
}
return binder;
}
private static Imports BuildImports(CSharpCompilation compilation, PEModuleSymbol module, ImmutableArray<ImportRecord> importRecords, InContainerBinder binder, MetadataDecoder metadataDecoder)
{
// We make a first pass to extract all of the extern aliases because other imports may depend on them.
var externsBuilder = ArrayBuilder<AliasAndExternAliasDirective>.GetInstance();
foreach (var importRecord in importRecords)
{
if (importRecord.TargetKind != ImportTargetKind.Assembly)
{
continue;
}
var alias = importRecord.Alias;
IdentifierNameSyntax aliasNameSyntax;
if (!TryParseIdentifierNameSyntax(alias, out aliasNameSyntax))
{
Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid extern alias '{alias}'");
continue;
}
var externAliasSyntax = SyntaxFactory.ExternAliasDirective(aliasNameSyntax.Identifier);
var aliasSymbol = new AliasSymbol(binder, externAliasSyntax); // Binder is only used to access compilation.
externsBuilder.Add(new AliasAndExternAliasDirective(aliasSymbol, externAliasDirective: null)); // We have one, but we pass null for consistency.
}
var externs = externsBuilder.ToImmutableAndFree();
if (externs.Any())
{
// NB: This binder (and corresponding Imports) is only used to bind the other imports.
// We'll merge the externs into a final Imports object and return that to be used in
// the actual binder chain.
binder = new InContainerBinder(
binder.Container,
binder,
Imports.FromCustomDebugInfo(binder.Compilation, new Dictionary<string, AliasAndUsingDirective>(), ImmutableArray<NamespaceOrTypeAndUsingDirective>.Empty, externs));
}
var usingAliases = new Dictionary<string, AliasAndUsingDirective>();
var usingsBuilder = ArrayBuilder<NamespaceOrTypeAndUsingDirective>.GetInstance();
foreach (var importRecord in importRecords)
{
switch (importRecord.TargetKind)
{
case ImportTargetKind.Type:
{
var portableImportRecord = importRecord as PortableImportRecord;
TypeSymbol typeSymbol = portableImportRecord != null
? portableImportRecord.GetTargetType(metadataDecoder)
: metadataDecoder.GetTypeSymbolForSerializedType(importRecord.TargetString);
Debug.Assert((object)typeSymbol != null);
if (typeSymbol.IsErrorType())
{
// Type is unrecognized. The import may have been
// valid in the original source but unnecessary.
continue; // Don't add anything for this import.
}
else if (importRecord.Alias == null && !typeSymbol.IsStatic)
{
// Only static types can be directly imported.
continue;
}
if (!TryAddImport(importRecord.Alias, typeSymbol, usingsBuilder, usingAliases, binder, importRecord))
{
continue;
}
break;
}
case ImportTargetKind.Namespace:
{
var namespaceName = importRecord.TargetString;
NameSyntax targetSyntax;
if (!SyntaxHelpers.TryParseDottedName(namespaceName, out targetSyntax))
{
// DevDiv #999086: Some previous version of VS apparently generated type aliases as "UA{alias} T{alias-qualified type name}".
// Neither Roslyn nor Dev12 parses such imports. However, Roslyn discards them, rather than interpreting them as "UA{alias}"
// (which will rarely work and never be correct).
Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid target '{importRecord.TargetString}'");
continue;
}
NamespaceSymbol namespaceSymbol;
var portableImportRecord = importRecord as PortableImportRecord;
if (portableImportRecord != null)
{
var targetAssembly = portableImportRecord.GetTargetAssembly<ModuleSymbol, AssemblySymbol>(module, module.Module);
if ((object)targetAssembly == null)
{
namespaceSymbol = BindNamespace(namespaceName, compilation.GlobalNamespace);
}
else if (targetAssembly.IsMissing)
{
Debug.WriteLine($"Import record '{importRecord}' has invalid assembly reference '{targetAssembly.Identity}'");
continue;
}
else
{
namespaceSymbol = BindNamespace(namespaceName, targetAssembly.GlobalNamespace);
}
}
else
{
var globalNamespace = compilation.GlobalNamespace;
var externAlias = ((NativeImportRecord)importRecord).ExternAlias;
if (externAlias != null)
{
IdentifierNameSyntax externAliasSyntax = null;
if (!TryParseIdentifierNameSyntax(externAlias, out externAliasSyntax))
{
Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid extern alias '{externAlias}'");
continue;
}
var unusedDiagnostics = DiagnosticBag.GetInstance();
var aliasSymbol = (AliasSymbol)binder.BindNamespaceAliasSymbol(externAliasSyntax, unusedDiagnostics);
unusedDiagnostics.Free();
if ((object)aliasSymbol == null)
{
Debug.WriteLine($"Import record '{importRecord}' requires unknown extern alias '{externAlias}'");
continue;
}
globalNamespace = (NamespaceSymbol)aliasSymbol.Target;
}
namespaceSymbol = BindNamespace(namespaceName, globalNamespace);
}
if ((object)namespaceSymbol == null)
{
// Namespace is unrecognized. The import may have been
// valid in the original source but unnecessary.
continue; // Don't add anything for this import.
}
if (!TryAddImport(importRecord.Alias, namespaceSymbol, usingsBuilder, usingAliases, binder, importRecord))
{
continue;
}
break;
}
case ImportTargetKind.Assembly:
{
// Handled in first pass (above).
break;
}
default:
{
throw ExceptionUtilities.UnexpectedValue(importRecord.TargetKind);
}
}
}
return Imports.FromCustomDebugInfo(binder.Compilation, usingAliases, usingsBuilder.ToImmutableAndFree(), externs);
}
private static NamespaceSymbol BindNamespace(string namespaceName, NamespaceSymbol globalNamespace)
{
var namespaceSymbol = globalNamespace;
foreach (var name in namespaceName.Split('.'))
{
var members = namespaceSymbol.GetMembers(name);
namespaceSymbol = members.Length == 1
? members[0] as NamespaceSymbol
: null;
if ((object)namespaceSymbol == null)
{
break;
}
}
return namespaceSymbol;
}
private static bool TryAddImport(
string alias,
NamespaceOrTypeSymbol targetSymbol,
ArrayBuilder<NamespaceOrTypeAndUsingDirective> usingsBuilder,
Dictionary<string, AliasAndUsingDirective> usingAliases,
InContainerBinder binder,
ImportRecord importRecord)
{
if (alias == null)
{
usingsBuilder.Add(new NamespaceOrTypeAndUsingDirective(targetSymbol, usingDirective: null));
}
else
{
IdentifierNameSyntax aliasSyntax;
if (!TryParseIdentifierNameSyntax(alias, out aliasSyntax))
{
Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid alias '{alias}'");
return false;
}
var aliasSymbol = AliasSymbol.CreateCustomDebugInfoAlias(targetSymbol, aliasSyntax.Identifier, binder);
usingAliases.Add(alias, new AliasAndUsingDirective(aliasSymbol, usingDirective: null));
}
return true;
}
private static bool TryParseIdentifierNameSyntax(string name, out IdentifierNameSyntax syntax)
{
Debug.Assert(name != null);
if (name == MetadataReferenceProperties.GlobalAlias)
{
syntax = SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword));
return true;
}
NameSyntax nameSyntax;
if (!SyntaxHelpers.TryParseDottedName(name, out nameSyntax) || nameSyntax.Kind() != SyntaxKind.IdentifierName)
{
syntax = null;
return false;
}
syntax = (IdentifierNameSyntax)nameSyntax;
return true;
}
internal CommonMessageProvider MessageProvider
{
get { return this.Compilation.MessageProvider; }
}
private static DkmClrCompilationResultFlags GetLocalResultFlags(LocalSymbol local)
{
// CONSIDER: We might want to prevent the user from modifying pinned locals -
// that's pretty dangerous.
return local.IsConst
? DkmClrCompilationResultFlags.ReadOnlyResult
: DkmClrCompilationResultFlags.None;
}
/// <summary>
/// Generate the set of locals to use for binding.
/// </summary>
private static ImmutableArray<LocalSymbol> GetLocalsForBinding(
ImmutableArray<LocalSymbol> locals,
ImmutableArray<string> displayClassVariableNamesInOrder,
ImmutableDictionary<string, DisplayClassVariable> displayClassVariables)
{
var builder = ArrayBuilder<LocalSymbol>.GetInstance();
foreach (var local in locals)
{
var name = local.Name;
if (name == null)
{
continue;
}
if (GeneratedNames.GetKind(name) != GeneratedNameKind.None)
{
continue;
}
// Although Roslyn doesn't name synthesized locals unless they are well-known to EE,
// Dev12 did so we need to skip them here.
if (GeneratedNames.IsSynthesizedLocalName(name))
{
continue;
}
builder.Add(local);
}
foreach (var variableName in displayClassVariableNamesInOrder)
{
var variable = displayClassVariables[variableName];
switch (variable.Kind)
{
case DisplayClassVariableKind.Local:
case DisplayClassVariableKind.Parameter:
builder.Add(new EEDisplayClassFieldLocalSymbol(variable));
break;
}
}
return builder.ToImmutableAndFree();
}
/// <summary>
/// Return a mapping of captured variables (parameters, locals, and
/// "this") to locals. The mapping is needed to expose the original
/// local identifiers (those from source) in the binder.
/// </summary>
private static void GetDisplayClassVariables(
MethodSymbol method,
ImmutableArray<LocalSymbol> locals,
InScopeHoistedLocals inScopeHoistedLocals,
out ImmutableArray<string> displayClassVariableNamesInOrder,
out ImmutableDictionary<string, DisplayClassVariable> displayClassVariables,
out ImmutableHashSet<string> hoistedParameterNames)
{
// Calculated the shortest paths from locals to instances of display
// classes. There should not be two instances of the same display
// class immediately within any particular method.
var displayClassTypes = PooledHashSet<NamedTypeSymbol>.GetInstance();
var displayClassInstances = ArrayBuilder<DisplayClassInstanceAndFields>.GetInstance();
// Add any display class instances from locals (these will contain any hoisted locals).
foreach (var local in locals)
{
var name = local.Name;
if ((name != null) && (GeneratedNames.GetKind(name) == GeneratedNameKind.DisplayClassLocalOrField))
{
var instance = new DisplayClassInstanceFromLocal((EELocalSymbol)local);
displayClassTypes.Add(instance.Type);
displayClassInstances.Add(new DisplayClassInstanceAndFields(instance));
}
}
foreach (var parameter in method.Parameters)
{
if (GeneratedNames.GetKind(parameter.Name) == GeneratedNameKind.TransparentIdentifier)
{
var instance = new DisplayClassInstanceFromParameter(parameter);
displayClassTypes.Add(instance.Type);
displayClassInstances.Add(new DisplayClassInstanceAndFields(instance));
}
}
var containingType = method.ContainingType;
bool isIteratorOrAsyncMethod = false;
if (IsDisplayClassType(containingType))
{
if (!method.IsStatic)
{
// Add "this" display class instance.
var instance = new DisplayClassInstanceFromParameter(method.ThisParameter);
displayClassTypes.Add(instance.Type);
displayClassInstances.Add(new DisplayClassInstanceAndFields(instance));
}
isIteratorOrAsyncMethod = GeneratedNames.GetKind(containingType.Name) == GeneratedNameKind.StateMachineType;
}
if (displayClassInstances.Any())
{
// Find any additional display class instances breadth first.
for (int depth = 0; GetDisplayClassInstances(displayClassTypes, displayClassInstances, depth) > 0; depth++)
{
}
// The locals are the set of all fields from the display classes.
var displayClassVariableNamesInOrderBuilder = ArrayBuilder<string>.GetInstance();
var displayClassVariablesBuilder = PooledDictionary<string, DisplayClassVariable>.GetInstance();
var parameterNames = PooledHashSet<string>.GetInstance();
if (isIteratorOrAsyncMethod)
{
Debug.Assert(IsDisplayClassType(containingType));
foreach (var field in containingType.GetMembers().OfType<FieldSymbol>())
{
// All iterator and async state machine fields (including hoisted locals) have mangled names, except
// for hoisted parameters (whose field names are always the same as the original source parameters).
var fieldName = field.Name;
if (GeneratedNames.GetKind(fieldName) == GeneratedNameKind.None)
{
parameterNames.Add(fieldName);
}
}
}
else
{
foreach (var p in method.Parameters)
{
parameterNames.Add(p.Name);
}
}
var pooledHoistedParameterNames = PooledHashSet<string>.GetInstance();
foreach (var instance in displayClassInstances)
{
GetDisplayClassVariables(
displayClassVariableNamesInOrderBuilder,
displayClassVariablesBuilder,
parameterNames,
inScopeHoistedLocals,
instance,
pooledHoistedParameterNames);
}
hoistedParameterNames = pooledHoistedParameterNames.ToImmutableHashSet<string>();
pooledHoistedParameterNames.Free();
parameterNames.Free();
displayClassVariableNamesInOrder = displayClassVariableNamesInOrderBuilder.ToImmutableAndFree();
displayClassVariables = displayClassVariablesBuilder.ToImmutableDictionary();
displayClassVariablesBuilder.Free();
}
else
{
hoistedParameterNames = ImmutableHashSet<string>.Empty;
displayClassVariableNamesInOrder = ImmutableArray<string>.Empty;
displayClassVariables = ImmutableDictionary<string, DisplayClassVariable>.Empty;
}
displayClassTypes.Free();
displayClassInstances.Free();
}
/// <summary>
/// Return the set of display class instances that can be reached
/// from the given local. A particular display class may be reachable
/// from multiple locals. In those cases, the instance from the
/// shortest path (fewest intermediate fields) is returned.
/// </summary>
private static int GetDisplayClassInstances(
HashSet<NamedTypeSymbol> displayClassTypes,
ArrayBuilder<DisplayClassInstanceAndFields> displayClassInstances,
int depth)
{
Debug.Assert(displayClassInstances.All(p => p.Depth <= depth));
var atDepth = ArrayBuilder<DisplayClassInstanceAndFields>.GetInstance();
atDepth.AddRange(displayClassInstances.Where(p => p.Depth == depth));
Debug.Assert(atDepth.Count > 0);
int n = 0;
foreach (var instance in atDepth)
{
n += GetDisplayClassInstances(displayClassTypes, displayClassInstances, instance);
}
atDepth.Free();
return n;
}
private static int GetDisplayClassInstances(
HashSet<NamedTypeSymbol> displayClassTypes,
ArrayBuilder<DisplayClassInstanceAndFields> displayClassInstances,
DisplayClassInstanceAndFields instance)
{
// Display class instance. The display class fields are variables.
int n = 0;
foreach (var member in instance.Type.GetMembers())
{
if (member.Kind != SymbolKind.Field)
{
continue;
}
var field = (FieldSymbol)member;
var fieldType = field.Type;
var fieldKind = GeneratedNames.GetKind(field.Name);
if (fieldKind == GeneratedNameKind.DisplayClassLocalOrField ||
fieldKind == GeneratedNameKind.TransparentIdentifier ||
IsTransparentIdentifierFieldInAnonymousType(field) ||
(fieldKind == GeneratedNameKind.ThisProxyField && GeneratedNames.GetKind(fieldType.Name) == GeneratedNameKind.LambdaDisplayClass)) // Async lambda case.
{
Debug.Assert(!field.IsStatic);
// A local that is itself a display class instance.
if (displayClassTypes.Add((NamedTypeSymbol)fieldType))
{
var other = instance.FromField(field);
displayClassInstances.Add(other);
n++;
}
}
}
return n;
}
private static bool IsTransparentIdentifierFieldInAnonymousType(FieldSymbol field)
{
string fieldName = field.Name;
if (GeneratedNames.GetKind(fieldName) != GeneratedNameKind.AnonymousTypeField)
{
return false;
}
GeneratedNameKind kind;
int openBracketOffset;
int closeBracketOffset;
if (!GeneratedNames.TryParseGeneratedName(fieldName, out kind, out openBracketOffset, out closeBracketOffset))
{
return false;
}
fieldName = fieldName.Substring(openBracketOffset + 1, closeBracketOffset - openBracketOffset - 1);
return GeneratedNames.GetKind(fieldName) == GeneratedNameKind.TransparentIdentifier;
}
private static void GetDisplayClassVariables(
ArrayBuilder<string> displayClassVariableNamesInOrderBuilder,
Dictionary<string, DisplayClassVariable> displayClassVariablesBuilder,
HashSet<string> parameterNames,
InScopeHoistedLocals inScopeHoistedLocals,
DisplayClassInstanceAndFields instance,
HashSet<string> hoistedParameterNames)
{
// Display class instance. The display class fields are variables.
foreach (var member in instance.Type.GetMembers())
{
if (member.Kind != SymbolKind.Field)
{
continue;
}
var field = (FieldSymbol)member;
var fieldName = field.Name;
REPARSE:
DisplayClassVariableKind variableKind;
string variableName;
GeneratedNameKind fieldKind;
int openBracketOffset;
int closeBracketOffset;
GeneratedNames.TryParseGeneratedName(fieldName, out fieldKind, out openBracketOffset, out closeBracketOffset);
switch (fieldKind)
{
case GeneratedNameKind.AnonymousTypeField:
Debug.Assert(fieldName == field.Name); // This only happens once.
fieldName = fieldName.Substring(openBracketOffset + 1, closeBracketOffset - openBracketOffset - 1);
goto REPARSE;
case GeneratedNameKind.TransparentIdentifier:
// A transparent identifier (field) in an anonymous type synthesized for a transparent identifier.
Debug.Assert(!field.IsStatic);
continue;
case GeneratedNameKind.DisplayClassLocalOrField:
// A local that is itself a display class instance.
Debug.Assert(!field.IsStatic);
continue;
case GeneratedNameKind.HoistedLocalField:
// Filter out hoisted locals that are known to be out-of-scope at the current IL offset.
// Hoisted locals with invalid indices will be included since more information is better
// than less in error scenarios.
if (!inScopeHoistedLocals.IsInScope(fieldName))
{
continue;
}
variableName = fieldName.Substring(openBracketOffset + 1, closeBracketOffset - openBracketOffset - 1);
variableKind = DisplayClassVariableKind.Local;
Debug.Assert(!field.IsStatic);
break;
case GeneratedNameKind.ThisProxyField:
// A reference to "this".
variableName = fieldName;
variableKind = DisplayClassVariableKind.This;
Debug.Assert(!field.IsStatic);
break;
case GeneratedNameKind.None:
// A reference to a parameter or local.
variableName = fieldName;
if (parameterNames.Contains(variableName))
{
variableKind = DisplayClassVariableKind.Parameter;
hoistedParameterNames.Add(variableName);
}
else
{
variableKind = DisplayClassVariableKind.Local;
}
Debug.Assert(!field.IsStatic);
break;
default:
continue;
}
if (displayClassVariablesBuilder.ContainsKey(variableName))
{
// Only expecting duplicates for async state machine
// fields (that should be at the top-level).
Debug.Assert(displayClassVariablesBuilder[variableName].DisplayClassFields.Count() == 1);
Debug.Assert(instance.Fields.Count() >= 1); // greater depth
Debug.Assert((variableKind == DisplayClassVariableKind.Parameter) ||
(variableKind == DisplayClassVariableKind.This));
}
else if (variableKind != DisplayClassVariableKind.This || GeneratedNames.GetKind(instance.Type.ContainingType.Name) != GeneratedNameKind.LambdaDisplayClass)
{
// In async lambdas, the hoisted "this" field in the state machine type will point to the display class instance, if there is one.
// In such cases, we want to add the display class "this" to the map instead (or nothing, if it lacks one).
displayClassVariableNamesInOrderBuilder.Add(variableName);
displayClassVariablesBuilder.Add(variableName, instance.ToVariable(variableName, variableKind, field));
}
}
}
private static bool IsDisplayClassType(NamedTypeSymbol type)
{
switch (GeneratedNames.GetKind(type.Name))
{
case GeneratedNameKind.LambdaDisplayClass:
case GeneratedNameKind.StateMachineType:
return true;
default:
return false;
}
}
private static NamedTypeSymbol GetNonDisplayClassContainer(NamedTypeSymbol type)
{
// 1) Display class and state machine types are always nested within the types
// that use them (so that they can access private members of those types).
// 2) The native compiler used to produce nested display classes for nested lambdas,
// so we may have to walk out more than one level.
while (IsDisplayClassType(type))
{
type = type.ContainingType;
}
Debug.Assert((object)type != null);
return type;
}
/// <summary>
/// Identifies the method in which binding should occur.
/// </summary>
/// <param name="candidateSubstitutedSourceMethod">
/// The symbol of the method that is currently on top of the callstack, with
/// EE type parameters substituted in place of the original type parameters.
/// </param>
/// <param name="hasDisplayClassThis">
/// True if "this" is available via a display class in the current context.
/// </param>
/// <returns>
/// If <paramref name="candidateSubstitutedSourceMethod"/> is compiler-generated,
/// then we will attempt to determine which user-defined method caused it to be
/// generated. For example, if <paramref name="candidateSubstitutedSourceMethod"/>
/// is a state machine MoveNext method, then we will try to find the iterator or
/// async method for which it was generated. If we are able to find the original
/// method, then we will substitute in the EE type parameters. Otherwise, we will
/// return <paramref name="candidateSubstitutedSourceMethod"/>.
/// </returns>
/// <remarks>
/// In the event that the original method is overloaded, we may not be able to determine
/// which overload actually corresponds to the state machine. In particular, we do not
/// have information about the signature of the original method (i.e. number of parameters,
/// parameter types and ref-kinds, return type). However, we conjecture that this
/// level of uncertainty is acceptable, since parameters are managed by a separate binder
/// in the synthesized binder chain and we have enough information to check the other method
/// properties that are used during binding (e.g. static-ness, generic arity, type parameter
/// constraints).
/// </remarks>
internal static MethodSymbol GetSubstitutedSourceMethod(
MethodSymbol candidateSubstitutedSourceMethod,
bool hasDisplayClassThis)
{
var candidateSubstitutedSourceType = candidateSubstitutedSourceMethod.ContainingType;
string desiredMethodName;
if (GeneratedNames.TryParseSourceMethodNameFromGeneratedName(candidateSubstitutedSourceType.Name, GeneratedNameKind.StateMachineType, out desiredMethodName) ||
GeneratedNames.TryParseSourceMethodNameFromGeneratedName(candidateSubstitutedSourceMethod.Name, GeneratedNameKind.LambdaMethod, out desiredMethodName))
{
// We could be in the MoveNext method of an async lambda.
string tempMethodName;
if (GeneratedNames.TryParseSourceMethodNameFromGeneratedName(desiredMethodName, GeneratedNameKind.LambdaMethod, out tempMethodName))
{
desiredMethodName = tempMethodName;
var containing = candidateSubstitutedSourceType.ContainingType;
Debug.Assert((object)containing != null);
if (GeneratedNames.GetKind(containing.Name) == GeneratedNameKind.LambdaDisplayClass)
{
candidateSubstitutedSourceType = containing;
hasDisplayClassThis = candidateSubstitutedSourceType.MemberNames.Select(GeneratedNames.GetKind).Contains(GeneratedNameKind.ThisProxyField);
}
}
var desiredTypeParameters = candidateSubstitutedSourceType.OriginalDefinition.TypeParameters;
// We need to use a ThreeState, rather than a bool, because we can't distinguish between
// a roslyn lambda that only captures "this" and a dev12 lambda that captures nothing
// (neither introduces a display class). This is unnecessary in the state machine case,
// because then "this" is hoisted unconditionally.
var isDesiredMethodStatic = hasDisplayClassThis
? ThreeState.False
: (GeneratedNames.GetKind(candidateSubstitutedSourceType.Name) == GeneratedNameKind.StateMachineType)
? ThreeState.True
: ThreeState.Unknown;
// Type containing the original iterator, async, or lambda-containing method.
var substitutedSourceType = GetNonDisplayClassContainer(candidateSubstitutedSourceType);
foreach (var candidateMethod in substitutedSourceType.GetMembers().OfType<MethodSymbol>())
{
if (IsViableSourceMethod(candidateMethod, desiredMethodName, desiredTypeParameters, isDesiredMethodStatic))
{
return desiredTypeParameters.Length == 0
? candidateMethod
: candidateMethod.Construct(candidateSubstitutedSourceType.TypeArguments);
}
}
Debug.Assert(false, "Why didn't we find a substituted source method for " + candidateSubstitutedSourceMethod + "?");
}
return candidateSubstitutedSourceMethod;
}
private static bool IsViableSourceMethod(MethodSymbol candidateMethod, string desiredMethodName, ImmutableArray<TypeParameterSymbol> desiredTypeParameters, ThreeState isDesiredMethodStatic)
{
return
!candidateMethod.IsAbstract &&
(isDesiredMethodStatic == ThreeState.Unknown || isDesiredMethodStatic.Value() == candidateMethod.IsStatic) &&
candidateMethod.Name == desiredMethodName &&
HaveSameConstraints(candidateMethod.TypeParameters, desiredTypeParameters);
}
private static bool HaveSameConstraints(ImmutableArray<TypeParameterSymbol> candidateTypeParameters, ImmutableArray<TypeParameterSymbol> desiredTypeParameters)
{
int arity = candidateTypeParameters.Length;
if (arity != desiredTypeParameters.Length)
{
return false;
}
else if (arity == 0)
{
return true;
}
var indexedTypeParameters = IndexedTypeParameterSymbol.Take(arity);
var candidateTypeMap = new TypeMap(candidateTypeParameters, indexedTypeParameters, allowAlpha: true);
var desiredTypeMap = new TypeMap(desiredTypeParameters, indexedTypeParameters, allowAlpha: true);
return MemberSignatureComparer.HaveSameConstraints(candidateTypeParameters, candidateTypeMap, desiredTypeParameters, desiredTypeMap);
}
private struct DisplayClassInstanceAndFields
{
internal readonly DisplayClassInstance Instance;
internal readonly ConsList<FieldSymbol> Fields;
internal DisplayClassInstanceAndFields(DisplayClassInstance instance) :
this(instance, ConsList<FieldSymbol>.Empty)
{
Debug.Assert(IsDisplayClassType(instance.Type) ||
GeneratedNames.GetKind(instance.Type.Name) == GeneratedNameKind.AnonymousType);
}
private DisplayClassInstanceAndFields(DisplayClassInstance instance, ConsList<FieldSymbol> fields)
{
this.Instance = instance;
this.Fields = fields;
}
internal NamedTypeSymbol Type
{
get { return this.Fields.Any() ? (NamedTypeSymbol)this.Fields.Head.Type : this.Instance.Type; }
}
internal int Depth
{
get { return this.Fields.Count(); }
}
internal DisplayClassInstanceAndFields FromField(FieldSymbol field)
{
Debug.Assert(IsDisplayClassType((NamedTypeSymbol)field.Type) ||
GeneratedNames.GetKind(field.Type.Name) == GeneratedNameKind.AnonymousType);
return new DisplayClassInstanceAndFields(this.Instance, this.Fields.Prepend(field));
}
internal DisplayClassVariable ToVariable(string name, DisplayClassVariableKind kind, FieldSymbol field)
{
return new DisplayClassVariable(name, kind, this.Instance, this.Fields.Prepend(field));
}
}
}
}
| |
/*(c) Copyright 2012, VersionOne, Inc. All rights reserved. (c)*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.DirectoryServices;
namespace VersionOne.IIS {
public abstract class IISObject {
private static IDictionary<string, IISObject> _map = new Dictionary<string, IISObject>();
private string _path;
protected string Path {
get { return _path; }
}
public string Name {
get {
string[] parts = _path.Split('/');
return parts[parts.Length - 1];
}
}
private IDictionary _properties = new Hashtable();
private IDictionary Properties {
get { return _properties; }
}
private bool _haschanged;
public bool HasChanged {
get { return _haschanged; }
}
public IISObject(string path) {
_path = path;
_map[path] = this;
}
public void AcceptChanges() {
if (HasChanged) {
using (DirectoryEntry entry = new DirectoryEntry(_path)) {
foreach (DictionaryEntry propentry in Properties)
entry.InvokeSet((string) propentry.Key, propentry.Value);
entry.CommitChanges();
}
}
}
public void RejectChanges() {
Properties.Clear();
_haschanged = false;
}
protected T Create<T>(string name, string type) where T : IISObject {
using (DirectoryEntry entry = new DirectoryEntry(_path))
using (DirectoryEntry e = entry.Children.Add(name, type))
e.CommitChanges();
return GetChild<T>(name);
}
protected T GetProperty<T>(string name) {
object value = Properties[name];
if (value == null) {
using (DirectoryEntry entry = new DirectoryEntry(_path))
value = Properties[name] = entry.InvokeGet(name);
}
return (T) value;
}
protected void SetProperty<T>(string name, T value) {
T v = GetProperty<T>(name);
if (!v.Equals(value)) {
Properties[name] = value;
_haschanged = true;
}
}
protected void Execute(string method) {
using (DirectoryEntry entry = new DirectoryEntry(_path))
entry.Invoke(method, null);
}
protected object Execute(string method, params object[] args) {
using (DirectoryEntry entry = new DirectoryEntry(_path))
return entry.Invoke(method, args);
}
protected T GetChild<T>(string name) where T : IISObject {
string fullpath = Path + "/" + name;
if (DirectoryEntry.Exists(fullpath))
return GetNode<T>(fullpath);
return null;
}
protected T GetParent<T>() where T : IISObject {
string[] parts = _path.Split('/');
string path = string.Join("/", parts, 0, parts.Length - 1);
return GetNode<T>(path);
}
private static T GetNode<T>(string fullpath) where T : IISObject {
IISObject v;
if (!_map.TryGetValue(fullpath, out v))
v = (T) Activator.CreateInstance(typeof (T), new object[] {fullpath});
return (T) v;
}
protected IDictionary<string, T> GetChildren<T>(string type) where T : IISObject {
IDictionary<string, T> results = new Dictionary<string, T>();
using (DirectoryEntry entry = new DirectoryEntry(_path)) {
foreach (DirectoryEntry child in entry.Children)
using (child)
if (child.SchemaClassName == type)
results.Add(child.Name, GetChild<T>(child.Name));
}
return results;
}
}
public class IISComputer : IISObject {
private IISWebService _webservice;
public IISWebService WebService {
get {
if (_webservice == null)
_webservice = GetChild<IISWebService>("W3SVC");
return _webservice;
}
}
public IISComputer() : this("localhost") {}
public IISComputer(string servername) : base("IIS://" + servername) {}
}
public class IISWebService : IISObject {
public IISWebService(string path) : base(path) {}
public IISComputer Computer {
get { return GetParent<IISComputer>(); }
}
private IDictionary<string, IISWebServer> _webservers;
private IDictionary<string, IISWebServer> WebServersDict {
get {
if (_webservers == null)
_webservers = GetChildren<IISWebServer>("IIsWebServer");
return _webservers;
}
}
public ICollection<IISWebServer> WebServers {
get { return WebServersDict.Values; }
}
private IISApplicationPools _apppools;
public IISApplicationPools AppPools {
get {
if (_apppools == null)
_apppools = GetChild<IISApplicationPools>("AppPools");
return _apppools;
}
}
}
public class IISApplicationPools : IISObject {
public IISApplicationPools(string path) : base(path) {}
public IISWebService WebService {
get { return GetParent<IISWebService>(); }
}
private IDictionary<string, IISApplicationPool> _apppools;
private IDictionary<string, IISApplicationPool> AppPoolsDict {
get {
if (_apppools == null)
_apppools = GetChildren<IISApplicationPool>("IIsApplicationPool");
return _apppools;
}
}
public ICollection<IISApplicationPool> AppPools {
get { return AppPoolsDict.Values; }
}
public IISApplicationPool GetApplicationPool(string name) {
IISApplicationPool pool;
AppPoolsDict.TryGetValue(name, out pool);
return pool;
}
public IISApplicationPool AddApplicationPool(string name) {
IISApplicationPool apppool = GetApplicationPool(name);
if (apppool == null) {
apppool = Create<IISApplicationPool>(name, "IIsApplicationPool");
AppPoolsDict.Add(name, apppool);
}
return apppool;
}
}
public class IISApplicationPool : IISObject {
public IISApplicationPool(string path) : base(path) {}
public IISApplicationPools AppPools {
get { return GetParent<IISApplicationPools>(); }
}
public int PeriodicRestartMemory {
get { return GetProperty<int>("PeriodicRestartMemory"); }
set { SetProperty("PeriodicRestartMemory", value); }
}
public int PeriodicRestartPrivateMemory {
get { return GetProperty<int>("PeriodicRestartPrivateMemory"); }
set { SetProperty("PeriodicRestartPrivateMemory", value); }
}
public void Start() {
Execute("Start");
}
public void Stop() {
Execute("Stop");
}
public void Recycle() {
Execute("Recycle");
}
}
public class IISWebServer : IISObject {
public IISWebServer(string path) : base(path) {}
public IISWebService WebService {
get { return GetParent<IISWebService>(); }
}
private IDictionary<string, IISRootWebVirtualDir> _virtualdirs;
private IDictionary<string, IISRootWebVirtualDir> VirtualDirsDict {
get {
if (_virtualdirs == null)
_virtualdirs = GetChildren<IISRootWebVirtualDir>("IIsWebVirtualDir");
return _virtualdirs;
}
}
public string ServerBindings {
get { return GetProperty<string>("ServerBindings"); }
}
public string HostName {
get {
string[] parts = ServerBindings.Split(':');
string host = "localhost";
if (parts[2] != string.Empty)
host = parts[2];
return host;
}
}
public int Port {
get {
string[] parts = ServerBindings.Split(':');
string port = "80";
if (parts[1] != string.Empty)
port = parts[1];
return int.Parse(port);
}
}
public string Url {
get {
string url = "http://" + HostName;
if (Port != 80)
url += ":" + Port;
return url;
}
}
public ICollection<IISRootWebVirtualDir> VirtualDirs {
get { return VirtualDirsDict.Values; }
}
}
public class IISWebVirtualDir : IISObject {
public IISWebVirtualDir(string path) : base(path) {}
public IISWebVirtualDir ParentDir {
get { return GetParent<IISWebVirtualDir>(); }
}
public virtual bool IsRoot {
get { return false; }
}
private IDictionary<string, IISWebVirtualDir> _virtualdirs;
private IDictionary<string, IISWebVirtualDir> VirtualDirsDict {
get {
if (_virtualdirs == null)
_virtualdirs = GetChildren<IISWebVirtualDir>("IIsWebVirtualDir");
return _virtualdirs;
}
}
public ICollection<IISWebVirtualDir> VirtualDirs {
get { return VirtualDirsDict.Values; }
}
public string AppPoolID {
get { return GetProperty<string>("AppPoolID"); }
set { SetProperty("AppPoolID", value); }
}
public IISWebVirtualDir GetVirtualDir(string instancename) {
IISWebVirtualDir instance;
if (VirtualDirsDict.TryGetValue(instancename, out instance))
return instance;
return null;
}
}
public class IISRootWebVirtualDir : IISWebVirtualDir {
public override bool IsRoot {
get { return true; }
}
public IISWebServer WebServer {
get { return GetParent<IISWebServer>(); }
}
public IISRootWebVirtualDir(string path) : base(path) {}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Reflection;
using System.Reflection.Metadata;
using System.Threading;
using Internal.TypeSystem;
namespace Internal.TypeSystem.Ecma
{
public sealed class EcmaMethod : MethodDesc, EcmaModule.IEntityHandleObject
{
private static class MethodFlags
{
public const int BasicMetadataCache = 0x0001;
public const int Virtual = 0x0002;
public const int NewSlot = 0x0004;
public const int Abstract = 0x0008;
public const int Final = 0x0010;
public const int NoInlining = 0x0020;
public const int AggressiveInlining = 0x0040;
public const int RuntimeImplemented = 0x0080;
public const int AttributeMetadataCache = 0x0100;
public const int Intrinsic = 0x0200;
public const int InternalCall = 0x0400;
};
private EcmaType _type;
private MethodDefinitionHandle _handle;
// Cached values
private ThreadSafeFlags _methodFlags;
private MethodSignature _signature;
private string _name;
private TypeDesc[] _genericParameters; // TODO: Optional field?
internal EcmaMethod(EcmaType type, MethodDefinitionHandle handle)
{
_type = type;
_handle = handle;
#if DEBUG
// Initialize name eagerly in debug builds for convenience
this.ToString();
#endif
}
EntityHandle EcmaModule.IEntityHandleObject.Handle
{
get
{
return _handle;
}
}
public override TypeSystemContext Context
{
get
{
return _type.Module.Context;
}
}
public override TypeDesc OwningType
{
get
{
return _type;
}
}
private MethodSignature InitializeSignature()
{
var metadataReader = MetadataReader;
BlobReader signatureReader = metadataReader.GetBlobReader(metadataReader.GetMethodDefinition(_handle).Signature);
EcmaSignatureParser parser = new EcmaSignatureParser(Module, signatureReader);
var signature = parser.ParseMethodSignature();
return (_signature = signature);
}
public override MethodSignature Signature
{
get
{
if (_signature == null)
return InitializeSignature();
return _signature;
}
}
public EcmaModule Module
{
get
{
return _type.EcmaModule;
}
}
public MetadataReader MetadataReader
{
get
{
return _type.MetadataReader;
}
}
public MethodDefinitionHandle Handle
{
get
{
return _handle;
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private int InitializeMethodFlags(int mask)
{
int flags = 0;
if ((mask & MethodFlags.BasicMetadataCache) != 0)
{
var methodAttributes = Attributes;
var methodImplAttributes = ImplAttributes;
if ((methodAttributes & MethodAttributes.Virtual) != 0)
flags |= MethodFlags.Virtual;
if ((methodAttributes & MethodAttributes.NewSlot) != 0)
flags |= MethodFlags.NewSlot;
if ((methodAttributes & MethodAttributes.Abstract) != 0)
flags |= MethodFlags.Abstract;
if ((methodAttributes & MethodAttributes.Final) != 0)
flags |= MethodFlags.Final;
if ((methodImplAttributes & MethodImplAttributes.NoInlining) != 0)
flags |= MethodFlags.NoInlining;
if ((methodImplAttributes & MethodImplAttributes.AggressiveInlining) != 0)
flags |= MethodFlags.AggressiveInlining;
if ((methodImplAttributes & MethodImplAttributes.Runtime) != 0)
flags |= MethodFlags.RuntimeImplemented;
if ((methodImplAttributes & MethodImplAttributes.InternalCall) != 0)
flags |= MethodFlags.InternalCall;
flags |= MethodFlags.BasicMetadataCache;
}
// Fetching custom attribute based properties is more expensive, so keep that under
// a separate cache that might not be accessed very frequently.
if ((mask & MethodFlags.AttributeMetadataCache) != 0)
{
var metadataReader = this.MetadataReader;
var methodDefinition = metadataReader.GetMethodDefinition(_handle);
foreach (var attributeHandle in methodDefinition.GetCustomAttributes())
{
StringHandle namespaceHandle, nameHandle;
if (!metadataReader.GetAttributeNamespaceAndName(attributeHandle, out namespaceHandle, out nameHandle))
continue;
if (metadataReader.StringComparer.Equals(namespaceHandle, "System.Runtime.CompilerServices"))
{
if (metadataReader.StringComparer.Equals(nameHandle, "IntrinsicAttribute"))
{
flags |= MethodFlags.Intrinsic;
}
}
}
flags |= MethodFlags.AttributeMetadataCache;
}
Debug.Assert((flags & mask) != 0);
_methodFlags.AddFlags(flags);
return flags & mask;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private int GetMethodFlags(int mask)
{
int flags = _methodFlags.Value & mask;
if (flags != 0)
return flags;
return InitializeMethodFlags(mask);
}
public override bool IsVirtual
{
get
{
return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.Virtual) & MethodFlags.Virtual) != 0;
}
}
public override bool IsNewSlot
{
get
{
return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.NewSlot) & MethodFlags.NewSlot) != 0;
}
}
public override bool IsAbstract
{
get
{
return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.Abstract) & MethodFlags.Abstract) != 0;
}
}
public override bool IsFinal
{
get
{
return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.Final) & MethodFlags.Final) != 0;
}
}
public override bool IsNoInlining
{
get
{
return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.NoInlining) & MethodFlags.NoInlining) != 0;
}
}
public override bool IsAggressiveInlining
{
get
{
return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.AggressiveInlining) & MethodFlags.AggressiveInlining) != 0;
}
}
public override bool IsRuntimeImplemented
{
get
{
return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.RuntimeImplemented) & MethodFlags.RuntimeImplemented) != 0;
}
}
public override bool IsIntrinsic
{
get
{
return (GetMethodFlags(MethodFlags.AttributeMetadataCache | MethodFlags.Intrinsic) & MethodFlags.Intrinsic) != 0;
}
}
public override bool IsInternalCall
{
get
{
return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.InternalCall) & MethodFlags.InternalCall) != 0;
}
}
public MethodAttributes Attributes
{
get
{
return MetadataReader.GetMethodDefinition(_handle).Attributes;
}
}
public MethodImplAttributes ImplAttributes
{
get
{
return MetadataReader.GetMethodDefinition(_handle).ImplAttributes;
}
}
private string InitializeName()
{
var metadataReader = MetadataReader;
var name = metadataReader.GetString(metadataReader.GetMethodDefinition(_handle).Name);
return (_name = name);
}
public override string Name
{
get
{
if (_name == null)
return InitializeName();
return _name;
}
}
private void ComputeGenericParameters()
{
var genericParameterHandles = MetadataReader.GetMethodDefinition(_handle).GetGenericParameters();
int count = genericParameterHandles.Count;
if (count > 0)
{
TypeDesc[] genericParameters = new TypeDesc[count];
int i = 0;
foreach (var genericParameterHandle in genericParameterHandles)
{
genericParameters[i++] = new EcmaGenericParameter(Module, genericParameterHandle);
}
Interlocked.CompareExchange(ref _genericParameters, genericParameters, null);
}
else
{
_genericParameters = TypeDesc.EmptyTypes;
}
}
public override Instantiation Instantiation
{
get
{
if (_genericParameters == null)
ComputeGenericParameters();
return new Instantiation(_genericParameters);
}
}
public override bool HasCustomAttribute(string attributeNamespace, string attributeName)
{
return MetadataReader.HasCustomAttribute(MetadataReader.GetMethodDefinition(_handle).GetCustomAttributes(),
attributeNamespace, attributeName);
}
public override string ToString()
{
return _type.ToString() + "." + Name;
}
public override bool IsPInvoke
{
get
{
return (((int)Attributes & (int)MethodAttributes.PinvokeImpl) != 0);
}
}
public override PInvokeMetadata GetPInvokeMethodMetadata()
{
if (!IsPInvoke)
return default(PInvokeMetadata);
MetadataReader metadataReader = MetadataReader;
MethodImport import = metadataReader.GetMethodDefinition(_handle).GetImport();
string name = metadataReader.GetString(import.Name);
// Spot check the enums match
Debug.Assert((int)MethodImportAttributes.CallingConventionStdCall == (int)PInvokeAttributes.CallingConventionStdCall);
Debug.Assert((int)MethodImportAttributes.CharSetAuto == (int)PInvokeAttributes.CharSetAuto);
Debug.Assert((int)MethodImportAttributes.CharSetUnicode == (int)PInvokeAttributes.CharSetUnicode);
return new PInvokeMetadata(name, (PInvokeAttributes)import.Attributes);
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// PublicKeyResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
namespace Twilio.Rest.Accounts.V1.Credential
{
public class PublicKeyResource : Resource
{
private static Request BuildReadRequest(ReadPublicKeyOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Accounts,
"/v1/Credentials/PublicKeys",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Retrieves a collection of Public Key Credentials belonging to the account used to make the request
/// </summary>
/// <param name="options"> Read PublicKey parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of PublicKey </returns>
public static ResourceSet<PublicKeyResource> Read(ReadPublicKeyOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<PublicKeyResource>.FromJson("credentials", response.Content);
return new ResourceSet<PublicKeyResource>(page, options, client);
}
#if !NET35
/// <summary>
/// Retrieves a collection of Public Key Credentials belonging to the account used to make the request
/// </summary>
/// <param name="options"> Read PublicKey parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of PublicKey </returns>
public static async System.Threading.Tasks.Task<ResourceSet<PublicKeyResource>> ReadAsync(ReadPublicKeyOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<PublicKeyResource>.FromJson("credentials", response.Content);
return new ResourceSet<PublicKeyResource>(page, options, client);
}
#endif
/// <summary>
/// Retrieves a collection of Public Key Credentials belonging to the account used to make the request
/// </summary>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of PublicKey </returns>
public static ResourceSet<PublicKeyResource> Read(int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadPublicKeyOptions(){PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// Retrieves a collection of Public Key Credentials belonging to the account used to make the request
/// </summary>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of PublicKey </returns>
public static async System.Threading.Tasks.Task<ResourceSet<PublicKeyResource>> ReadAsync(int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadPublicKeyOptions(){PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<PublicKeyResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<PublicKeyResource>.FromJson("credentials", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<PublicKeyResource> NextPage(Page<PublicKeyResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.Accounts)
);
var response = client.Request(request);
return Page<PublicKeyResource>.FromJson("credentials", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<PublicKeyResource> PreviousPage(Page<PublicKeyResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.Accounts)
);
var response = client.Request(request);
return Page<PublicKeyResource>.FromJson("credentials", response.Content);
}
private static Request BuildCreateRequest(CreatePublicKeyOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Accounts,
"/v1/Credentials/PublicKeys",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Create a new Public Key Credential
/// </summary>
/// <param name="options"> Create PublicKey parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of PublicKey </returns>
public static PublicKeyResource Create(CreatePublicKeyOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// Create a new Public Key Credential
/// </summary>
/// <param name="options"> Create PublicKey parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of PublicKey </returns>
public static async System.Threading.Tasks.Task<PublicKeyResource> CreateAsync(CreatePublicKeyOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// Create a new Public Key Credential
/// </summary>
/// <param name="publicKey"> A URL encoded representation of the public key </param>
/// <param name="friendlyName"> A string to describe the resource </param>
/// <param name="accountSid"> The Subaccount this Credential should be associated with. </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of PublicKey </returns>
public static PublicKeyResource Create(string publicKey,
string friendlyName = null,
string accountSid = null,
ITwilioRestClient client = null)
{
var options = new CreatePublicKeyOptions(publicKey){FriendlyName = friendlyName, AccountSid = accountSid};
return Create(options, client);
}
#if !NET35
/// <summary>
/// Create a new Public Key Credential
/// </summary>
/// <param name="publicKey"> A URL encoded representation of the public key </param>
/// <param name="friendlyName"> A string to describe the resource </param>
/// <param name="accountSid"> The Subaccount this Credential should be associated with. </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of PublicKey </returns>
public static async System.Threading.Tasks.Task<PublicKeyResource> CreateAsync(string publicKey,
string friendlyName = null,
string accountSid = null,
ITwilioRestClient client = null)
{
var options = new CreatePublicKeyOptions(publicKey){FriendlyName = friendlyName, AccountSid = accountSid};
return await CreateAsync(options, client);
}
#endif
private static Request BuildFetchRequest(FetchPublicKeyOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Accounts,
"/v1/Credentials/PublicKeys/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Fetch the public key specified by the provided Credential Sid
/// </summary>
/// <param name="options"> Fetch PublicKey parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of PublicKey </returns>
public static PublicKeyResource Fetch(FetchPublicKeyOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// Fetch the public key specified by the provided Credential Sid
/// </summary>
/// <param name="options"> Fetch PublicKey parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of PublicKey </returns>
public static async System.Threading.Tasks.Task<PublicKeyResource> FetchAsync(FetchPublicKeyOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// Fetch the public key specified by the provided Credential Sid
/// </summary>
/// <param name="pathSid"> The unique string that identifies the resource </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of PublicKey </returns>
public static PublicKeyResource Fetch(string pathSid, ITwilioRestClient client = null)
{
var options = new FetchPublicKeyOptions(pathSid);
return Fetch(options, client);
}
#if !NET35
/// <summary>
/// Fetch the public key specified by the provided Credential Sid
/// </summary>
/// <param name="pathSid"> The unique string that identifies the resource </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of PublicKey </returns>
public static async System.Threading.Tasks.Task<PublicKeyResource> FetchAsync(string pathSid,
ITwilioRestClient client = null)
{
var options = new FetchPublicKeyOptions(pathSid);
return await FetchAsync(options, client);
}
#endif
private static Request BuildUpdateRequest(UpdatePublicKeyOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Accounts,
"/v1/Credentials/PublicKeys/" + options.PathSid + "",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Modify the properties of a given Account
/// </summary>
/// <param name="options"> Update PublicKey parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of PublicKey </returns>
public static PublicKeyResource Update(UpdatePublicKeyOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// Modify the properties of a given Account
/// </summary>
/// <param name="options"> Update PublicKey parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of PublicKey </returns>
public static async System.Threading.Tasks.Task<PublicKeyResource> UpdateAsync(UpdatePublicKeyOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// Modify the properties of a given Account
/// </summary>
/// <param name="pathSid"> The unique string that identifies the resource </param>
/// <param name="friendlyName"> A string to describe the resource </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of PublicKey </returns>
public static PublicKeyResource Update(string pathSid, string friendlyName = null, ITwilioRestClient client = null)
{
var options = new UpdatePublicKeyOptions(pathSid){FriendlyName = friendlyName};
return Update(options, client);
}
#if !NET35
/// <summary>
/// Modify the properties of a given Account
/// </summary>
/// <param name="pathSid"> The unique string that identifies the resource </param>
/// <param name="friendlyName"> A string to describe the resource </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of PublicKey </returns>
public static async System.Threading.Tasks.Task<PublicKeyResource> UpdateAsync(string pathSid,
string friendlyName = null,
ITwilioRestClient client = null)
{
var options = new UpdatePublicKeyOptions(pathSid){FriendlyName = friendlyName};
return await UpdateAsync(options, client);
}
#endif
private static Request BuildDeleteRequest(DeletePublicKeyOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Delete,
Rest.Domain.Accounts,
"/v1/Credentials/PublicKeys/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Delete a Credential from your account
/// </summary>
/// <param name="options"> Delete PublicKey parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of PublicKey </returns>
public static bool Delete(DeletePublicKeyOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#if !NET35
/// <summary>
/// Delete a Credential from your account
/// </summary>
/// <param name="options"> Delete PublicKey parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of PublicKey </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeletePublicKeyOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#endif
/// <summary>
/// Delete a Credential from your account
/// </summary>
/// <param name="pathSid"> The unique string that identifies the resource </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of PublicKey </returns>
public static bool Delete(string pathSid, ITwilioRestClient client = null)
{
var options = new DeletePublicKeyOptions(pathSid);
return Delete(options, client);
}
#if !NET35
/// <summary>
/// Delete a Credential from your account
/// </summary>
/// <param name="pathSid"> The unique string that identifies the resource </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of PublicKey </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathSid, ITwilioRestClient client = null)
{
var options = new DeletePublicKeyOptions(pathSid);
return await DeleteAsync(options, client);
}
#endif
/// <summary>
/// Converts a JSON string into a PublicKeyResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> PublicKeyResource object represented by the provided JSON </returns>
public static PublicKeyResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<PublicKeyResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The unique string that identifies the resource
/// </summary>
[JsonProperty("sid")]
public string Sid { get; private set; }
/// <summary>
/// The SID of the Account that created the Credential that the PublicKey resource belongs to
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The string that you assigned to describe the resource
/// </summary>
[JsonProperty("friendly_name")]
public string FriendlyName { get; private set; }
/// <summary>
/// The RFC 2822 date and time in GMT when the resource was created
/// </summary>
[JsonProperty("date_created")]
public DateTime? DateCreated { get; private set; }
/// <summary>
/// The RFC 2822 date and time in GMT when the resource was last updated
/// </summary>
[JsonProperty("date_updated")]
public DateTime? DateUpdated { get; private set; }
/// <summary>
/// The URI for this resource, relative to `https://accounts.twilio.com`
/// </summary>
[JsonProperty("url")]
public Uri Url { get; private set; }
private PublicKeyResource()
{
}
}
}
| |
// Copyright 2018 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 Google.Api.Gax;
using System;
using System.Linq;
namespace Google.Cloud.Monitoring.V3
{
/// <summary>
/// Resource name for the 'project' resource.
/// </summary>
public sealed partial class ProjectName : IResourceName, IEquatable<ProjectName>
{
private static readonly PathTemplate s_template = new PathTemplate("projects/{project}");
/// <summary>
/// Parses the given project resource name in string form into a new
/// <see cref="ProjectName"/> instance.
/// </summary>
/// <param name="projectName">The project resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="ProjectName"/> if successful.</returns>
public static ProjectName Parse(string projectName)
{
GaxPreconditions.CheckNotNull(projectName, nameof(projectName));
TemplatedResourceName resourceName = s_template.ParseName(projectName);
return new ProjectName(resourceName[0]);
}
/// <summary>
/// Tries to parse the given project resource name in string form into a new
/// <see cref="ProjectName"/> instance.
/// </summary>
/// <remarks>
/// This method still throws <see cref="ArgumentNullException"/> if <paramref name="projectName"/> is null,
/// as this would usually indicate a programming error rather than a data error.
/// </remarks>
/// <param name="projectName">The project resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">When this method returns, the parsed <see cref="ProjectName"/>,
/// or <c>null</c> if parsing fails.</param>
/// <returns><c>true</c> if the name was parsed succssfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string projectName, out ProjectName result)
{
GaxPreconditions.CheckNotNull(projectName, nameof(projectName));
TemplatedResourceName resourceName;
if (s_template.TryParseName(projectName, out resourceName))
{
result = new ProjectName(resourceName[0]);
return true;
}
else
{
result = null;
return false;
}
}
/// <summary>
/// Constructs a new instance of the <see cref="ProjectName"/> resource name class
/// from its component parts.
/// </summary>
/// <param name="projectId">The project ID. Must not be <c>null</c>.</param>
public ProjectName(string projectId)
{
ProjectId = GaxPreconditions.CheckNotNull(projectId, nameof(projectId));
}
/// <summary>
/// The project ID. Never <c>null</c>.
/// </summary>
public string ProjectId { get; }
/// <inheritdoc />
public ResourceNameKind Kind => ResourceNameKind.Simple;
/// <inheritdoc />
public override string ToString() => s_template.Expand(ProjectId);
/// <inheritdoc />
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc />
public override bool Equals(object obj) => Equals(obj as ProjectName);
/// <inheritdoc />
public bool Equals(ProjectName other) => ToString() == other?.ToString();
/// <inheritdoc />
public static bool operator ==(ProjectName a, ProjectName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc />
public static bool operator !=(ProjectName a, ProjectName b) => !(a == b);
}
/// <summary>
/// Resource name for the 'metric_descriptor' resource.
/// </summary>
public sealed partial class MetricDescriptorName : IResourceName, IEquatable<MetricDescriptorName>
{
private static readonly PathTemplate s_template = new PathTemplate("projects/{project}/metricDescriptors/{metric_descriptor=**}");
/// <summary>
/// Parses the given metric_descriptor resource name in string form into a new
/// <see cref="MetricDescriptorName"/> instance.
/// </summary>
/// <param name="metricDescriptorName">The metric_descriptor resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="MetricDescriptorName"/> if successful.</returns>
public static MetricDescriptorName Parse(string metricDescriptorName)
{
GaxPreconditions.CheckNotNull(metricDescriptorName, nameof(metricDescriptorName));
TemplatedResourceName resourceName = s_template.ParseName(metricDescriptorName);
return new MetricDescriptorName(resourceName[0], resourceName[1]);
}
/// <summary>
/// Tries to parse the given metric_descriptor resource name in string form into a new
/// <see cref="MetricDescriptorName"/> instance.
/// </summary>
/// <remarks>
/// This method still throws <see cref="ArgumentNullException"/> if <paramref name="metricDescriptorName"/> is null,
/// as this would usually indicate a programming error rather than a data error.
/// </remarks>
/// <param name="metricDescriptorName">The metric_descriptor resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">When this method returns, the parsed <see cref="MetricDescriptorName"/>,
/// or <c>null</c> if parsing fails.</param>
/// <returns><c>true</c> if the name was parsed succssfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string metricDescriptorName, out MetricDescriptorName result)
{
GaxPreconditions.CheckNotNull(metricDescriptorName, nameof(metricDescriptorName));
TemplatedResourceName resourceName;
if (s_template.TryParseName(metricDescriptorName, out resourceName))
{
result = new MetricDescriptorName(resourceName[0], resourceName[1]);
return true;
}
else
{
result = null;
return false;
}
}
/// <summary>
/// Constructs a new instance of the <see cref="MetricDescriptorName"/> resource name class
/// from its component parts.
/// </summary>
/// <param name="projectId">The project ID. Must not be <c>null</c>.</param>
/// <param name="metricDescriptorId">The metricDescriptor ID. Must not be <c>null</c>.</param>
public MetricDescriptorName(string projectId, string metricDescriptorId)
{
ProjectId = GaxPreconditions.CheckNotNull(projectId, nameof(projectId));
MetricDescriptorId = GaxPreconditions.CheckNotNull(metricDescriptorId, nameof(metricDescriptorId));
}
/// <summary>
/// The project ID. Never <c>null</c>.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The metricDescriptor ID. Never <c>null</c>.
/// </summary>
public string MetricDescriptorId { get; }
/// <inheritdoc />
public ResourceNameKind Kind => ResourceNameKind.Simple;
/// <inheritdoc />
public override string ToString() => s_template.Expand(ProjectId, MetricDescriptorId);
/// <inheritdoc />
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc />
public override bool Equals(object obj) => Equals(obj as MetricDescriptorName);
/// <inheritdoc />
public bool Equals(MetricDescriptorName other) => ToString() == other?.ToString();
/// <inheritdoc />
public static bool operator ==(MetricDescriptorName a, MetricDescriptorName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc />
public static bool operator !=(MetricDescriptorName a, MetricDescriptorName b) => !(a == b);
}
/// <summary>
/// Resource name for the 'monitored_resource_descriptor' resource.
/// </summary>
public sealed partial class MonitoredResourceDescriptorName : IResourceName, IEquatable<MonitoredResourceDescriptorName>
{
private static readonly PathTemplate s_template = new PathTemplate("projects/{project}/monitoredResourceDescriptors/{monitored_resource_descriptor}");
/// <summary>
/// Parses the given monitored_resource_descriptor resource name in string form into a new
/// <see cref="MonitoredResourceDescriptorName"/> instance.
/// </summary>
/// <param name="monitoredResourceDescriptorName">The monitored_resource_descriptor resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="MonitoredResourceDescriptorName"/> if successful.</returns>
public static MonitoredResourceDescriptorName Parse(string monitoredResourceDescriptorName)
{
GaxPreconditions.CheckNotNull(monitoredResourceDescriptorName, nameof(monitoredResourceDescriptorName));
TemplatedResourceName resourceName = s_template.ParseName(monitoredResourceDescriptorName);
return new MonitoredResourceDescriptorName(resourceName[0], resourceName[1]);
}
/// <summary>
/// Tries to parse the given monitored_resource_descriptor resource name in string form into a new
/// <see cref="MonitoredResourceDescriptorName"/> instance.
/// </summary>
/// <remarks>
/// This method still throws <see cref="ArgumentNullException"/> if <paramref name="monitoredResourceDescriptorName"/> is null,
/// as this would usually indicate a programming error rather than a data error.
/// </remarks>
/// <param name="monitoredResourceDescriptorName">The monitored_resource_descriptor resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">When this method returns, the parsed <see cref="MonitoredResourceDescriptorName"/>,
/// or <c>null</c> if parsing fails.</param>
/// <returns><c>true</c> if the name was parsed succssfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string monitoredResourceDescriptorName, out MonitoredResourceDescriptorName result)
{
GaxPreconditions.CheckNotNull(monitoredResourceDescriptorName, nameof(monitoredResourceDescriptorName));
TemplatedResourceName resourceName;
if (s_template.TryParseName(monitoredResourceDescriptorName, out resourceName))
{
result = new MonitoredResourceDescriptorName(resourceName[0], resourceName[1]);
return true;
}
else
{
result = null;
return false;
}
}
/// <summary>
/// Constructs a new instance of the <see cref="MonitoredResourceDescriptorName"/> resource name class
/// from its component parts.
/// </summary>
/// <param name="projectId">The project ID. Must not be <c>null</c>.</param>
/// <param name="monitoredResourceDescriptorId">The monitoredResourceDescriptor ID. Must not be <c>null</c>.</param>
public MonitoredResourceDescriptorName(string projectId, string monitoredResourceDescriptorId)
{
ProjectId = GaxPreconditions.CheckNotNull(projectId, nameof(projectId));
MonitoredResourceDescriptorId = GaxPreconditions.CheckNotNull(monitoredResourceDescriptorId, nameof(monitoredResourceDescriptorId));
}
/// <summary>
/// The project ID. Never <c>null</c>.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The monitoredResourceDescriptor ID. Never <c>null</c>.
/// </summary>
public string MonitoredResourceDescriptorId { get; }
/// <inheritdoc />
public ResourceNameKind Kind => ResourceNameKind.Simple;
/// <inheritdoc />
public override string ToString() => s_template.Expand(ProjectId, MonitoredResourceDescriptorId);
/// <inheritdoc />
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc />
public override bool Equals(object obj) => Equals(obj as MonitoredResourceDescriptorName);
/// <inheritdoc />
public bool Equals(MonitoredResourceDescriptorName other) => ToString() == other?.ToString();
/// <inheritdoc />
public static bool operator ==(MonitoredResourceDescriptorName a, MonitoredResourceDescriptorName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc />
public static bool operator !=(MonitoredResourceDescriptorName a, MonitoredResourceDescriptorName b) => !(a == b);
}
/// <summary>
/// Resource name for the 'group' resource.
/// </summary>
public sealed partial class GroupName : IResourceName, IEquatable<GroupName>
{
private static readonly PathTemplate s_template = new PathTemplate("projects/{project}/groups/{group}");
/// <summary>
/// Parses the given group resource name in string form into a new
/// <see cref="GroupName"/> instance.
/// </summary>
/// <param name="groupName">The group resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="GroupName"/> if successful.</returns>
public static GroupName Parse(string groupName)
{
GaxPreconditions.CheckNotNull(groupName, nameof(groupName));
TemplatedResourceName resourceName = s_template.ParseName(groupName);
return new GroupName(resourceName[0], resourceName[1]);
}
/// <summary>
/// Tries to parse the given group resource name in string form into a new
/// <see cref="GroupName"/> instance.
/// </summary>
/// <remarks>
/// This method still throws <see cref="ArgumentNullException"/> if <paramref name="groupName"/> is null,
/// as this would usually indicate a programming error rather than a data error.
/// </remarks>
/// <param name="groupName">The group resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">When this method returns, the parsed <see cref="GroupName"/>,
/// or <c>null</c> if parsing fails.</param>
/// <returns><c>true</c> if the name was parsed succssfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string groupName, out GroupName result)
{
GaxPreconditions.CheckNotNull(groupName, nameof(groupName));
TemplatedResourceName resourceName;
if (s_template.TryParseName(groupName, out resourceName))
{
result = new GroupName(resourceName[0], resourceName[1]);
return true;
}
else
{
result = null;
return false;
}
}
/// <summary>
/// Constructs a new instance of the <see cref="GroupName"/> resource name class
/// from its component parts.
/// </summary>
/// <param name="projectId">The project ID. Must not be <c>null</c>.</param>
/// <param name="groupId">The group ID. Must not be <c>null</c>.</param>
public GroupName(string projectId, string groupId)
{
ProjectId = GaxPreconditions.CheckNotNull(projectId, nameof(projectId));
GroupId = GaxPreconditions.CheckNotNull(groupId, nameof(groupId));
}
/// <summary>
/// The project ID. Never <c>null</c>.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The group ID. Never <c>null</c>.
/// </summary>
public string GroupId { get; }
/// <inheritdoc />
public ResourceNameKind Kind => ResourceNameKind.Simple;
/// <inheritdoc />
public override string ToString() => s_template.Expand(ProjectId, GroupId);
/// <inheritdoc />
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc />
public override bool Equals(object obj) => Equals(obj as GroupName);
/// <inheritdoc />
public bool Equals(GroupName other) => ToString() == other?.ToString();
/// <inheritdoc />
public static bool operator ==(GroupName a, GroupName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc />
public static bool operator !=(GroupName a, GroupName b) => !(a == b);
}
/// <summary>
/// Resource name for the 'uptime_check_config' resource.
/// </summary>
public sealed partial class UptimeCheckConfigName : IResourceName, IEquatable<UptimeCheckConfigName>
{
private static readonly PathTemplate s_template = new PathTemplate("projects/{project}/uptimeCheckConfigs/{uptime_check_config}");
/// <summary>
/// Parses the given uptime_check_config resource name in string form into a new
/// <see cref="UptimeCheckConfigName"/> instance.
/// </summary>
/// <param name="uptimeCheckConfigName">The uptime_check_config resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="UptimeCheckConfigName"/> if successful.</returns>
public static UptimeCheckConfigName Parse(string uptimeCheckConfigName)
{
GaxPreconditions.CheckNotNull(uptimeCheckConfigName, nameof(uptimeCheckConfigName));
TemplatedResourceName resourceName = s_template.ParseName(uptimeCheckConfigName);
return new UptimeCheckConfigName(resourceName[0], resourceName[1]);
}
/// <summary>
/// Tries to parse the given uptime_check_config resource name in string form into a new
/// <see cref="UptimeCheckConfigName"/> instance.
/// </summary>
/// <remarks>
/// This method still throws <see cref="ArgumentNullException"/> if <paramref name="uptimeCheckConfigName"/> is null,
/// as this would usually indicate a programming error rather than a data error.
/// </remarks>
/// <param name="uptimeCheckConfigName">The uptime_check_config resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">When this method returns, the parsed <see cref="UptimeCheckConfigName"/>,
/// or <c>null</c> if parsing fails.</param>
/// <returns><c>true</c> if the name was parsed succssfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string uptimeCheckConfigName, out UptimeCheckConfigName result)
{
GaxPreconditions.CheckNotNull(uptimeCheckConfigName, nameof(uptimeCheckConfigName));
TemplatedResourceName resourceName;
if (s_template.TryParseName(uptimeCheckConfigName, out resourceName))
{
result = new UptimeCheckConfigName(resourceName[0], resourceName[1]);
return true;
}
else
{
result = null;
return false;
}
}
/// <summary>
/// Constructs a new instance of the <see cref="UptimeCheckConfigName"/> resource name class
/// from its component parts.
/// </summary>
/// <param name="projectId">The project ID. Must not be <c>null</c>.</param>
/// <param name="uptimeCheckConfigId">The uptimeCheckConfig ID. Must not be <c>null</c>.</param>
public UptimeCheckConfigName(string projectId, string uptimeCheckConfigId)
{
ProjectId = GaxPreconditions.CheckNotNull(projectId, nameof(projectId));
UptimeCheckConfigId = GaxPreconditions.CheckNotNull(uptimeCheckConfigId, nameof(uptimeCheckConfigId));
}
/// <summary>
/// The project ID. Never <c>null</c>.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The uptimeCheckConfig ID. Never <c>null</c>.
/// </summary>
public string UptimeCheckConfigId { get; }
/// <inheritdoc />
public ResourceNameKind Kind => ResourceNameKind.Simple;
/// <inheritdoc />
public override string ToString() => s_template.Expand(ProjectId, UptimeCheckConfigId);
/// <inheritdoc />
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc />
public override bool Equals(object obj) => Equals(obj as UptimeCheckConfigName);
/// <inheritdoc />
public bool Equals(UptimeCheckConfigName other) => ToString() == other?.ToString();
/// <inheritdoc />
public static bool operator ==(UptimeCheckConfigName a, UptimeCheckConfigName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc />
public static bool operator !=(UptimeCheckConfigName a, UptimeCheckConfigName b) => !(a == b);
}
public partial class CreateGroupRequest
{
/// <summary>
/// <see cref="ProjectName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public ProjectName ProjectName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Monitoring.V3.ProjectName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class CreateMetricDescriptorRequest
{
/// <summary>
/// <see cref="ProjectName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public ProjectName ProjectName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Monitoring.V3.ProjectName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class CreateTimeSeriesRequest
{
/// <summary>
/// <see cref="ProjectName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public ProjectName ProjectName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Monitoring.V3.ProjectName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class DeleteGroupRequest
{
/// <summary>
/// <see cref="GroupName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public GroupName GroupName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Monitoring.V3.GroupName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class DeleteMetricDescriptorRequest
{
/// <summary>
/// <see cref="MetricDescriptorName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public MetricDescriptorName MetricDescriptorName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Monitoring.V3.MetricDescriptorName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class GetGroupRequest
{
/// <summary>
/// <see cref="GroupName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public GroupName GroupName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Monitoring.V3.GroupName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class GetMetricDescriptorRequest
{
/// <summary>
/// <see cref="MetricDescriptorName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public MetricDescriptorName MetricDescriptorName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Monitoring.V3.MetricDescriptorName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class GetMonitoredResourceDescriptorRequest
{
/// <summary>
/// <see cref="MonitoredResourceDescriptorName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public MonitoredResourceDescriptorName MonitoredResourceDescriptorName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Monitoring.V3.MonitoredResourceDescriptorName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class Group
{
/// <summary>
/// <see cref="GroupName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public GroupName GroupName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Monitoring.V3.GroupName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
/// <summary>
/// <see cref="GroupName"/>-typed view over the <see cref="ParentName"/> resource name property.
/// </summary>
public GroupName ParentNameAsGroupName
{
get { return string.IsNullOrEmpty(ParentName) ? null : Google.Cloud.Monitoring.V3.GroupName.Parse(ParentName); }
set { ParentName = value != null ? value.ToString() : ""; }
}
}
public partial class ListGroupMembersRequest
{
/// <summary>
/// <see cref="GroupName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public GroupName GroupName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Monitoring.V3.GroupName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class ListGroupsRequest
{
/// <summary>
/// <see cref="ProjectName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public ProjectName ProjectName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Monitoring.V3.ProjectName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
/// <summary>
/// <see cref="GroupName"/>-typed view over the <see cref="ChildrenOfGroup"/> resource name property.
/// </summary>
public GroupName ChildrenOfGroupAsGroupName
{
get { return string.IsNullOrEmpty(ChildrenOfGroup) ? null : Google.Cloud.Monitoring.V3.GroupName.Parse(ChildrenOfGroup); }
set { ChildrenOfGroup = value != null ? value.ToString() : ""; }
}
/// <summary>
/// <see cref="GroupName"/>-typed view over the <see cref="AncestorsOfGroup"/> resource name property.
/// </summary>
public GroupName AncestorsOfGroupAsGroupName
{
get { return string.IsNullOrEmpty(AncestorsOfGroup) ? null : Google.Cloud.Monitoring.V3.GroupName.Parse(AncestorsOfGroup); }
set { AncestorsOfGroup = value != null ? value.ToString() : ""; }
}
/// <summary>
/// <see cref="GroupName"/>-typed view over the <see cref="DescendantsOfGroup"/> resource name property.
/// </summary>
public GroupName DescendantsOfGroupAsGroupName
{
get { return string.IsNullOrEmpty(DescendantsOfGroup) ? null : Google.Cloud.Monitoring.V3.GroupName.Parse(DescendantsOfGroup); }
set { DescendantsOfGroup = value != null ? value.ToString() : ""; }
}
}
public partial class ListMetricDescriptorsRequest
{
/// <summary>
/// <see cref="ProjectName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public ProjectName ProjectName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Monitoring.V3.ProjectName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class ListMonitoredResourceDescriptorsRequest
{
/// <summary>
/// <see cref="ProjectName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public ProjectName ProjectName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Monitoring.V3.ProjectName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class ListTimeSeriesRequest
{
/// <summary>
/// <see cref="ProjectName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public ProjectName ProjectName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Monitoring.V3.ProjectName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Buffers;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading;
namespace System.IO.Pipelines
{
/// <summary>
/// Default <see cref="IPipeWriter"/> and <see cref="IPipeReader"/> implementation.
/// </summary>
internal class Pipe : IPipe, IPipeReader, IPipeWriter, IReadableBufferAwaiter, IWritableBufferAwaiter
{
private static readonly Action<object> _signalReaderAwaitable = state => ((Pipe)state).ReaderCancellationRequested();
private static readonly Action<object> _signalWriterAwaitable = state => ((Pipe)state).WriterCancellationRequested();
// This sync objects protects the following state:
// 1. _commitHead & _commitHeadIndex
// 2. _length
// 3. _readerAwaitable & _writerAwaitable
private readonly object _sync = new object();
private readonly BufferPool _pool;
private readonly long _maximumSizeHigh;
private readonly long _maximumSizeLow;
private readonly IScheduler _readerScheduler;
private readonly IScheduler _writerScheduler;
private long _length;
private long _currentWriteLength;
private PipeAwaitable _readerAwaitable;
private PipeAwaitable _writerAwaitable;
private PipeCompletion _writerCompletion;
private PipeCompletion _readerCompletion;
// The read head which is the extent of the IPipelineReader's consumed bytes
private BufferSegment _readHead;
// The commit head which is the extent of the bytes available to the IPipelineReader to consume
private BufferSegment _commitHead;
private int _commitHeadIndex;
// The write head which is the extent of the IPipelineWriter's written bytes
private BufferSegment _writingHead;
private PipeOperationState _readingState;
private PipeOperationState _writingState;
private bool _disposed;
internal long Length => _length;
/// <summary>
/// Initializes the <see cref="Pipe"/> with the specifed <see cref="IBufferPool"/>.
/// </summary>
/// <param name="pool"></param>
/// <param name="options"></param>
public Pipe(BufferPool pool, PipeOptions options = null)
{
if (pool == null)
{
throw new ArgumentNullException(nameof(pool));
}
options = options ?? new PipeOptions();
if (options.MaximumSizeLow < 0)
{
throw new ArgumentOutOfRangeException(nameof(options.MaximumSizeLow));
}
if (options.MaximumSizeHigh < 0)
{
throw new ArgumentOutOfRangeException(nameof(options.MaximumSizeHigh));
}
if (options.MaximumSizeLow > options.MaximumSizeHigh)
{
throw new ArgumentException(nameof(options.MaximumSizeHigh) + " should be greater or equal to " + nameof(options.MaximumSizeLow), nameof(options.MaximumSizeHigh));
}
_pool = pool;
_maximumSizeHigh = options.MaximumSizeHigh;
_maximumSizeLow = options.MaximumSizeLow;
_readerScheduler = options.ReaderScheduler ?? InlineScheduler.Default;
_writerScheduler = options.WriterScheduler ?? InlineScheduler.Default;
ResetState();
}
private void ResetState()
{
_readerAwaitable = new PipeAwaitable(completed: false);
_writerAwaitable = new PipeAwaitable(completed: true);
_readerCompletion = default(PipeCompletion);
_writerCompletion = default(PipeCompletion);
_commitHeadIndex = 0;
_currentWriteLength = 0;
_length = 0;
}
internal Buffer<byte> Buffer => _writingHead?.Buffer.Slice(_writingHead.End, _writingHead.WritableBytes) ?? Buffer<byte>.Empty;
/// <summary>
/// Allocates memory from the pipeline to write into.
/// </summary>
/// <param name="minimumSize">The minimum size buffer to allocate</param>
/// <returns>A <see cref="WritableBuffer"/> that can be written to.</returns>
WritableBuffer IPipeWriter.Alloc(int minimumSize)
{
if (_writerCompletion.IsCompleted)
{
PipelinesThrowHelper.ThrowInvalidOperationException(ExceptionResource.NoWritingAllowed, _writerCompletion.Location);
}
if (minimumSize < 0)
{
PipelinesThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.minimumSize);
}
lock (_sync)
{
// CompareExchange not required as its setting to current value if test fails
_writingState.Begin(ExceptionResource.AlreadyWriting);
if (minimumSize > 0)
{
try
{
AllocateWriteHeadUnsynchronized(minimumSize);
}
catch (Exception)
{
// Reset producing state if allocation failed
_writingState.End(ExceptionResource.NoWriteToComplete);
throw;
}
}
_currentWriteLength = 0;
return new WritableBuffer(this);
}
}
internal void Ensure(int count = 1)
{
EnsureAlloc();
var segment = _writingHead;
if (segment == null)
{
// Changing commit head shared with Reader
lock (_sync)
{
segment = AllocateWriteHeadUnsynchronized(count);
}
}
var bytesLeftInBuffer = segment.WritableBytes;
// If inadequate bytes left or if the segment is readonly
if (bytesLeftInBuffer == 0 || bytesLeftInBuffer < count || segment.ReadOnly)
{
var nextBuffer = _pool.Rent(count);
var nextSegment = new BufferSegment(nextBuffer);
segment.Next = nextSegment;
_writingHead = nextSegment;
}
}
private BufferSegment AllocateWriteHeadUnsynchronized(int count)
{
BufferSegment segment = null;
if (_commitHead != null && !_commitHead.ReadOnly)
{
// Try to return the tail so the calling code can append to it
int remaining = _commitHead.WritableBytes;
if (count <= remaining)
{
// Free tail space of the right amount, use that
segment = _commitHead;
}
}
if (segment == null)
{
// No free tail space, allocate a new segment
segment = new BufferSegment(_pool.Rent(count));
}
if (_commitHead == null)
{
// No previous writes have occurred
_commitHead = segment;
}
else if (segment != _commitHead && _commitHead.Next == null)
{
// Append the segment to the commit head if writes have been committed
// and it isn't the same segment (unused tail space)
_commitHead.Next = segment;
}
// Set write head to assigned segment
_writingHead = segment;
return segment;
}
internal void Append(ReadableBuffer buffer)
{
if (buffer.IsEmpty)
{
return; // nothing to do
}
EnsureAlloc();
BufferSegment clonedEnd;
var clonedBegin = BufferSegment.Clone(buffer.Start, buffer.End, out clonedEnd);
if (_writingHead == null)
{
// No active write
lock (_sync)
{
if (_commitHead == null)
{
// No allocated buffers yet, not locking as _readHead will be null
_commitHead = clonedBegin;
}
else
{
Debug.Assert(_commitHead.Next == null);
// Allocated buffer, append as next segment
_commitHead.Next = clonedBegin;
}
}
}
else
{
Debug.Assert(_writingHead.Next == null);
// Active write, append as next segment
_writingHead.Next = clonedBegin;
}
// Move write head to end of buffer
_writingHead = clonedEnd;
_currentWriteLength += buffer.Length;
}
private void EnsureAlloc()
{
if (!_writingState.IsActive)
{
PipelinesThrowHelper.ThrowInvalidOperationException(ExceptionResource.NotWritingNoAlloc);
}
}
internal void Commit()
{
// Changing commit head shared with Reader
lock (_sync)
{
CommitUnsynchronized();
}
}
internal void CommitUnsynchronized()
{
_writingState.End(ExceptionResource.NoWriteToComplete);
if (_writingHead == null)
{
// Nothing written to commit
return;
}
if (_readHead == null)
{
// Update the head to point to the head of the buffer.
// This happens if we called alloc(0) then write
_readHead = _commitHead;
}
// Always move the commit head to the write head
_commitHead = _writingHead;
_commitHeadIndex = _writingHead.End;
_length += _currentWriteLength;
// Do not reset if reader is complete
if (_maximumSizeHigh > 0 &&
_length >= _maximumSizeHigh &&
!_readerCompletion.IsCompleted)
{
_writerAwaitable.Reset();
}
// Clear the writing state
_writingHead = null;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void AdvanceWriter(int bytesWritten)
{
EnsureAlloc();
if (bytesWritten > 0)
{
if (_writingHead == null)
{
PipelinesThrowHelper.ThrowInvalidOperationException(ExceptionResource.AdvancingWithNoBuffer);
}
Debug.Assert(!_writingHead.ReadOnly);
Debug.Assert(_writingHead.Next == null);
var buffer = _writingHead.Buffer;
var bufferIndex = _writingHead.End + bytesWritten;
if (bufferIndex > buffer.Length)
{
PipelinesThrowHelper.ThrowInvalidOperationException(ExceptionResource.AdvancingPastBufferSize);
}
_writingHead.End = bufferIndex;
_currentWriteLength += bytesWritten;
}
else if (bytesWritten < 0)
{
PipelinesThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.bytesWritten);
} // and if zero, just do nothing; don't need to validate tail etc
}
internal WritableBufferAwaitable FlushAsync(CancellationToken cancellationToken = default(CancellationToken))
{
Action awaitable;
CancellationTokenRegistration cancellationTokenRegistration;
lock (_sync)
{
if (_writingState.IsActive)
{
// Commit the data as not already committed
CommitUnsynchronized();
}
awaitable = _readerAwaitable.Complete();
cancellationTokenRegistration = _writerAwaitable.AttachToken(cancellationToken, _signalWriterAwaitable, this);
}
cancellationTokenRegistration.Dispose();
TrySchedule(_readerScheduler, awaitable);
return new WritableBufferAwaitable(this);
}
internal ReadableBuffer AsReadableBuffer()
{
if (_writingHead == null)
{
return new ReadableBuffer(); // Nothing written return empty
}
ReadCursor readStart;
lock (_sync)
{
readStart = new ReadCursor(_commitHead, _commitHeadIndex);
}
return new ReadableBuffer(readStart, new ReadCursor(_writingHead, _writingHead.End));
}
/// <summary>
/// Marks the pipeline as being complete, meaning no more items will be written to it.
/// </summary>
/// <param name="exception">Optional Exception indicating a failure that's causing the pipeline to complete.</param>
void IPipeWriter.Complete(Exception exception)
{
if (_writingState.IsActive)
{
PipelinesThrowHelper.ThrowInvalidOperationException(ExceptionResource.CompleteWriterActiveWriter, _writingState.Location);
}
_writerCompletion.TryComplete(exception);
Action awaitable;
lock (_sync)
{
awaitable = _readerAwaitable.Complete();
}
TrySchedule(_readerScheduler, awaitable);
if (_readerCompletion.IsCompleted)
{
Dispose();
}
}
// Reading
void IPipeReader.Advance(ReadCursor consumed, ReadCursor examined)
{
BufferSegment returnStart = null;
BufferSegment returnEnd = null;
int consumedBytes = 0;
if (!consumed.IsDefault)
{
returnStart = _readHead;
consumedBytes = ReadCursor.GetLength(returnStart, returnStart.Start, consumed.Segment, consumed.Index);
returnEnd = consumed.Segment;
_readHead = consumed.Segment;
_readHead.Start = consumed.Index;
}
// Reading commit head shared with writer
Action continuation = null;
lock (_sync)
{
var oldLength = _length;
_length -= consumedBytes;
if (oldLength >= _maximumSizeLow &&
_length < _maximumSizeLow)
{
continuation = _writerAwaitable.Complete();
}
// We reset the awaitable to not completed if we've examined everything the producer produced so far
if (examined.Segment == _commitHead &&
examined.Index == _commitHeadIndex &&
!_writerCompletion.IsCompleted)
{
if (!_writerAwaitable.IsCompleted)
{
PipelinesThrowHelper.ThrowInvalidOperationException(ExceptionResource.BackpressureDeadlock);
}
_readerAwaitable.Reset();
}
_readingState.End(ExceptionResource.NoReadToComplete);
}
while (returnStart != null && returnStart != returnEnd)
{
var returnSegment = returnStart;
returnStart = returnStart.Next;
returnSegment.Dispose();
}
TrySchedule(_writerScheduler, continuation);
}
/// <summary>
/// Signal to the producer that the consumer is done reading.
/// </summary>
/// <param name="exception">Optional Exception indicating a failure that's causing the pipeline to complete.</param>
void IPipeReader.Complete(Exception exception)
{
if (_readingState.IsActive)
{
PipelinesThrowHelper.ThrowInvalidOperationException(ExceptionResource.CompleteReaderActiveReader, _readingState.Location);
}
_readerCompletion.TryComplete(exception);
Action awaitable;
lock (_sync)
{
awaitable = _writerAwaitable.Complete();
}
TrySchedule(_writerScheduler, awaitable);
if (_writerCompletion.IsCompleted)
{
Dispose();
}
}
/// <summary>
/// Cancel to currently pending call to <see cref="ReadAsync"/> without completing the <see cref="IPipeReader"/>.
/// </summary>
void IPipeReader.CancelPendingRead()
{
Action awaitable;
lock (_sync)
{
awaitable = _readerAwaitable.Cancel();
}
TrySchedule(_readerScheduler, awaitable);
}
/// <summary>
/// Cancel to currently pending call to <see cref="WritableBuffer.FlushAsync"/> without completing the <see cref="IPipeWriter"/>.
/// </summary>
void IPipeWriter.CancelPendingFlush()
{
Action awaitable;
lock (_sync)
{
awaitable = _writerAwaitable.Cancel();
}
TrySchedule(_writerScheduler, awaitable);
}
ReadableBufferAwaitable IPipeReader.ReadAsync(CancellationToken token)
{
CancellationTokenRegistration cancellationTokenRegistration;
if (_readerCompletion.IsCompleted)
{
PipelinesThrowHelper.ThrowInvalidOperationException(ExceptionResource.NoReadingAllowed, _readerCompletion.Location);
}
lock (_sync)
{
cancellationTokenRegistration= _readerAwaitable.AttachToken(token, _signalReaderAwaitable, this);
}
cancellationTokenRegistration.Dispose();
return new ReadableBufferAwaitable(this);
}
bool IPipeReader.TryRead(out ReadResult result)
{
lock (_sync)
{
if (_readerCompletion.IsCompleted)
{
PipelinesThrowHelper.ThrowInvalidOperationException(ExceptionResource.NoReadingAllowed, _readerCompletion.Location);
}
result = new ReadResult();
if (_length > 0 || _readerAwaitable.IsCompleted)
{
GetResult(ref result);
return true;
}
if(_readerAwaitable.HasContinuation)
{
PipelinesThrowHelper.ThrowInvalidOperationException(ExceptionResource.AlreadyReading);
}
return false;
}
}
private static void TrySchedule(IScheduler scheduler, Action action)
{
if (action != null)
{
scheduler.Schedule(action);
}
}
private void Dispose()
{
lock (_sync)
{
if (_disposed)
{
return;
}
_disposed = true;
// Return all segments
var segment = _readHead;
while (segment != null)
{
var returnSegment = segment;
segment = segment.Next;
returnSegment.Dispose();
}
_readHead = null;
_commitHead = null;
}
}
// IReadableBufferAwaiter members
bool IReadableBufferAwaiter.IsCompleted => _readerAwaitable.IsCompleted;
void IReadableBufferAwaiter.OnCompleted(Action continuation)
{
Action awaitable;
lock (_sync)
{
awaitable = _readerAwaitable.OnCompleted(continuation, ref _writerCompletion);
}
TrySchedule(_readerScheduler, awaitable);
}
ReadResult IReadableBufferAwaiter.GetResult()
{
if (!_readerAwaitable.IsCompleted)
{
PipelinesThrowHelper.ThrowInvalidOperationException(ExceptionResource.GetResultNotCompleted);
}
var result = new ReadResult();
lock (_sync)
{
GetResult(ref result);
}
return result;
}
private void GetResult(ref ReadResult result)
{
if (_writerCompletion.IsCompletedOrThrow())
{
result.ResultFlags |= ResultFlags.Completed;
}
var isCancelled = _readerAwaitable.ObserveCancelation();
if (isCancelled)
{
result.ResultFlags |= ResultFlags.Cancelled;
}
// No need to read end if there is no head
var head = _readHead;
if (head != null)
{
// Reading commit head shared with writer
result.ResultBuffer.BufferEnd.Segment = _commitHead;
result.ResultBuffer.BufferEnd.Index = _commitHeadIndex;
result.ResultBuffer.BufferLength = ReadCursor.GetLength(head, head.Start, _commitHead, _commitHeadIndex);
result.ResultBuffer.BufferStart.Segment = head;
result.ResultBuffer.BufferStart.Index = head.Start;
}
if (isCancelled)
{
_readingState.BeginTentative(ExceptionResource.AlreadyReading);
}
else
{
_readingState.Begin(ExceptionResource.AlreadyReading);
}
}
// IWritableBufferAwaiter members
bool IWritableBufferAwaiter.IsCompleted => _writerAwaitable.IsCompleted;
FlushResult IWritableBufferAwaiter.GetResult()
{
var result = new FlushResult();
lock (_sync)
{
if (!_writerAwaitable.IsCompleted)
{
PipelinesThrowHelper.ThrowInvalidOperationException(ExceptionResource.GetResultNotCompleted);
}
// Change the state from to be cancelled -> observed
if (_writerAwaitable.ObserveCancelation())
{
result.ResultFlags |= ResultFlags.Cancelled;
}
if (_readerCompletion.IsCompletedOrThrow())
{
result.ResultFlags |= ResultFlags.Completed;
}
}
return result;
}
void IWritableBufferAwaiter.OnCompleted(Action continuation)
{
Action awaitable;
lock (_sync)
{
awaitable = _writerAwaitable.OnCompleted(continuation, ref _readerCompletion);
}
TrySchedule(_writerScheduler, awaitable);
}
private void ReaderCancellationRequested()
{
Action action;
lock (_sync)
{
action = _readerAwaitable.Cancel();
}
TrySchedule(_readerScheduler, action);
}
private void WriterCancellationRequested()
{
Action action;
lock (_sync)
{
action = _writerAwaitable.Cancel();
}
TrySchedule(_writerScheduler, action);
}
public IPipeReader Reader => this;
public IPipeWriter Writer => this;
public void Reset()
{
if (!_disposed)
{
throw new InvalidOperationException("Both reader and writer need to be completed to be able to reset ");
}
_disposed = false;
ResetState();
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
/// @class ContextPopup
/// @brief Create a Popup Dialog that closes itself when signaled by an event.
///
/// ContextPopup is a support class that offers a simple way of displaying
/// reusable context sensitive GuiControl popups. These dialogs are created
/// and shown to the user when the <b>show</b> method is used.
///
/// Once a Popup is shown it will be dismissed if it meets one of a few
/// criteria.
///
/// 1. A user clicks anywhere outside the bounds of the GuiControl, specified by
/// the 'dialog' field on the object.
/// 2. Time Passes of (n)Milliseconds, specifed by the 'timeout' field on
/// the object.
///
/// For example, if you wished to create a context dialog with a dialog you held in
/// a local variable named %myDialog you would create a new script object as such.
///
///
/// @code
/// %MyContextPopup = new ScriptObject()
/// {
/// class = ContextPopup;
/// superClass= MyCallbackNamespace; // Only Necessary when you want to perform logic pre/post showing
/// dialog = %%myDialog.getID();
/// delay = 500; // Pop the Popup after 500 Milliseconds
/// };
/// @endcode
///
/// Now, if you wanted to show the dialog %%myDialog and have it dismissed when anything in the
/// background is clicked, simply call the following.
///
///
/// @code
/// %MyContextPopup.show( %positionX, %positionY );
/// @endcode
///
/// If you need to know more than show the dialog and hide it when clicked or time passes, ContextPopup
/// Provides callback methods that you may override for doing intermediate processing on a dialog
/// that is to be shown or is being hidden. For example, in the above script we created a Context Dialog Container
/// called @%myContextDialog with a superClass of <b>MyCallbackNamespace</b>. If we wanted to hide the cursor when
/// the dialog was shown, and show it when the dialog was hidden, we could implement the following functions.
///
/// @code
/// function MyCallbackNamespace::onContextActivate( %%this )
/// {
/// // Hide Cursor Here
/// }
/// function MyCallbackNamespace::onContextDeactivate( %%this )
/// {
/// // Show Cursor Here
/// }
/// @endcode
///
/// @field GuiControl Dialog The GuiControl dialog to be shown when the context dialog is activated
function ContextDialogContainer::onAdd(%this)
{
// Add to our cleanup group.
$EditorClassesGroup.add( %this );
%this.base = new GuiButtonBaseCtrl()
{
profile = ToolsGuiTransparentProfile;
class = ContextDialogWatcher;
parent = %this;
modal = true;
};
// Flag not active.
%this.isPushed = false;
// Add to our cleanup group.
$EditorClassesGroup.add( %this.base );
return true;
}
function ContextDialogContainer::onRemove(%this)
{
%this.Hide();
if( isObject( %this.base ) )
%this.base.delete();
}
//-----------------------------------------------------------------------------
/// (SimID this, int positionX, int positionY)
/// Shows the GuiControl specified in the Dialog field at the coordinates passed
/// to this function. If no coordinates are passed to this function, the Dialog control
/// is shown using it's current position.
///
/// @param this The ContextDialogContainer object
/// @param positionX The X Position in Global Screen Coordinates to display the dialog
/// @param positionY The Y Position in Global Screen Coordinates to display the dialog
/// @param delay Optional delay before this popup is hidden that overrides that specified at construction time
///
//-----------------------------------------------------------------------------
function ContextDialogContainer::Show( %this, %positionX, %positionY, %delay )
{
if( %this.isPushed == true )
return true;
if( !isObject( %this.Dialog ) )
return false;
// Store old parent.
%this.oldParent = %this.dialog.getParent();
// Set new parent.
%this.base.add( %this.Dialog );
if( %positionX !$= "" && %positionY !$= "" )
%this.Dialog.setPositionGlobal( %positionX, %positionY );
Canvas.pushDialog( %this.base, 99 );
// Setup Delay Schedule
if( isEventPending( %this.popSchedule ) )
cancel( %this.popSchedule );
if( %delay !$= "" )
%this.popSchedule = %this.schedule( %delay, hide );
else if( %this.Delay !$= "" )
%this.popSchedule = %this.schedule( %this.Delay, hide );
}
//-----------------------------------------------------------------------------
/// (SimID this)
/// Hides the GuiControl specified in the Dialog field if shown. This function
/// is provided merely for more flexibility in when your dialog is shown. If you
/// do not call this function, it will be called when the dialog is dismissed by
/// a background click.
///
/// @param this The ContextDialogContainer object
///
//-----------------------------------------------------------------------------
function ContextDialogContainer::Hide( %this )
{
if( %this.isPushed == true )
Canvas.popDialog( %this.base );
// Restore Old Parent;
if( isObject( %this.Dialog ) && isObject( %this.oldParent ) )
%this.oldParent.add( %this.Dialog );
}
// ContextDialogWatcher Class - JDD
// CDW is a namespace link for the context background button to catch
// event information and pass it back to the main class.
//
// onClick it will dismiss the parent
// onDialogPop it will cleanup and notify user of deactivation
// onDialogPush it will initialize state information and notify user of activation
function ContextDialogWatcher::onClick( %this )
{
if( isObject( %this.parent ) )
%this.parent.hide();
}
function ContextDialogWatcher::onDialogPop( %this )
{
if( !isObject( %this.parent ) )
return;
%this.parent.isPushed = false;
if( %this.parent.isMethod( "onContextDeactivate" ) )
%this.parent.onContextDeactivate();
}
function ContextDialogWatcher::onDialogPush( %this )
{
if( !isObject( %this.parent ) )
return;
%this.parent.isPushed = true;
if( %this.parent.isMethod( "onContextActivate" ) )
%this.parent.onContextActivate();
}
| |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
namespace System.Data.Entity.Interception
{
using System.Data.Common;
using System.Data.Entity.Core;
using System.Data.Entity.Core.Common;
using System.Data.Entity.Core.EntityClient;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Infrastructure.DependencyResolution;
using System.Data.Entity.Infrastructure.Interception;
using System.Data.Entity.SqlServer;
using System.Data.Entity.TestHelpers;
using System.Data.SqlClient;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Moq;
using Xunit;
public class CommitFailureTests : FunctionalTestBase
{
private void Execute_commit_failure_test(
Action<Action> verifyInitialization, Action<Action> verifySaveChanges, int expectedBlogs, bool useTransactionHandler,
bool useExecutionStrategy, bool rollbackOnFail)
{
var failingTransactionInterceptorMock = new Mock<FailingTransactionInterceptor> { CallBase = true };
var failingTransactionInterceptor = failingTransactionInterceptorMock.Object;
DbInterception.Add(failingTransactionInterceptor);
if (useTransactionHandler)
{
MutableResolver.AddResolver<Func<TransactionHandler>>(
new TransactionHandlerResolver(() => new CommitFailureHandler(), null, null));
}
var isSqlAzure = DatabaseTestHelpers.IsSqlAzure(ModelHelpers.BaseConnectionString);
if (useExecutionStrategy)
{
MutableResolver.AddResolver<Func<IDbExecutionStrategy>>(
key =>
(Func<IDbExecutionStrategy>)
(() => isSqlAzure
? new TestSqlAzureExecutionStrategy()
: (IDbExecutionStrategy)
new SqlAzureExecutionStrategy(maxRetryCount: 2, maxDelay: TimeSpan.FromMilliseconds(1))));
}
try
{
using (var context = new BlogContextCommit())
{
context.Database.Delete();
failingTransactionInterceptor.ShouldFailTimes = 1;
failingTransactionInterceptor.ShouldRollBack = rollbackOnFail;
verifyInitialization(() => context.Blogs.Count());
failingTransactionInterceptor.ShouldFailTimes = 0;
ExtendedSqlAzureExecutionStrategy.ExecuteNew(
() =>
{
Assert.Equal(expectedBlogs, context.Blogs.Count());
});
failingTransactionInterceptor.ShouldFailTimes = 1;
context.Blogs.Add(new BlogContext.Blog());
verifySaveChanges(() => context.SaveChanges());
var expectedCommitCount = useTransactionHandler
? useExecutionStrategy
? 6
: rollbackOnFail
? 4
: 3
: 4;
failingTransactionInterceptorMock.Verify(
m => m.Committing(It.IsAny<DbTransaction>(), It.IsAny<DbTransactionInterceptionContext>()),
isSqlAzure
? Times.AtLeast(expectedCommitCount)
: Times.Exactly(expectedCommitCount));
}
}
finally
{
DbInterception.Remove(failingTransactionInterceptor);
MutableResolver.ClearResolvers();
}
DbDispatchersHelpers.AssertNoInterceptors();
}
[Fact]
public void No_TransactionHandler_and_no_ExecutionStrategy_throws_CommitFailedException_on_commit_fail()
{
using (var context = new BlogContextCommit())
{
ExtendedSqlAzureExecutionStrategy.ExecuteNew(
() =>
{
Assert.Equal(expectedBlogs, context.Blogs.Count());
});
using (var transactionContext = new TransactionContext(context.Database.Connection))
{
using (var infoContext = GetInfoContext(transactionContext))
{
Assert.True(
!infoContext.TableExists("__Transactions")
|| !transactionContext.Transactions.Any());
}
}
}
Execute_commit_failure_test(
c => Assert.Throws<DataException>(() => c()).InnerException.ValidateMessage("CommitFailed"),
c => Assert.Throws<CommitFailedException>(() => c()).ValidateMessage("CommitFailed"),
expectedBlogs: 1,
useTransactionHandler: false,
useExecutionStrategy: false,
rollbackOnFail: true);
}
[Fact]
public void No_TransactionHandler_and_no_ExecutionStrategy_throws_CommitFailedException_on_false_commit_fail()
{
Execute_commit_failure_test(
c => Assert.Throws<DataException>(() => c()).InnerException.ValidateMessage("CommitFailed"),
c => Assert.Throws<CommitFailedException>(() => c()).ValidateMessage("CommitFailed"),
expectedBlogs: 2,
useTransactionHandler: false,
useExecutionStrategy: false,
rollbackOnFail: false);
}
[Fact]
[UseDefaultExecutionStrategy]
public void TransactionHandler_and_no_ExecutionStrategy_rethrows_original_exception_on_commit_fail()
{
Execute_commit_failure_test(
c => Assert.Throws<TimeoutException>(() => c()),
c =>
{
var exception = Assert.Throws<EntityException>(() => c());
Assert.IsType<TimeoutException>(exception.InnerException);
},
expectedBlogs: 1,
useTransactionHandler: true,
useExecutionStrategy: false,
rollbackOnFail: true);
}
[Fact]
public void TransactionHandler_and_no_ExecutionStrategy_does_not_throw_on_false_commit_fail()
{
Execute_commit_failure_test(
c => c(),
c => c(),
expectedBlogs: 2,
useTransactionHandler: true,
useExecutionStrategy: false,
rollbackOnFail: false);
}
[Fact]
public void No_TransactionHandler_and_ExecutionStrategy_throws_CommitFailedException_on_commit_fail()
{
Execute_commit_failure_test(
c => Assert.Throws<DataException>(() => c()).InnerException.ValidateMessage("CommitFailed"),
c => Assert.Throws<CommitFailedException>(() => c()).ValidateMessage("CommitFailed"),
expectedBlogs: 1,
useTransactionHandler: false,
useExecutionStrategy: true,
rollbackOnFail: true);
}
[Fact]
public void No_TransactionHandler_and_ExecutionStrategy_throws_CommitFailedException_on_false_commit_fail()
{
Execute_commit_failure_test(
c => Assert.Throws<DataException>(() => c()).InnerException.ValidateMessage("CommitFailed"),
c => Assert.Throws<CommitFailedException>(() => c()).ValidateMessage("CommitFailed"),
expectedBlogs: 2,
useTransactionHandler: false,
useExecutionStrategy: true,
rollbackOnFail: false);
}
[Fact]
public void TransactionHandler_and_ExecutionStrategy_retries_on_commit_fail()
{
Execute_commit_failure_test(
c => c(),
c => c(),
expectedBlogs: 2,
useTransactionHandler: true,
useExecutionStrategy: true,
rollbackOnFail: true);
}
[Fact]
public void TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail()
{
MutableResolver.AddResolver<Func<TransactionHandler>>(
new TransactionHandlerResolver(() => new CommitFailureHandler(), null, null));
TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_implementation(
context => context.SaveChanges());
}
#if !NET40
[Fact]
public void TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_async()
{
MutableResolver.AddResolver<Func<TransactionHandler>>(
new TransactionHandlerResolver(() => new CommitFailureHandler(), null, null));
TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_implementation(
context => context.SaveChangesAsync().Wait());
}
#endif
[Fact]
public void TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_with_custom_TransactionContext()
{
MutableResolver.AddResolver<Func<TransactionHandler>>(
new TransactionHandlerResolver(() => new CommitFailureHandler(c => new MyTransactionContext(c)), null, null));
TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_implementation(
context =>
{
context.SaveChanges();
using (var infoContext = GetInfoContext(context))
{
Assert.True(infoContext.TableExists("MyTransactions"));
var column = infoContext.Columns.Single(c => c.Name == "Time");
Assert.Equal("datetime2", column.Type);
}
});
}
public class MyTransactionContext : TransactionContext
{
public MyTransactionContext(DbConnection connection)
: base(connection)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<TransactionRow>()
.ToTable("MyTransactions")
.HasKey(e => e.Id)
.Property(e => e.CreationTime).HasColumnName("Time").HasColumnType("datetime2");
}
}
private void TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_implementation(
Action<BlogContextCommit> runAndVerify)
{
var failingTransactionInterceptorMock = new Mock<FailingTransactionInterceptor> { CallBase = true };
var failingTransactionInterceptor = failingTransactionInterceptorMock.Object;
DbInterception.Add(failingTransactionInterceptor);
var isSqlAzure = DatabaseTestHelpers.IsSqlAzure(ModelHelpers.BaseConnectionString);
MutableResolver.AddResolver<Func<IDbExecutionStrategy>>(
key =>
(Func<IDbExecutionStrategy>)
(() => isSqlAzure
? new TestSqlAzureExecutionStrategy()
: (IDbExecutionStrategy)new SqlAzureExecutionStrategy(maxRetryCount: 2, maxDelay: TimeSpan.FromMilliseconds(1))));
try
{
using (var context = new BlogContextCommit())
{
failingTransactionInterceptor.ShouldFailTimes = 0;
context.Database.Delete();
Assert.Equal(1, context.Blogs.Count());
failingTransactionInterceptor.ShouldFailTimes = 2;
failingTransactionInterceptor.ShouldRollBack = false;
context.Blogs.Add(new BlogContext.Blog());
runAndVerify(context);
failingTransactionInterceptorMock.Verify(
m => m.Committing(It.IsAny<DbTransaction>(), It.IsAny<DbTransactionInterceptionContext>()),
isSqlAzure
? Times.AtLeast(3)
: Times.Exactly(3));
}
using (var context = new BlogContextCommit())
{
Assert.Equal(2, context.Blogs.Count());
using (var transactionContext = new TransactionContext(context.Database.Connection))
{
using (var infoContext = GetInfoContext(transactionContext))
{
Assert.True(
!infoContext.TableExists("__Transactions")
|| !transactionContext.Transactions.Any());
}
}
}
}
finally
{
DbInterception.Remove(failingTransactionInterceptorMock.Object);
MutableResolver.ClearResolvers();
}
DbDispatchersHelpers.AssertNoInterceptors();
}
[Fact]
public void CommitFailureHandler_Dispose_does_not_use_ExecutionStrategy()
{
CommitFailureHandler_with_ExecutionStrategy_test(
(c, executionStrategyMock) =>
{
c.TransactionHandler.Dispose();
executionStrategyMock.Verify(e => e.Execute(It.IsAny<Func<int>>()), Times.Exactly(3));
});
}
[Fact]
public void CommitFailureHandler_Dispose_catches_exceptions()
{
CommitFailureHandler_with_ExecutionStrategy_test(
(c, executionStrategyMock) =>
{
using (var transactionContext = new TransactionContext(((EntityConnection)c.Connection).StoreConnection))
{
foreach (var tran in transactionContext.Set<TransactionRow>().ToList())
{
transactionContext.Transactions.Remove(tran);
}
transactionContext.SaveChanges();
}
c.TransactionHandler.Dispose();
});
}
[Fact]
public void CommitFailureHandler_prunes_transactions_after_set_amount()
{
CommitFailureHandler_prunes_transactions_after_set_amount_implementation(false);
}
[Fact]
public void CommitFailureHandler_prunes_transactions_after_set_amount_and_handles_false_failure()
{
CommitFailureHandler_prunes_transactions_after_set_amount_implementation(true);
}
private void CommitFailureHandler_prunes_transactions_after_set_amount_implementation(bool shouldThrow)
{
var failingTransactionInterceptor = new FailingTransactionInterceptor();
DbInterception.Add(failingTransactionInterceptor);
MutableResolver.AddResolver<Func<TransactionHandler>>(
new TransactionHandlerResolver(() => new MyCommitFailureHandler(c => new TransactionContext(c)), null, null));
try
{
using (var context = new BlogContextCommit())
{
context.Database.Delete();
Assert.Equal(1, context.Blogs.Count());
var objectContext = ((IObjectContextAdapter)context).ObjectContext;
var transactionHandler = (MyCommitFailureHandler)objectContext.TransactionHandler;
for (var i = 0; i < transactionHandler.PruningLimit; i++)
{
context.Blogs.Add(new BlogContext.Blog());
context.SaveChanges();
}
AssertTransactionHistoryCount(context, transactionHandler.PruningLimit);
if (shouldThrow)
{
failingTransactionInterceptor.ShouldFailTimes = 1;
failingTransactionInterceptor.ShouldRollBack = false;
}
context.Blogs.Add(new BlogContext.Blog());
context.SaveChanges();
context.Blogs.Add(new BlogContext.Blog());
context.SaveChanges();
AssertTransactionHistoryCount(context, 1);
Assert.Equal(1, transactionHandler.TransactionContext.ChangeTracker.Entries<TransactionRow>().Count());
}
}
finally
{
DbInterception.Remove(failingTransactionInterceptor);
MutableResolver.ClearResolvers();
}
DbDispatchersHelpers.AssertNoInterceptors();
}
[Fact]
public void CommitFailureHandler_ClearTransactionHistory_uses_ExecutionStrategy()
{
CommitFailureHandler_with_ExecutionStrategy_test(
(c, executionStrategyMock) =>
{
((MyCommitFailureHandler)c.TransactionHandler).ClearTransactionHistory();
executionStrategyMock.Verify(e => e.Execute(It.IsAny<Func<int>>()), Times.Exactly(4));
Assert.Empty(((MyCommitFailureHandler)c.TransactionHandler).TransactionContext.ChangeTracker.Entries<TransactionRow>());
});
}
[Fact]
public void CommitFailureHandler_ClearTransactionHistory_does_not_catch_exceptions()
{
var failingTransactionInterceptor = new FailingTransactionInterceptor();
DbInterception.Add(failingTransactionInterceptor);
try
{
CommitFailureHandler_with_ExecutionStrategy_test(
(c, executionStrategyMock) =>
{
MutableResolver.AddResolver<Func<IDbExecutionStrategy>>(
key => (Func<IDbExecutionStrategy>)(() => new SimpleExecutionStrategy()));
failingTransactionInterceptor.ShouldFailTimes = 1;
failingTransactionInterceptor.ShouldRollBack = true;
Assert.Throws<EntityException>(
() => ((MyCommitFailureHandler)c.TransactionHandler).ClearTransactionHistory());
MutableResolver.ClearResolvers();
AssertTransactionHistoryCount(c, 1);
((MyCommitFailureHandler)c.TransactionHandler).ClearTransactionHistory();
AssertTransactionHistoryCount(c, 0);
});
}
finally
{
DbInterception.Remove(failingTransactionInterceptor);
}
}
[Fact]
public void CommitFailureHandler_PruneTransactionHistory_uses_ExecutionStrategy()
{
CommitFailureHandler_with_ExecutionStrategy_test(
(c, executionStrategyMock) =>
{
((MyCommitFailureHandler)c.TransactionHandler).PruneTransactionHistory();
executionStrategyMock.Verify(e => e.Execute(It.IsAny<Func<int>>()), Times.Exactly(4));
Assert.Empty(((MyCommitFailureHandler)c.TransactionHandler).TransactionContext.ChangeTracker.Entries<TransactionRow>());
});
}
[Fact]
public void CommitFailureHandler_PruneTransactionHistory_does_not_catch_exceptions()
{
var failingTransactionInterceptor = new FailingTransactionInterceptor();
DbInterception.Add(failingTransactionInterceptor);
try
{
CommitFailureHandler_with_ExecutionStrategy_test(
(c, executionStrategyMock) =>
{
MutableResolver.AddResolver<Func<IDbExecutionStrategy>>(
key => (Func<IDbExecutionStrategy>)(() => new SimpleExecutionStrategy()));
failingTransactionInterceptor.ShouldFailTimes = 1;
failingTransactionInterceptor.ShouldRollBack = true;
Assert.Throws<EntityException>(
() => ((MyCommitFailureHandler)c.TransactionHandler).PruneTransactionHistory());
MutableResolver.ClearResolvers();
AssertTransactionHistoryCount(c, 1);
((MyCommitFailureHandler)c.TransactionHandler).PruneTransactionHistory();
AssertTransactionHistoryCount(c, 0);
});
}
finally
{
DbInterception.Remove(failingTransactionInterceptor);
}
}
#if !NET40
[Fact]
public void CommitFailureHandler_ClearTransactionHistoryAsync_uses_ExecutionStrategy()
{
CommitFailureHandler_with_ExecutionStrategy_test(
(c, executionStrategyMock) =>
{
((MyCommitFailureHandler)c.TransactionHandler).ClearTransactionHistoryAsync().Wait();
executionStrategyMock.Verify(
e => e.ExecuteAsync(It.IsAny<Func<Task<int>>>(), It.IsAny<CancellationToken>()), Times.Once());
Assert.Empty(((MyCommitFailureHandler)c.TransactionHandler).TransactionContext.ChangeTracker.Entries<TransactionRow>());
});
}
[Fact]
public void CommitFailureHandler_ClearTransactionHistoryAsync_does_not_catch_exceptions()
{
var failingTransactionInterceptor = new FailingTransactionInterceptor();
DbInterception.Add(failingTransactionInterceptor);
try
{
CommitFailureHandler_with_ExecutionStrategy_test(
(c, executionStrategyMock) =>
{
MutableResolver.AddResolver<Func<IDbExecutionStrategy>>(
key => (Func<IDbExecutionStrategy>)(() => new SimpleExecutionStrategy()));
failingTransactionInterceptor.ShouldFailTimes = 1;
failingTransactionInterceptor.ShouldRollBack = true;
Assert.Throws<EntityException>(
() => ExceptionHelpers.UnwrapAggregateExceptions(
() => ((MyCommitFailureHandler)c.TransactionHandler).ClearTransactionHistoryAsync().Wait()));
MutableResolver.ClearResolvers();
AssertTransactionHistoryCount(c, 1);
((MyCommitFailureHandler)c.TransactionHandler).ClearTransactionHistoryAsync().Wait();
AssertTransactionHistoryCount(c, 0);
});
}
finally
{
DbInterception.Remove(failingTransactionInterceptor);
}
}
[Fact]
public void CommitFailureHandler_PruneTransactionHistoryAsync_uses_ExecutionStrategy()
{
CommitFailureHandler_with_ExecutionStrategy_test(
(c, executionStrategyMock) =>
{
((MyCommitFailureHandler)c.TransactionHandler).PruneTransactionHistoryAsync().Wait();
executionStrategyMock.Verify(
e => e.ExecuteAsync(It.IsAny<Func<Task<int>>>(), It.IsAny<CancellationToken>()), Times.Once());
Assert.Empty(((MyCommitFailureHandler)c.TransactionHandler).TransactionContext.ChangeTracker.Entries<TransactionRow>());
});
}
[Fact]
public void CommitFailureHandler_PruneTransactionHistoryAsync_does_not_catch_exceptions()
{
var failingTransactionInterceptor = new FailingTransactionInterceptor();
DbInterception.Add(failingTransactionInterceptor);
try
{
CommitFailureHandler_with_ExecutionStrategy_test(
(c, executionStrategyMock) =>
{
MutableResolver.AddResolver<Func<IDbExecutionStrategy>>(
key => (Func<IDbExecutionStrategy>)(() => new SimpleExecutionStrategy()));
failingTransactionInterceptor.ShouldFailTimes = 1;
failingTransactionInterceptor.ShouldRollBack = true;
Assert.Throws<EntityException>(
() => ExceptionHelpers.UnwrapAggregateExceptions(
() => ((MyCommitFailureHandler)c.TransactionHandler).PruneTransactionHistoryAsync().Wait()));
MutableResolver.ClearResolvers();
AssertTransactionHistoryCount(c, 1);
((MyCommitFailureHandler)c.TransactionHandler).PruneTransactionHistoryAsync().Wait();
AssertTransactionHistoryCount(c, 0);
});
}
finally
{
DbInterception.Remove(failingTransactionInterceptor);
}
}
#endif
private void CommitFailureHandler_with_ExecutionStrategy_test(
Action<ObjectContext, Mock<TestSqlAzureExecutionStrategy>> pruneAndVerify)
{
MutableResolver.AddResolver<Func<TransactionHandler>>(
new TransactionHandlerResolver(() => new MyCommitFailureHandler(c => new TransactionContext(c)), null, null));
var executionStrategyMock = new Mock<TestSqlAzureExecutionStrategy> { CallBase = true };
MutableResolver.AddResolver<Func<IDbExecutionStrategy>>(
key => (Func<IDbExecutionStrategy>)(() => executionStrategyMock.Object));
try
{
using (var context = new BlogContextCommit())
{
context.Database.Delete();
Assert.Equal(1, context.Blogs.Count());
context.Blogs.Add(new BlogContext.Blog());
context.SaveChanges();
AssertTransactionHistoryCount(context, 1);
executionStrategyMock.Verify(e => e.Execute(It.IsAny<Func<int>>()), Times.Exactly(3));
#if !NET40
executionStrategyMock.Verify(
e => e.ExecuteAsync(It.IsAny<Func<Task<int>>>(), It.IsAny<CancellationToken>()), Times.Never());
#endif
var objectContext = ((IObjectContextAdapter)context).ObjectContext;
pruneAndVerify(objectContext, executionStrategyMock);
using (var transactionContext = new TransactionContext(context.Database.Connection))
{
Assert.Equal(0, transactionContext.Transactions.Count());
}
}
}
finally
{
MutableResolver.ClearResolvers();
}
}
private void AssertTransactionHistoryCount(DbContext context, int count)
{
AssertTransactionHistoryCount(((IObjectContextAdapter)context).ObjectContext, count);
}
private void AssertTransactionHistoryCount(ObjectContext context, int count)
{
using (var transactionContext = new TransactionContext(((EntityConnection)context.Connection).StoreConnection))
{
Assert.Equal(count, transactionContext.Transactions.Count());
}
}
public class SimpleExecutionStrategy : IDbExecutionStrategy
{
public bool RetriesOnFailure
{
get { return false; }
}
public virtual void Execute(Action operation)
{
operation();
}
public virtual TResult Execute<TResult>(Func<TResult> operation)
{
return operation();
}
#if !NET40
public virtual Task ExecuteAsync(Func<Task> operation, CancellationToken cancellationToken)
{
return operation();
}
public virtual Task<TResult> ExecuteAsync<TResult>(Func<Task<TResult>> operation, CancellationToken cancellationToken)
{
return operation();
}
#endif
}
public class MyCommitFailureHandler : CommitFailureHandler
{
public MyCommitFailureHandler(Func<DbConnection, TransactionContext> transactionContextFactory)
: base(transactionContextFactory)
{
}
public new void MarkTransactionForPruning(TransactionRow transaction)
{
base.MarkTransactionForPruning(transaction);
}
public new TransactionContext TransactionContext
{
get { return base.TransactionContext; }
}
public new virtual int PruningLimit
{
get { return base.PruningLimit; }
}
}
[Fact]
[UseDefaultExecutionStrategy]
public void CommitFailureHandler_supports_nested_transactions()
{
MutableResolver.AddResolver<Func<TransactionHandler>>(
new TransactionHandlerResolver(() => new CommitFailureHandler(), null, null));
try
{
using (var context = new BlogContextCommit())
{
context.Database.Delete();
Assert.Equal(1, context.Blogs.Count());
context.Blogs.Add(new BlogContext.Blog());
using (var transaction = context.Database.BeginTransaction())
{
using (var innerContext = new BlogContextCommit())
{
using (var innerTransaction = innerContext.Database.BeginTransaction())
{
Assert.Equal(1, innerContext.Blogs.Count());
innerContext.Blogs.Add(new BlogContext.Blog());
innerContext.SaveChanges();
innerTransaction.Commit();
}
}
context.SaveChanges();
transaction.Commit();
}
}
using (var context = new BlogContextCommit())
{
Assert.Equal(3, context.Blogs.Count());
}
}
finally
{
MutableResolver.ClearResolvers();
}
DbDispatchersHelpers.AssertNoInterceptors();
}
[Fact]
public void BuildDatabaseInitializationScript_can_be_used_to_initialize_the_database()
{
MutableResolver.AddResolver<Func<TransactionHandler>>(
new TransactionHandlerResolver(() => new CommitFailureHandler(), null, null));
MutableResolver.AddResolver<Func<IDbExecutionStrategy>>(
key => (Func<IDbExecutionStrategy>)(() => new TestSqlAzureExecutionStrategy()));
try
{
using (var context = new BlogContextCommit())
{
context.Database.Delete();
Assert.Equal(1, context.Blogs.Count());
}
MutableResolver.AddResolver<Func<TransactionHandler>>(
new TransactionHandlerResolver(() => new CommitFailureHandler(c => new TransactionContextNoInit(c)), null, null));
using (var context = new BlogContextCommit())
{
context.Blogs.Add(new BlogContext.Blog());
Assert.Throws<EntityException>(() => context.SaveChanges());
context.Database.ExecuteSqlCommand(
TransactionalBehavior.DoNotEnsureTransaction,
((IObjectContextAdapter)context).ObjectContext.TransactionHandler.BuildDatabaseInitializationScript());
context.SaveChanges();
}
using (var context = new BlogContextCommit())
{
Assert.Equal(2, context.Blogs.Count());
}
}
finally
{
MutableResolver.ClearResolvers();
}
DbDispatchersHelpers.AssertNoInterceptors();
}
[Fact]
public void BuildDatabaseInitializationScript_can_be_used_to_initialize_the_database_if_no_migration_generator()
{
var mockDbProviderServiceResolver = new Mock<IDbDependencyResolver>();
mockDbProviderServiceResolver
.Setup(r => r.GetService(It.IsAny<Type>(), It.IsAny<string>()))
.Returns(SqlProviderServices.Instance);
MutableResolver.AddResolver<DbProviderServices>(mockDbProviderServiceResolver.Object);
var mockDbProviderFactoryResolver = new Mock<IDbDependencyResolver>();
mockDbProviderFactoryResolver
.Setup(r => r.GetService(It.IsAny<Type>(), It.IsAny<string>()))
.Returns(SqlClientFactory.Instance);
MutableResolver.AddResolver<DbProviderFactory>(mockDbProviderFactoryResolver.Object);
BuildDatabaseInitializationScript_can_be_used_to_initialize_the_database();
}
[Fact]
public void FromContext_returns_the_current_handler()
{
MutableResolver.AddResolver<Func<TransactionHandler>>(
new TransactionHandlerResolver(() => new CommitFailureHandler(), null, null));
try
{
using (var context = new BlogContextCommit())
{
context.Database.Delete();
var commitFailureHandler = CommitFailureHandler.FromContext(((IObjectContextAdapter)context).ObjectContext);
Assert.IsType<CommitFailureHandler>(commitFailureHandler);
Assert.Same(commitFailureHandler, CommitFailureHandler.FromContext(context));
}
}
finally
{
MutableResolver.ClearResolvers();
}
}
[Fact]
public void TransactionHandler_is_disposed_even_if_the_context_is_not()
{
var context = new BlogContextCommit();
context.Database.Delete();
Assert.Equal(1, context.Blogs.Count());
var weakDbContext = new WeakReference(context);
var weakObjectContext = new WeakReference(((IObjectContextAdapter)context).ObjectContext);
var weakTransactionHandler = new WeakReference(((IObjectContextAdapter)context).ObjectContext.TransactionHandler);
context = null;
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.False(weakDbContext.IsAlive);
Assert.False(weakObjectContext.IsAlive);
DbDispatchersHelpers.AssertNoInterceptors();
// Need a second pass as the TransactionHandler is removed from the interceptors in the ObjectContext finalizer
GC.Collect();
Assert.False(weakTransactionHandler.IsAlive);
}
public class TransactionContextNoInit : TransactionContext
{
static TransactionContextNoInit()
{
Database.SetInitializer<TransactionContextNoInit>(null);
}
public TransactionContextNoInit(DbConnection connection)
: base(connection)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<TransactionRow>()
.ToTable("TransactionContextNoInit");
}
}
public class FailingTransactionInterceptor : IDbTransactionInterceptor
{
private int _timesToFail;
private int _shouldFailTimes;
public int ShouldFailTimes
{
get { return _shouldFailTimes; }
set
{
_shouldFailTimes = value;
_timesToFail = value;
}
}
public bool ShouldRollBack;
public FailingTransactionInterceptor()
{
_timesToFail = ShouldFailTimes;
}
public void ConnectionGetting(DbTransaction transaction, DbTransactionInterceptionContext<DbConnection> interceptionContext)
{
}
public void ConnectionGot(DbTransaction transaction, DbTransactionInterceptionContext<DbConnection> interceptionContext)
{
}
public void IsolationLevelGetting(
DbTransaction transaction, DbTransactionInterceptionContext<IsolationLevel> interceptionContext)
{
}
public void IsolationLevelGot(DbTransaction transaction, DbTransactionInterceptionContext<IsolationLevel> interceptionContext)
{
}
public virtual void Committing(DbTransaction transaction, DbTransactionInterceptionContext interceptionContext)
{
if (_timesToFail-- > 0)
{
if (ShouldRollBack)
{
transaction.Rollback();
}
else
{
transaction.Commit();
}
interceptionContext.Exception = new TimeoutException();
}
else
{
_timesToFail = ShouldFailTimes;
}
}
public void Committed(DbTransaction transaction, DbTransactionInterceptionContext interceptionContext)
{
if (interceptionContext.Exception != null)
{
_timesToFail--;
}
}
public void Disposing(DbTransaction transaction, DbTransactionInterceptionContext interceptionContext)
{
}
public void Disposed(DbTransaction transaction, DbTransactionInterceptionContext interceptionContext)
{
}
public void RollingBack(DbTransaction transaction, DbTransactionInterceptionContext interceptionContext)
{
}
public void RolledBack(DbTransaction transaction, DbTransactionInterceptionContext interceptionContext)
{
}
}
public class BlogContextCommit : BlogContext
{
static BlogContextCommit()
{
Database.SetInitializer<BlogContextCommit>(new BlogInitializer());
}
}
}
}
| |
/*
* This file is part of the OpenKinect Project. http://www.openkinect.org
*
* Copyright (c) 2010 individual OpenKinect contributors. See the CONTRIB file
* for details.
*
* This code is licensed to you under the terms of the Apache License, version
* 2.0, or, at your option, the terms of the GNU General Public License,
* version 2.0. See the APACHE20 and GPL2 files for the text of the licenses,
* or the following URLs:
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.gnu.org/licenses/gpl-2.0.txt
*
* If you redistribute this file in source form, modified or unmodified, you
* may:
* 1) Leave this header intact and distribute it under the same terms,
* accompanying it with the APACHE20 and GPL20 files, or
* 2) Delete the Apache 2.0 clause and accompany it with the GPL2 file, or
* 3) Delete the GPL v2 clause and accompany it with the APACHE20 file
* In all cases you must keep the copyright notice intact and include a copy
* of the CONTRIB file.
*
* Binary distributions must follow the binary distribution requirements of
* either License.
*/
using System;
using System.Threading;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace freenect
{
/// <summary>
/// Provides access to native libfreenect calls. These are "ugly" calls used internally
/// in the wrapper.
/// </summary>
///
///
class KinectNative
{
/// <summary>
/// Main freenect context. There is one per session.
/// </summary>
private static IntPtr freenectContext = IntPtr.Zero;
/// <summary>
/// Map between native pointers to actual Kinect devices
/// </summary>
private static Dictionary<IntPtr, Kinect> deviceMap = new Dictionary<IntPtr, Kinect>();
/// <summary>
/// Callback delegate for log messages coming in from the C library.
/// </summary>
private static FreenectLogCallback LogCallback = new FreenectLogCallback(Kinect.LogCallback);
/// <summary>
/// Gets a freenect context to work with.
/// </summary>
public static IntPtr Context
{
get
{
// Make sure we have a context
if(KinectNative.freenectContext == IntPtr.Zero)
{
KinectNative.InitializeContext();
}
// Return it
return KinectNative.freenectContext;
}
}
/// <summary>
/// Shuts down the context and closes any open devices.
/// </summary>
public static void ShutdownContext()
{
// Close all devices
foreach(Kinect device in KinectNative.deviceMap.Values)
{
device.Close();
}
// Shutdown context
int result = KinectNative.freenect_shutdown(KinectNative.freenectContext);
if(result != 0)
{
throw new Exception("Could not shutdown freenect context. Error Code:" + result);
}
// Dispose pointer
KinectNative.freenectContext = IntPtr.Zero;
}
/// <summary>
/// Gets a kinect device given it's native pointer. This is
/// useful for callbacks.
/// </summary>
/// <param name="pointer">
/// A <see cref="IntPtr"/>
/// </param>
/// <returns>
/// A <see cref="Kinect"/>
/// </returns>
public static Kinect GetDevice(IntPtr pointer)
{
if(KinectNative.deviceMap.ContainsKey(pointer) == false)
{
return null;
}
return KinectNative.deviceMap[pointer];
}
/// <summary>
/// Registers a device and its native pointer
/// </summary>
/// <param name="pointer">
/// A <see cref="IntPtr"/>
/// </param>
/// <param name="device">
/// A <see cref="Kinect"/>
/// </param>
public static void RegisterDevice(IntPtr pointer, Kinect device)
{
if(KinectNative.deviceMap.ContainsKey(pointer))
{
KinectNative.deviceMap.Remove(pointer);
}
KinectNative.deviceMap.Add(pointer, device);
}
/// <summary>
/// Unregister the device pointed to by the specified native pointer.
/// </summary>
/// <param name="pointer">
/// A <see cref="IntPtr"/>
/// </param>
public static void UnregisterDevice(IntPtr pointer)
{
if(KinectNative.deviceMap.ContainsKey(pointer))
{
KinectNative.deviceMap.Remove(pointer);
}
}
/// <summary>
/// Initializes the freenect context
/// </summary>
private static void InitializeContext()
{
int result = KinectNative.freenect_init(ref KinectNative.freenectContext, IntPtr.Zero);
if(result != 0)
{
throw new Exception("Could not initialize freenect context. Error Code:" + result);
}
// Set callbacks for logging
KinectNative.freenect_set_log_callback(KinectNative.freenectContext, LogCallback);
}
[DllImport("freenect", CallingConvention=CallingConvention.Cdecl)]
public static extern int freenect_init(ref IntPtr context, IntPtr freenectUSBContext);
[DllImport("freenect", CallingConvention=CallingConvention.Cdecl)]
public static extern int freenect_shutdown(IntPtr context);
[DllImport("freenect", CallingConvention=CallingConvention.Cdecl)]
public static extern void freenect_set_log_level(IntPtr context, LoggingLevel level);
[DllImport("freenect", CallingConvention=CallingConvention.Cdecl)]
public static extern void freenect_set_log_callback(IntPtr context, FreenectLogCallback callback);
[DllImport("freenect", CallingConvention=CallingConvention.Cdecl)]
public static extern int freenect_process_events(IntPtr context);
[DllImport("freenect", CallingConvention=CallingConvention.Cdecl)]
public static extern int freenect_num_devices(IntPtr context);
[DllImport("freenect", CallingConvention=CallingConvention.Cdecl)]
public static extern int freenect_open_device(IntPtr context, ref IntPtr device, int index);
[DllImport("freenect", CallingConvention=CallingConvention.Cdecl)]
public static extern int freenect_close_device(IntPtr device);
[DllImport("freenect", CallingConvention=CallingConvention.Cdecl)]
public static extern void freenect_set_depth_callback(IntPtr device, FreenectCameraDataCallback callback);
[DllImport("freenect", CallingConvention=CallingConvention.Cdecl)]
public static extern void freenect_set_video_callback(IntPtr device, FreenectCameraDataCallback callback);
[DllImport("freenect", CallingConvention=CallingConvention.Cdecl)]
public static extern int freenect_set_depth_buffer(IntPtr device, IntPtr buf);
[DllImport("freenect", CallingConvention=CallingConvention.Cdecl)]
public static extern int freenect_set_video_buffer(IntPtr device, IntPtr buf);
[DllImport("freenect", CallingConvention=CallingConvention.Cdecl)]
public static extern int freenect_start_depth(IntPtr device);
[DllImport("freenect", CallingConvention=CallingConvention.Cdecl)]
public static extern int freenect_start_video(IntPtr device);
[DllImport("freenect", CallingConvention=CallingConvention.Cdecl)]
public static extern int freenect_stop_depth(IntPtr device);
[DllImport("freenect", CallingConvention=CallingConvention.Cdecl)]
public static extern int freenect_stop_video(IntPtr device);
[DllImport("freenect", CallingConvention=CallingConvention.Cdecl)]
public static extern int freenect_update_tilt_state(IntPtr device);
[DllImport("freenect", CallingConvention=CallingConvention.Cdecl)]
public static extern IntPtr freenect_get_tilt_state(IntPtr device);
[DllImport("freenect", CallingConvention=CallingConvention.Cdecl)]
public static extern double freenect_get_tilt_degs(IntPtr device);
[DllImport("freenect", CallingConvention=CallingConvention.Cdecl)]
public static extern int freenect_set_tilt_degs(IntPtr device, double angle);
[DllImport("freenect", CallingConvention=CallingConvention.Cdecl)]
public static extern MotorTiltStatus freenect_get_tilt_status(IntPtr device);
[DllImport("freenect", CallingConvention=CallingConvention.Cdecl)]
public static extern int freenect_set_led(IntPtr device, LEDColor color);
[DllImport("freenect", CallingConvention=CallingConvention.Cdecl)]
public static extern int freenect_get_video_mode_count(IntPtr device);
[DllImport("freenect", CallingConvention=CallingConvention.Cdecl)]
public static extern FreenectFrameMode freenect_get_video_mode(int modeNum);
[DllImport("freenect", CallingConvention=CallingConvention.Cdecl)]
public static extern FreenectFrameMode freenect_get_current_video_mode();
[DllImport("freenect", CallingConvention=CallingConvention.Cdecl)]
public static extern FreenectFrameMode freenect_find_video_mode(Resolution resolution, VideoFormat videoFormat);
[DllImport("freenect", CallingConvention=CallingConvention.Cdecl)]
public static extern int freenect_set_video_mode(IntPtr device, FreenectFrameMode mode);
[DllImport("freenect", CallingConvention=CallingConvention.Cdecl)]
public static extern int freenect_get_depth_mode_count(IntPtr device);
[DllImport("freenect", CallingConvention=CallingConvention.Cdecl)]
public static extern FreenectFrameMode freenect_get_depth_mode(int modeNum);
[DllImport("freenect", CallingConvention=CallingConvention.Cdecl)]
public static extern FreenectFrameMode freenect_get_current_depth_mode();
[DllImport("freenect", CallingConvention=CallingConvention.Cdecl)]
public static extern FreenectFrameMode freenect_find_depth_mode(Resolution resolution, DepthFormat depthFormat);
[DllImport("freenect", CallingConvention=CallingConvention.Cdecl)]
public static extern int freenect_set_depth_mode(IntPtr device, FreenectFrameMode mode);
}
/// <summary>
/// Frame capture settings for all video/depth feeds
/// </summary>
[StructLayout(LayoutKind.Explicit)]
internal struct FreenectFrameMode
{
[FieldOffset(0)]
public UInt32 Reserved;
[FieldOffset(4)]
public Resolution Resolution;
[FieldOffset(8)]
public VideoFormat VideoFormat;
[FieldOffset(8)]
public DepthFormat DepthFormat;
[FieldOffset(12)]
public int Bytes;
[FieldOffset(16)]
public short Width;
[FieldOffset(18)]
public short Height;
[FieldOffset(20)]
public byte DataBitsPerPixel;
[FieldOffset(21)]
public byte PaddingBitsPerPixel;
[FieldOffset(22)]
public byte Framerate;
[FieldOffset(23)]
public byte IsValid;
}
/// <summary>
/// Device tilt state values. This holds stuff like accel and tilt status
/// </summary>
internal struct FreenectTiltState
{
public Int16 AccelerometerX;
public Int16 AccelerometerY;
public Int16 AccelerometerZ;
public SByte TiltAngle;
public MotorTiltStatus TiltStatus;
}
/// <summary>
/// "Native" callback for freelect library logging
/// </summary>
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void FreenectLogCallback(IntPtr device, LoggingLevel logLevel, string message);
/// <summary>
/// "Native" callback for camera data
/// </summary>
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void FreenectCameraDataCallback(IntPtr device, IntPtr data, UInt32 timestamp);
}
| |
// 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.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using OleConstants = Microsoft.VisualStudio.OLE.Interop.Constants;
using VsCommands = Microsoft.VisualStudio.VSConstants.VSStd97CmdID;
using VsCommands2K = Microsoft.VisualStudio.VSConstants.VSStd2KCmdID;
using Microsoft.VisualStudioTools.Infrastructure;
#if DEV14_OR_LATER
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.Imaging.Interop;
#endif
namespace Microsoft.VisualStudioTools.Project {
internal class FolderNode : HierarchyNode, IDiskBasedNode {
#region ctors
/// <summary>
/// Constructor for the FolderNode
/// </summary>
/// <param name="root">Root node of the hierarchy</param>
/// <param name="relativePath">relative path from root i.e.: "NewFolder1\\NewFolder2\\NewFolder3</param>
/// <param name="element">Associated project element</param>
public FolderNode(ProjectNode root, ProjectElement element)
: base(root, element) {
}
#endregion
#region overridden properties
public override bool CanOpenCommandPrompt {
get {
return true;
}
}
internal override string FullPathToChildren {
get {
return Url;
}
}
public override int SortPriority {
get { return DefaultSortOrderNode.FolderNode; }
}
/// <summary>
/// This relates to the SCC glyph
/// </summary>
public override VsStateIcon StateIconIndex {
get {
// The SCC manager does not support being asked for the state icon of a folder (result of the operation is undefined)
return VsStateIcon.STATEICON_NOSTATEICON;
}
}
public override bool CanAddFiles {
get {
return true;
}
}
#endregion
#region overridden methods
protected override NodeProperties CreatePropertiesObject() {
return new FolderNodeProperties(this);
}
protected internal override void DeleteFromStorage(string path) {
this.DeleteFolder(path);
}
/// <summary>
/// Get the automation object for the FolderNode
/// </summary>
/// <returns>An instance of the Automation.OAFolderNode type if succeeded</returns>
public override object GetAutomationObject() {
if (this.ProjectMgr == null || this.ProjectMgr.IsClosed) {
return null;
}
return new Automation.OAFolderItem(this.ProjectMgr.GetAutomationObject() as Automation.OAProject, this);
}
#if DEV14_OR_LATER
protected override bool SupportsIconMonikers {
get { return true; }
}
protected override ImageMoniker GetIconMoniker(bool open) {
return open ? KnownMonikers.FolderOpened : KnownMonikers.FolderClosed;
}
#else
public override object GetIconHandle(bool open) {
return ProjectMgr.GetIconHandleByName(open ?
ProjectNode.ImageName.OpenFolder :
ProjectNode.ImageName.Folder
);
}
#endif
/// <summary>
/// Rename Folder
/// </summary>
/// <param name="label">new Name of Folder</param>
/// <returns>VSConstants.S_OK, if succeeded</returns>
public override int SetEditLabel(string label) {
if (IsBeingCreated) {
return FinishFolderAdd(label, false);
} else {
if (String.Equals(CommonUtils.GetFileOrDirectoryName(Url), label, StringComparison.Ordinal)) {
// Label matches current Name
return VSConstants.S_OK;
}
string newPath = CommonUtils.GetAbsoluteDirectoryPath(CommonUtils.GetParent(Url), label);
// Verify that No Directory/file already exists with the new name among current children
var existingChild = Parent.FindImmediateChildByName(label);
if (existingChild != null && existingChild != this) {
return ShowFileOrFolderAlreadyExistsErrorMessage(newPath);
}
// Verify that No Directory/file already exists with the new name on disk.
// Unless the path exists because it is the path to the source file also.
if ((Directory.Exists(newPath) || File.Exists(newPath)) && !CommonUtils.IsSamePath(Url, newPath)) {
return ShowFileOrFolderAlreadyExistsErrorMessage(newPath);
}
if (!ProjectMgr.Tracker.CanRenameItem(Url, newPath, VSRENAMEFILEFLAGS.VSRENAMEFILEFLAGS_Directory)) {
return VSConstants.S_OK;
}
}
try {
var oldTriggerFlag = this.ProjectMgr.EventTriggeringFlag;
ProjectMgr.EventTriggeringFlag |= ProjectNode.EventTriggering.DoNotTriggerTrackerQueryEvents;
try {
RenameFolder(label);
} finally {
ProjectMgr.EventTriggeringFlag = oldTriggerFlag;
}
//Refresh the properties in the properties window
IVsUIShell shell = this.ProjectMgr.GetService(typeof(SVsUIShell)) as IVsUIShell;
Utilities.CheckNotNull(shell, "Could not get the UI shell from the project");
ErrorHandler.ThrowOnFailure(shell.RefreshPropertyBrowser(0));
// Notify the listeners that the name of this folder is changed. This will
// also force a refresh of the SolutionExplorer's node.
ProjectMgr.OnPropertyChanged(this, (int)__VSHPROPID.VSHPROPID_Caption, 0);
} catch (Exception e) {
if (e.IsCriticalException()) {
throw;
}
throw new InvalidOperationException(SR.GetString(SR.RenameFolder, e.Message));
}
return VSConstants.S_OK;
}
internal static string PathTooLongMessage {
get {
return SR.GetString(SR.PathTooLongShortMessage);
}
}
private int FinishFolderAdd(string label, bool wasCancelled) {
// finish creation
string filename = label.Trim();
if (filename == "." || filename == "..") {
Debug.Assert(!wasCancelled); // cancelling leaves us with a valid label
NativeMethods.SetErrorDescription("{0} is an invalid filename.", filename);
return VSConstants.E_FAIL;
}
var path = Path.Combine(Parent.FullPathToChildren, label);
if (path.Length >= NativeMethods.MAX_FOLDER_PATH) {
if (wasCancelled) {
// cancelling an edit label doesn't result in the error
// being displayed, so we'll display one for the user.
Utilities.ShowMessageBox(
ProjectMgr.Site,
null,
PathTooLongMessage,
OLEMSGICON.OLEMSGICON_CRITICAL,
OLEMSGBUTTON.OLEMSGBUTTON_OK,
OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST
);
} else {
NativeMethods.SetErrorDescription(PathTooLongMessage);
}
return VSConstants.E_FAIL;
}
if (filename == Caption || Parent.FindImmediateChildByName(filename) == null) {
if (ProjectMgr.QueryFolderAdd(Parent, path)) {
Directory.CreateDirectory(path);
IsBeingCreated = false;
var relativePath = CommonUtils.GetRelativeDirectoryPath(
ProjectMgr.ProjectHome,
CommonUtils.GetAbsoluteDirectoryPath(CommonUtils.GetParent(Url), label)
);
this.ItemNode.Rename(relativePath);
ProjectMgr.OnItemDeleted(this);
this.Parent.RemoveChild(this);
ProjectMgr.Site.GetUIThread().MustBeCalledFromUIThread();
this.ID = ProjectMgr.ItemIdMap.Add(this);
this.Parent.AddChild(this);
ExpandItem(EXPANDFLAGS.EXPF_SelectItem);
ProjectMgr.Tracker.OnFolderAdded(
path,
VSADDDIRECTORYFLAGS.VSADDDIRECTORYFLAGS_NoFlags
);
}
} else {
Debug.Assert(!wasCancelled); // we choose a label which didn't exist when we started the edit
// Set error: folder already exists
NativeMethods.SetErrorDescription("The folder {0} already exists.", filename);
return VSConstants.E_FAIL;
}
return VSConstants.S_OK;
}
public override int MenuCommandId {
get { return VsMenus.IDM_VS_CTXT_FOLDERNODE; }
}
public override Guid ItemTypeGuid {
get {
return VSConstants.GUID_ItemType_PhysicalFolder;
}
}
public override string Url {
get {
return CommonUtils.EnsureEndSeparator(ItemNode.Url);
}
}
public override string Caption {
get {
// it might have a backslash at the end...
// and it might consist of Grandparent\parent\this\
return CommonUtils.GetFileOrDirectoryName(Url);
}
}
public override string GetMkDocument() {
Debug.Assert(!string.IsNullOrEmpty(this.Url), "No url specified for this node");
Debug.Assert(Path.IsPathRooted(this.Url), "Url should not be a relative path");
return this.Url;
}
/// <summary>
/// Recursively walks the folder nodes and redraws the state icons
/// </summary>
protected internal override void UpdateSccStateIcons() {
for (HierarchyNode child = this.FirstChild; child != null; child = child.NextSibling) {
child.UpdateSccStateIcons();
}
}
internal override int QueryStatusOnNode(Guid cmdGroup, uint cmd, IntPtr pCmdText, ref QueryStatusResult result) {
if (cmdGroup == VsMenus.guidStandardCommandSet97) {
switch ((VsCommands)cmd) {
case VsCommands.Copy:
case VsCommands.Paste:
case VsCommands.Cut:
case VsCommands.Rename:
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
return VSConstants.S_OK;
case VsCommands.NewFolder:
if (!IsNonMemberItem) {
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
return VSConstants.S_OK;
}
break;
}
} else if (cmdGroup == VsMenus.guidStandardCommandSet2K) {
if ((VsCommands2K)cmd == VsCommands2K.EXCLUDEFROMPROJECT) {
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
return VSConstants.S_OK;
}
} else if (cmdGroup != ProjectMgr.SharedCommandGuid) {
return (int)OleConstants.OLECMDERR_E_UNKNOWNGROUP;
}
return base.QueryStatusOnNode(cmdGroup, cmd, pCmdText, ref result);
}
internal override bool CanDeleteItem(__VSDELETEITEMOPERATION deleteOperation) {
if (deleteOperation == __VSDELETEITEMOPERATION.DELITEMOP_DeleteFromStorage) {
return this.ProjectMgr.CanProjectDeleteItems;
}
return false;
}
protected internal override void GetSccFiles(IList<string> files, IList<tagVsSccFilesFlags> flags) {
for (HierarchyNode n = this.FirstChild; n != null; n = n.NextSibling) {
n.GetSccFiles(files, flags);
}
}
protected internal override void GetSccSpecialFiles(string sccFile, IList<string> files, IList<tagVsSccFilesFlags> flags) {
for (HierarchyNode n = this.FirstChild; n != null; n = n.NextSibling) {
n.GetSccSpecialFiles(sccFile, files, flags);
}
}
#endregion
#region virtual methods
/// <summary>
/// Override if your node is not a file system folder so that
/// it does nothing or it deletes it from your storage location.
/// </summary>
/// <param name="path">Path to the folder to delete</param>
public virtual void DeleteFolder(string path) {
if (Directory.Exists(path)) {
try {
try {
Directory.Delete(path, true);
} catch (UnauthorizedAccessException) {
// probably one or more files are read only
foreach (var file in Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories)) {
// We will ignore all exceptions here and rethrow when
// we retry the Directory.Delete.
try {
File.SetAttributes(file, FileAttributes.Normal);
} catch (UnauthorizedAccessException) {
} catch (IOException) {
}
}
Directory.Delete(path, true);
}
} catch (IOException ioEx) {
// re-throw with a friendly path
throw new IOException(ioEx.Message.Replace(path, Caption));
}
}
}
/// <summary>
/// creates the physical directory for a folder node
/// Override if your node does not use file system folder
/// </summary>
public virtual void CreateDirectory() {
if (Directory.Exists(this.Url) == false) {
Directory.CreateDirectory(this.Url);
}
}
/// <summary>
/// Creates a folder nodes physical directory
/// Override if your node does not use file system folder
/// </summary>
/// <param name="newName"></param>
/// <returns></returns>
public virtual void CreateDirectory(string newName) {
if (String.IsNullOrEmpty(newName)) {
throw new ArgumentException(SR.GetString(SR.ParameterCannotBeNullOrEmpty), "newName");
}
// on a new dir && enter, we get called with the same name (so do nothing if name is the same
string strNewDir = CommonUtils.GetAbsoluteDirectoryPath(CommonUtils.GetParent(Url), newName);
if (!CommonUtils.IsSameDirectory(Url, strNewDir)) {
if (Directory.Exists(strNewDir)) {
throw new InvalidOperationException(SR.GetString(SR.DirectoryExistsShortMessage));
}
Directory.CreateDirectory(strNewDir);
}
}
/// <summary>
/// Rename the physical directory for a folder node
/// Override if your node does not use file system folder
/// </summary>
/// <returns></returns>
public virtual void RenameDirectory(string newPath) {
if (Directory.Exists(this.Url)) {
if (CommonUtils.IsSameDirectory(this.Url, newPath)) {
// This is a rename to the same location with (possible) capitilization changes.
// Directory.Move does not allow renaming to the same name so P/Invoke MoveFile to bypass this.
if (!NativeMethods.MoveFile(this.Url, newPath)) {
// Rather than perform error handling, Call Directory.Move and let it handle the error handling.
// If this succeeds, then we didn't really have errors that needed handling.
Directory.Move(this.Url, newPath);
}
} else if (Directory.Exists(newPath)) {
// Directory exists and it wasn't the source. Item cannot be moved as name exists.
ShowFileOrFolderAlreadyExistsErrorMessage(newPath);
} else {
Directory.Move(this.Url, newPath);
}
}
}
void IDiskBasedNode.RenameForDeferredSave(string basePath, string baseNewPath) {
string oldPath = Path.Combine(basePath, ItemNode.GetMetadata(ProjectFileConstants.Include));
string newPath = Path.Combine(baseNewPath, ItemNode.GetMetadata(ProjectFileConstants.Include));
Directory.CreateDirectory(newPath);
ProjectMgr.UpdatePathForDeferredSave(oldPath, newPath);
}
#endregion
#region helper methods
/// <summary>
/// Renames the folder to the new name.
/// </summary>
public virtual void RenameFolder(string newName) {
// Do the rename (note that we only do the physical rename if the leaf name changed)
string newPath = Path.Combine(Parent.FullPathToChildren, newName);
string oldPath = Url;
if (!String.Equals(Path.GetFileName(Url), newName, StringComparison.Ordinal)) {
RenameDirectory(CommonUtils.GetAbsoluteDirectoryPath(ProjectMgr.ProjectHome, newPath));
}
bool wasExpanded = GetIsExpanded();
ReparentFolder(newPath);
var oldTriggerFlag = ProjectMgr.EventTriggeringFlag;
ProjectMgr.EventTriggeringFlag |= ProjectNode.EventTriggering.DoNotTriggerTrackerEvents;
try {
// Let all children know of the new path
for (HierarchyNode child = this.FirstChild; child != null; child = child.NextSibling) {
FolderNode node = child as FolderNode;
if (node == null) {
child.SetEditLabel(child.GetEditLabel());
} else {
node.RenameFolder(node.Caption);
}
}
} finally {
ProjectMgr.EventTriggeringFlag = oldTriggerFlag;
}
ProjectMgr.Tracker.OnItemRenamed(oldPath, newPath, VSRENAMEFILEFLAGS.VSRENAMEFILEFLAGS_Directory);
// Some of the previous operation may have changed the selection so set it back to us
ExpandItem(wasExpanded ? EXPANDFLAGS.EXPF_ExpandFolder : EXPANDFLAGS.EXPF_CollapseFolder);
ExpandItem(EXPANDFLAGS.EXPF_SelectItem);
}
/// <summary>
/// Moves the HierarchyNode from the old path to be a child of the
/// newly specified node.
///
/// This is a low-level operation that only updates the hierarchy and our MSBuild
/// state. The parents of the node must already be created.
///
/// To do a general rename, call RenameFolder instead.
/// </summary>
internal void ReparentFolder(string newPath) {
// Reparent the folder
ProjectMgr.OnItemDeleted(this);
Parent.RemoveChild(this);
ProjectMgr.Site.GetUIThread().MustBeCalledFromUIThread();
ID = ProjectMgr.ItemIdMap.Add(this);
ItemNode.Rename(CommonUtils.GetRelativeDirectoryPath(ProjectMgr.ProjectHome, newPath));
var parent = ProjectMgr.GetParentFolderForPath(newPath);
if (parent == null) {
Debug.Fail("ReparentFolder called without full path to parent being created");
throw new DirectoryNotFoundException(newPath);
}
parent.AddChild(this);
}
/// <summary>
/// Show error message if not in automation mode, otherwise throw exception
/// </summary>
/// <param name="newPath">path of file or folder already existing on disk</param>
/// <returns>S_OK</returns>
private int ShowFileOrFolderAlreadyExistsErrorMessage(string newPath) {
//A file or folder with the name '{0}' already exists on disk at this location. Please choose another name.
//If this file or folder does not appear in the Solution Explorer, then it is not currently part of your project. To view files which exist on disk, but are not in the project, select Show All Files from the Project menu.
string errorMessage = SR.GetString(SR.FileOrFolderAlreadyExists, newPath);
if (!Utilities.IsInAutomationFunction(this.ProjectMgr.Site)) {
string title = null;
OLEMSGICON icon = OLEMSGICON.OLEMSGICON_CRITICAL;
OLEMSGBUTTON buttons = OLEMSGBUTTON.OLEMSGBUTTON_OK;
OLEMSGDEFBUTTON defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST;
Utilities.ShowMessageBox(this.ProjectMgr.Site, title, errorMessage, icon, buttons, defaultButton);
return VSConstants.S_OK;
} else {
throw new InvalidOperationException(errorMessage);
}
}
protected override void OnCancelLabelEdit() {
if (IsBeingCreated) {
// finish the creation
FinishFolderAdd(Caption, true);
}
}
internal bool IsBeingCreated {
get {
return ProjectMgr.FolderBeingCreated == this;
}
set {
if (value) {
ProjectMgr.FolderBeingCreated = this;
} else {
ProjectMgr.FolderBeingCreated = null;
}
}
}
#endregion
protected override void RaiseOnItemRemoved(string documentToRemove, string[] filesToBeDeleted) {
VSREMOVEDIRECTORYFLAGS[] removeFlags = new VSREMOVEDIRECTORYFLAGS[1];
this.ProjectMgr.Tracker.OnFolderRemoved(documentToRemove, removeFlags[0]);
}
}
}
| |
/***************************************************************************
* TaskCollection.cs
*
* Copyright (C) 2007 Michael C. Urbanski
* Written by Mike Urbanski <[email protected]>
****************************************************************************/
/* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW:
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using Migo.TaskCore;
namespace Migo.TaskCore.Collections
{
public abstract class TaskCollection<T> : ICollection<T>
where T : Task
{
private AsyncCommandQueue commandQueue;
public EventHandler<ReorderedEventArgs> Reordered;
public EventHandler<TaskAddedEventArgs<T>> TaskAdded;
public EventHandler<TaskRemovedEventArgs<T>> TaskRemoved;
public abstract bool CanReorder
{
get; // is Move implemented
}
public virtual AsyncCommandQueue CommandQueue
{
get { return commandQueue; }
set { commandQueue = value; }
}
public abstract int Count {
get;
}
public abstract bool IsReadOnly {
get;
}
public abstract bool IsSynchronized {
get;
}
public abstract object SyncRoot {
get;
}
public TaskCollection () {}
public abstract IEnumerator<T> GetEnumerator ();
// This needs to be looked into.
IEnumerator IEnumerable.GetEnumerator ()
{
return GetEnumerator ();
}
public abstract T this [int index]
{
get; set;
}
public abstract void Add (T task);
public abstract bool Remove (T task);
public abstract void Remove (IEnumerable<T> tasks);
public abstract void CopyTo (T[] array, int index);
public abstract void CopyTo (Array array, int index);
public abstract void Clear ();
public abstract bool Contains (T task);
protected virtual IEnumerable<KeyValuePair<int,int>> DetectContinuity (int[] indices)
{
if (indices == null) {
throw new ArgumentNullException ("indices");
} else if (indices.Length == 0) {
return null;
}
int cnt;
int len = indices.Length;
List<KeyValuePair<int,int>> ret = new List<KeyValuePair<int,int>>();
int i = len-1;
while (i > 0) {
cnt = 1;
while (indices[i] == indices[i-1]+1)
{
++cnt;
if (--i == 0) {
break;
}
}
ret.Add (new KeyValuePair<int,int>(indices[i--], cnt));
}
return ret;
}
protected virtual void OnReordered (int[] newOrder)
{
EventHandler<ReorderedEventArgs> handler = Reordered;
if (handler != null) {
ReorderedEventArgs e = new ReorderedEventArgs (newOrder);
if (commandQueue != null) {
commandQueue.Register (
new EventWrapper<ReorderedEventArgs> (handler, this, e)
);
} else {
handler (this, e);
}
}
}
protected virtual void OnTaskAdded (int pos, T task)
{
EventHandler<TaskAddedEventArgs<T>> handler = TaskAdded;
if (handler != null) {
TaskAddedEventArgs<T> e = new TaskAddedEventArgs<T> (pos, task);
if (commandQueue != null) {
commandQueue.Register (
new EventWrapper<TaskAddedEventArgs<T>> (handler, this, e)
);
} else {
handler (this, e);
}
}
}
protected virtual void OnTasksAdded (ICollection<KeyValuePair<int,T>> pairs)
{
EventHandler<TaskAddedEventArgs<T>> handler = TaskAdded;
if (handler != null) {
TaskAddedEventArgs<T> e = new TaskAddedEventArgs<T> (pairs);
if (commandQueue != null) {
commandQueue.Register (new EventWrapper<TaskAddedEventArgs<T>> (
handler, this, e)
);
} else {
handler (this, e);
}
}
}
protected virtual void OnTaskRemoved (int index, T task)
{
EventHandler<TaskRemovedEventArgs<T>> handler = TaskRemoved;
if (handler != null) {
TaskRemovedEventArgs<T> e =
new TaskRemovedEventArgs<T> (index, task);
if (commandQueue != null) {
commandQueue.Register (
new EventWrapper<TaskRemovedEventArgs<T>> (handler, this, e)
);
} else {
handler (this, e);
}
}
}
protected virtual void OnTasksRemoved (ICollection<T> tasks,
IEnumerable<KeyValuePair<int,int>> indices)
{
EventHandler<TaskRemovedEventArgs<T>> handler = TaskRemoved;
if (handler != null) {
TaskRemovedEventArgs<T> e = new TaskRemovedEventArgs<T> (indices, tasks);
if (commandQueue != null) {
commandQueue.Register (
new EventWrapper<TaskRemovedEventArgs<T>> (handler, this, e)
);
} else {
handler (this, e);
}
}
}
}
}
| |
// 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.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.AspNetCore.Testing;
using Moq;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.ViewFeatures
{
public class DefaultEditorTemplatesTest
{
// Mappings from templateName to expected result when using StubbyHtmlHelper.
public static TheoryData<string, string> TemplateNameData
{
get
{
return new TheoryData<string, string>
{
{ null, "__TextBox__ class='text-box single-line'" },
{ string.Empty, "__TextBox__ class='text-box single-line'" },
{ "EmailAddress", "__TextBox__ class='text-box single-line' type='email'" },
{ "emailaddress", "__TextBox__ class='text-box single-line' type='email'" },
{ "HiddenInput", "HtmlEncode[[True]]__Hidden__" }, // Hidden also generates value by default.
{ "HIDDENINPUT", "HtmlEncode[[True]]__Hidden__" },
{ "MultilineText", "__TextArea__ class='text-box multi-line'" },
{ "multilinetext", "__TextArea__ class='text-box multi-line'" },
{ "Password", "__Password__ class='text-box single-line password'" },
{ "PASSWORD", "__Password__ class='text-box single-line password'" },
{ "PhoneNumber", "__TextBox__ class='text-box single-line' type='tel'" },
{ "phonenumber", "__TextBox__ class='text-box single-line' type='tel'" },
{ "Text", "__TextBox__ class='text-box single-line'" },
{ "TEXT", "__TextBox__ class='text-box single-line'" },
{ "Url", "__TextBox__ class='text-box single-line' type='url'" },
{ "url", "__TextBox__ class='text-box single-line' type='url'" },
{ "Date", "__TextBox__ class='text-box single-line' type='date'" },
{ "DATE", "__TextBox__ class='text-box single-line' type='date'" },
{ "DateTime", "__TextBox__ class='text-box single-line' type='datetime-local'" },
{ "datetime", "__TextBox__ class='text-box single-line' type='datetime-local'" },
{ "DateTime-local", "__TextBox__ class='text-box single-line' type='datetime-local'" },
{ "DATETIME-LOCAL", "__TextBox__ class='text-box single-line' type='datetime-local'" },
{ "datetimeoffset", "__TextBox__ class='text-box single-line' type='text'" },
{ "DateTimeOffset", "__TextBox__ class='text-box single-line' type='text'" },
{ "Time", "__TextBox__ class='text-box single-line' type='time'" },
{ "time", "__TextBox__ class='text-box single-line' type='time'" },
{ "Month", "__TextBox__ class='text-box single-line' type='month'" },
{ "month", "__TextBox__ class='text-box single-line' type='month'" },
{ "Week", "__TextBox__ class='text-box single-line' type='week'" },
{ "week", "__TextBox__ class='text-box single-line' type='week'" },
{ "Byte", "__TextBox__ class='text-box single-line' type='number'" },
{ "BYTE", "__TextBox__ class='text-box single-line' type='number'" },
{ "SByte", "__TextBox__ class='text-box single-line' type='number'" },
{ "sbyte", "__TextBox__ class='text-box single-line' type='number'" },
{ "Int16", "__TextBox__ class='text-box single-line' type='number'" },
{ "INT16", "__TextBox__ class='text-box single-line' type='number'" },
{ "UInt16", "__TextBox__ class='text-box single-line' type='number'" },
{ "uint16", "__TextBox__ class='text-box single-line' type='number'" },
{ "Int32", "__TextBox__ class='text-box single-line' type='number'" },
{ "INT32", "__TextBox__ class='text-box single-line' type='number'" },
{ "UInt32", "__TextBox__ class='text-box single-line' type='number'" },
{ "uint32", "__TextBox__ class='text-box single-line' type='number'" },
{ "Int64", "__TextBox__ class='text-box single-line' type='number'" },
{ "INT64", "__TextBox__ class='text-box single-line' type='number'" },
{ "UInt64", "__TextBox__ class='text-box single-line' type='number'" },
{ "uint64", "__TextBox__ class='text-box single-line' type='number'" },
{ "Single", "__TextBox__ class='text-box single-line'" },
{ "SINGLE", "__TextBox__ class='text-box single-line'" },
{ "Double", "__TextBox__ class='text-box single-line'" },
{ "double", "__TextBox__ class='text-box single-line'" },
{ "Boolean", "__CheckBox__ class='check-box'" }, // Not tri-state b/c string is not a Nullable type.
{ "BOOLEAN", "__CheckBox__ class='check-box'" },
{ "Decimal", "__TextBox__ class='text-box single-line'" },
{ "decimal", "__TextBox__ class='text-box single-line'" },
{ "String", "__TextBox__ class='text-box single-line'" },
{ "STRING", "__TextBox__ class='text-box single-line'" },
{ typeof(IFormFile).Name, "__TextBox__ class='text-box single-line' type='file'" },
{ TemplateRenderer.IEnumerableOfIFormFileName,
"__TextBox__ class='text-box single-line' type='file' multiple='multiple'" },
};
}
}
// label's IHtmlContent -> expected label text
public static TheoryData<IHtmlContent, string> ObjectTemplate_ChecksWriteTo_NotToStringData
{
get
{
// Similar to HtmlString.Empty today.
var noopContentWithEmptyToString = new Mock<IHtmlContent>(MockBehavior.Strict);
noopContentWithEmptyToString
.Setup(c => c.ToString())
.Returns(string.Empty);
noopContentWithEmptyToString.Setup(c => c.WriteTo(It.IsAny<TextWriter>(), It.IsAny<HtmlEncoder>()));
// Similar to an empty StringHtmlContent today.
var noopContentWithNonEmptyToString = new Mock<IHtmlContent>(MockBehavior.Strict);
noopContentWithNonEmptyToString
.Setup(c => c.ToString())
.Returns(typeof(StringHtmlContent).FullName);
noopContentWithNonEmptyToString.Setup(c => c.WriteTo(It.IsAny<TextWriter>(), It.IsAny<HtmlEncoder>()));
// Makes noop calls on the TextWriter.
var busyNoopContentWithNonEmptyToString = new Mock<IHtmlContent>(MockBehavior.Strict);
busyNoopContentWithNonEmptyToString
.Setup(c => c.ToString())
.Returns(typeof(StringHtmlContent).FullName);
busyNoopContentWithNonEmptyToString
.Setup(c => c.WriteTo(It.IsAny<TextWriter>(), It.IsAny<HtmlEncoder>()))
.Callback<TextWriter, HtmlEncoder>((writer, encoder) =>
{
writer.Write(string.Empty);
writer.Write(new char[0]);
writer.Write((char[])null);
writer.Write((object)null);
writer.Write((string)null);
writer.Write(format: "{0}", arg0: null);
writer.Write(new char[] { 'a', 'b', 'c' }, index: 1, count: 0);
});
// Unrealistic but covers all the bases.
var writingContentWithEmptyToString = new Mock<IHtmlContent>(MockBehavior.Strict);
writingContentWithEmptyToString
.Setup(c => c.ToString())
.Returns(string.Empty);
writingContentWithEmptyToString
.Setup(c => c.WriteTo(It.IsAny<TextWriter>(), It.IsAny<HtmlEncoder>()))
.Callback<TextWriter, HtmlEncoder>((writer, encoder) => writer.Write("Some string"));
// Similar to TagBuilder today.
var writingContentWithNonEmptyToString = new Mock<IHtmlContent>(MockBehavior.Strict);
writingContentWithNonEmptyToString
.Setup(c => c.ToString())
.Returns(typeof(TagBuilder).FullName);
writingContentWithNonEmptyToString
.Setup(c => c.WriteTo(It.IsAny<TextWriter>(), It.IsAny<HtmlEncoder>()))
.Callback<TextWriter, HtmlEncoder>((writer, encoder) => writer.Write("Some string"));
// label's IHtmlContent -> expected label text
return new TheoryData<IHtmlContent, string>
{
// Types HtmlHelper actually uses.
{ HtmlString.Empty, string.Empty },
{
new TagBuilder("label"),
"<div class=\"HtmlEncode[[editor-label]]\"><label></label></div>" + Environment.NewLine
},
// Another IHtmlContent implementation that does not override ToString().
{ new StringHtmlContent(string.Empty), string.Empty },
// Mocks
{ noopContentWithEmptyToString.Object, string.Empty },
{ noopContentWithNonEmptyToString.Object, string.Empty },
{ busyNoopContentWithNonEmptyToString.Object, string.Empty },
{
writingContentWithEmptyToString.Object,
"<div class=\"HtmlEncode[[editor-label]]\">Some string</div>" + Environment.NewLine
},
{
writingContentWithNonEmptyToString.Object,
"<div class=\"HtmlEncode[[editor-label]]\">Some string</div>" + Environment.NewLine
},
};
}
}
[Fact]
public void ObjectTemplateEditsSimplePropertiesOnObjectByDefault()
{
// Arrange
var expected =
"<div class=\"HtmlEncode[[editor-label]]\"><label for=\"HtmlEncode[[Property1]]\">HtmlEncode[[Property1]]</label></div>" +
Environment.NewLine +
"<div class=\"HtmlEncode[[editor-field]]\">Model = p1, ModelType = System.String, PropertyName = Property1, SimpleDisplayText = p1 " +
"<span class=\"HtmlEncode[[field-validation-valid]]\" data-valmsg-for=\"HtmlEncode[[Property1]]\" data-valmsg-replace=\"HtmlEncode[[true]]\">" +
"</span></div>" +
Environment.NewLine +
"<div class=\"HtmlEncode[[editor-label]]\"><label for=\"HtmlEncode[[Property2]]\">HtmlEncode[[Prop2]]</label></div>" +
Environment.NewLine +
"<div class=\"HtmlEncode[[editor-field]]\">Model = (null), ModelType = System.String, PropertyName = Property2, SimpleDisplayText = (null) " +
"<span class=\"HtmlEncode[[field-validation-valid]]\" data-valmsg-for=\"HtmlEncode[[Property2]]\" data-valmsg-replace=\"HtmlEncode[[true]]\">" +
"</span></div>" +
Environment.NewLine;
var model = new DefaultTemplatesUtilities.ObjectTemplateModel { Property1 = "p1", Property2 = null };
var html = DefaultTemplatesUtilities.GetHtmlHelper(model);
// Act
var result = DefaultEditorTemplates.ObjectTemplate(html);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
// Prior to aspnet/Mvc#6638 fix, helper did not generate Property1 <label> or containing <div> with this setup.
// Expect almost the same HTML as in ObjectTemplateEditsSimplePropertiesOnObjectByDefault(). Only difference is
// the <div class="editor-label">...</div> is not present for Property1.
[Fact]
public void ObjectTemplateSkipsLabel_IfDisplayNameIsEmpty()
{
// Arrange
var expected =
"<div class=\"HtmlEncode[[editor-label]]\"><label for=\"HtmlEncode[[Property1]]\"></label></div>" +
Environment.NewLine +
"<div class=\"HtmlEncode[[editor-field]]\">Model = p1, ModelType = System.String, PropertyName = Property1, SimpleDisplayText = p1 " +
"<span class=\"HtmlEncode[[field-validation-valid]]\" data-valmsg-for=\"HtmlEncode[[Property1]]\" data-valmsg-replace=\"HtmlEncode[[true]]\">" +
"</span></div>" +
Environment.NewLine +
"<div class=\"HtmlEncode[[editor-label]]\"><label for=\"HtmlEncode[[Property2]]\">HtmlEncode[[Prop2]]</label></div>" +
Environment.NewLine +
"<div class=\"HtmlEncode[[editor-field]]\">Model = (null), ModelType = System.String, PropertyName = Property2, SimpleDisplayText = (null) " +
"<span class=\"HtmlEncode[[field-validation-valid]]\" data-valmsg-for=\"HtmlEncode[[Property2]]\" data-valmsg-replace=\"HtmlEncode[[true]]\">" +
"</span></div>" +
Environment.NewLine;
var provider = new TestModelMetadataProvider();
provider
.ForProperty<DefaultTemplatesUtilities.ObjectTemplateModel>(
nameof(DefaultTemplatesUtilities.ObjectTemplateModel.Property1))
.DisplayDetails(dd => dd.DisplayName = () => string.Empty);
var model = new DefaultTemplatesUtilities.ObjectTemplateModel { Property1 = "p1", Property2 = null };
var html = DefaultTemplatesUtilities.GetHtmlHelper(model, provider);
// Act
var result = DefaultEditorTemplates.ObjectTemplate(html);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Theory]
[MemberData(nameof(ObjectTemplate_ChecksWriteTo_NotToStringData))]
public void ObjectTemplate_ChecksWriteTo_NotToString(IHtmlContent labelContent, string expectedLabel)
{
// Arrange
var expected =
expectedLabel +
"<div class=\"HtmlEncode[[editor-field]]\">Model = (null), ModelType = System.String, PropertyName = Property1, SimpleDisplayText = (null) " +
"</div>" +
Environment.NewLine +
expectedLabel +
"<div class=\"HtmlEncode[[editor-field]]\">Model = (null), ModelType = System.String, PropertyName = Property2, SimpleDisplayText = (null) " +
"</div>" +
Environment.NewLine;
var helperToCopy = DefaultTemplatesUtilities.GetHtmlHelper();
var helperMock = new Mock<IHtmlHelper>(MockBehavior.Strict);
helperMock.SetupGet(h => h.ViewContext).Returns(helperToCopy.ViewContext);
helperMock.SetupGet(h => h.ViewData).Returns(helperToCopy.ViewData);
helperMock
.Setup(h => h.Label(
It.Is<string>(s => string.Equals("Property1", s, StringComparison.Ordinal) ||
string.Equals("Property2", s, StringComparison.Ordinal)),
null, // labelText
null)) // htmlAttributes
.Returns(labelContent);
helperMock
.Setup(h => h.ValidationMessage(
It.Is<string>(s => string.Equals("Property1", s, StringComparison.Ordinal) ||
string.Equals("Property2", s, StringComparison.Ordinal)),
null, // message
null, // htmlAttributes
null)) // tag
.Returns(HtmlString.Empty);
// Act
var result = DefaultEditorTemplates.ObjectTemplate(helperMock.Object);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void ObjectTemplateDisplaysNullDisplayTextWithNullModelAndTemplateDepthGreaterThanOne()
{
// Arrange
var provider = new TestModelMetadataProvider();
provider.ForType<DefaultTemplatesUtilities.ObjectTemplateModel>().DisplayDetails(dd =>
{
dd.NullDisplayText = "Null Display Text";
dd.SimpleDisplayProperty = "Property1";
});
var html = DefaultTemplatesUtilities.GetHtmlHelper(provider: provider);
html.ViewData.TemplateInfo.AddVisited("foo");
html.ViewData.TemplateInfo.AddVisited("bar");
// Act
var result = DefaultEditorTemplates.ObjectTemplate(html);
// Assert
Assert.Equal(html.ViewData.ModelMetadata.NullDisplayText, HtmlContentUtilities.HtmlContentToString(result));
}
[Theory]
[MemberData(nameof(DefaultDisplayTemplatesTest.HtmlEncodeData), MemberType = typeof(DefaultDisplayTemplatesTest))]
public void ObjectTemplateDisplaysSimpleDisplayTextWithNonNullModelTemplateDepthGreaterThanOne(
string simpleDisplayText,
bool htmlEncode,
string expectedResult)
{
// Arrange
var model = new DefaultTemplatesUtilities.ObjectTemplateModel()
{
Property1 = simpleDisplayText,
};
var provider = new TestModelMetadataProvider();
provider.ForType<DefaultTemplatesUtilities.ObjectTemplateModel>().DisplayDetails(dd =>
{
dd.HtmlEncode = htmlEncode;
dd.NullDisplayText = "Null Display Text";
dd.SimpleDisplayProperty = "Property1";
});
var html = DefaultTemplatesUtilities.GetHtmlHelper(model, provider: provider);
html.ViewData.TemplateInfo.AddVisited("foo");
html.ViewData.TemplateInfo.AddVisited("bar");
// Act
var result = DefaultEditorTemplates.ObjectTemplate(html);
// Assert
Assert.Equal(expectedResult, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void ObjectTemplate_IgnoresPropertiesWith_ScaffoldColumnFalse()
{
// Arrange
var expected =
@"<div class=""HtmlEncode[[editor-label]]""><label for=""HtmlEncode[[Property1]]"">HtmlEncode[[Property1]]</label></div>" +
Environment.NewLine +
@"<div class=""HtmlEncode[[editor-field]]""><input class=""HtmlEncode[[text-box single-line]]"" id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[text]]"" value="""" /> " +
@"<span class=""HtmlEncode[[field-validation-valid]]"" data-valmsg-for=""HtmlEncode[[Property1]]"" data-valmsg-replace=""HtmlEncode[[true]]""></span></div>" +
Environment.NewLine +
@"<div class=""HtmlEncode[[editor-label]]""><label for=""HtmlEncode[[Property3]]"">HtmlEncode[[Property3]]</label></div>" +
Environment.NewLine +
@"<div class=""HtmlEncode[[editor-field]]""><input class=""HtmlEncode[[text-box single-line]]"" id=""HtmlEncode[[Property3]]"" name=""HtmlEncode[[Property3]]"" type=""HtmlEncode[[text]]"" value="""" /> " +
@"<span class=""HtmlEncode[[field-validation-valid]]"" data-valmsg-for=""HtmlEncode[[Property3]]"" data-valmsg-replace=""HtmlEncode[[true]]""></span></div>" +
Environment.NewLine;
var model = new DefaultTemplatesUtilities.ObjectWithScaffoldColumn();
var viewEngine = new Mock<ICompositeViewEngine>(MockBehavior.Strict);
viewEngine
.Setup(v => v.GetView(/*executingFilePath*/ null, It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound(string.Empty, Enumerable.Empty<string>()));
viewEngine
.Setup(v => v.FindView(It.IsAny<ActionContext>(), It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound("", Enumerable.Empty<string>()));
var htmlHelper = DefaultTemplatesUtilities.GetHtmlHelper(model, viewEngine.Object);
// Act
var result = DefaultEditorTemplates.ObjectTemplate(htmlHelper);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void ObjectTemplate_HonorsHideSurroundingHtml()
{
// Arrange
var expected =
"Model = p1, ModelType = System.String, PropertyName = Property1, SimpleDisplayText = p1" +
"<div class=\"HtmlEncode[[editor-label]]\"><label for=\"HtmlEncode[[Property2]]\">HtmlEncode[[Prop2]]</label></div>" +
Environment.NewLine +
"<div class=\"HtmlEncode[[editor-field]]\">" +
"Model = (null), ModelType = System.String, PropertyName = Property2, SimpleDisplayText = (null) " +
"<span class=\"HtmlEncode[[field-validation-valid]]\" data-valmsg-for=\"HtmlEncode[[Property2]]\" data-valmsg-replace=\"HtmlEncode[[true]]\">" +
"</span></div>" +
Environment.NewLine;
var provider = new TestModelMetadataProvider();
provider.ForProperty<DefaultTemplatesUtilities.ObjectTemplateModel>("Property1").DisplayDetails(dd =>
{
dd.HideSurroundingHtml = true;
});
var model = new DefaultTemplatesUtilities.ObjectTemplateModel { Property1 = "p1", Property2 = null };
var html = DefaultTemplatesUtilities.GetHtmlHelper(model, provider: provider);
// Act
var result = DefaultEditorTemplates.ObjectTemplate(html);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void ObjectTemplate_OrdersProperties_AsExpected()
{
// Arrange
var model = new OrderedModel();
var html = DefaultTemplatesUtilities.GetHtmlHelper(model);
var expectedProperties = new List<string>
{
"OrderedProperty3",
"OrderedProperty2",
"OrderedProperty1",
"Property3",
"Property1",
"Property2",
"LastProperty",
};
var stringBuilder = new StringBuilder();
foreach (var property in expectedProperties)
{
var label = string.Format(
CultureInfo.InvariantCulture,
"<div class=\"HtmlEncode[[editor-label]]\"><label for=\"HtmlEncode[[{0}]]\">HtmlEncode[[{0}]]</label></div>",
property);
stringBuilder.AppendLine(label);
var value = string.Format(
CultureInfo.InvariantCulture,
"<div class=\"HtmlEncode[[editor-field]]\">Model = (null), ModelType = System.String, PropertyName = {0}, " +
"SimpleDisplayText = (null) " +
"<span class=\"HtmlEncode[[field-validation-valid]]\" data-valmsg-for=\"HtmlEncode[[{0}]]\" data-valmsg-replace=\"HtmlEncode[[true]]\">" +
"</span></div>",
property);
stringBuilder.AppendLine(value);
}
var expected = stringBuilder.ToString();
// Act
var result = DefaultEditorTemplates.ObjectTemplate(html);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void HiddenInputTemplate_ReturnsValueAndHiddenInput()
{
// Arrange
var expected =
"HtmlEncode[[Formatted string]]<input id=\"HtmlEncode[[FieldPrefix]]\" name=\"HtmlEncode[[FieldPrefix]]\" type=\"HtmlEncode[[hidden]]\" value=\"HtmlEncode[[Model string]]\" />";
var model = "Model string";
var html = DefaultTemplatesUtilities.GetHtmlHelper(model);
var templateInfo = html.ViewData.TemplateInfo;
templateInfo.HtmlFieldPrefix = "FieldPrefix";
// TemplateBuilder sets FormattedModelValue before calling TemplateRenderer and it's used below.
templateInfo.FormattedModelValue = "Formatted string";
// Act
var result = DefaultEditorTemplates.HiddenInputTemplate(html);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void HiddenInputTemplate_HonorsHideSurroundingHtml()
{
// Arrange
var expected = "<input id=\"HtmlEncode[[FieldPrefix]]\" name=\"HtmlEncode[[FieldPrefix]]\" type=\"HtmlEncode[[hidden]]\" value=\"HtmlEncode[[Model string]]\" />";
var model = "Model string";
var provider = new TestModelMetadataProvider();
provider.ForType<string>().DisplayDetails(dd =>
{
dd.HideSurroundingHtml = true;
});
var html = DefaultTemplatesUtilities.GetHtmlHelper(model, provider: provider);
var templateInfo = html.ViewData.TemplateInfo;
templateInfo.HtmlFieldPrefix = "FieldPrefix";
templateInfo.FormattedModelValue = "Formatted string";
// Act
var result = DefaultEditorTemplates.HiddenInputTemplate(html);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void MultilineTextTemplate_ReturnsTextArea()
{
// Arrange
var expected =
"<textarea class=\"HtmlEncode[[text-box multi-line]]\" id=\"HtmlEncode[[FieldPrefix]]\" name=\"HtmlEncode[[FieldPrefix]]\">" +
Environment.NewLine +
"HtmlEncode[[Formatted string]]</textarea>";
var model = "Model string";
var html = DefaultTemplatesUtilities.GetHtmlHelper(model);
var templateInfo = html.ViewData.TemplateInfo;
templateInfo.HtmlFieldPrefix = "FieldPrefix";
// TemplateBuilder sets FormattedModelValue before calling TemplateRenderer and it's used below.
templateInfo.FormattedModelValue = "Formatted string";
// Act
var result = DefaultEditorTemplates.MultilineTemplate(html);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void PasswordTemplate_ReturnsInputElement_IgnoresValues()
{
// Arrange
var expected = "<input class=\"HtmlEncode[[text-box single-line password]]\" " +
"id=\"HtmlEncode[[FieldPrefix]]\" name=\"HtmlEncode[[FieldPrefix]]\" " +
"type=\"HtmlEncode[[password]]\" />";
// Template ignores Model.
var model = "Model string";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(model);
var viewData = helper.ViewData;
var templateInfo = viewData.TemplateInfo;
templateInfo.HtmlFieldPrefix = "FieldPrefix";
// Template ignores FormattedModelValue, ModelState and ViewData.
templateInfo.FormattedModelValue = "Formatted string";
viewData.ModelState.SetModelValue("FieldPrefix", "Raw model string", "Attempted model string");
viewData["FieldPrefix"] = "ViewData string";
// Act
var result = DefaultEditorTemplates.PasswordTemplate(helper);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void PasswordTemplate_ReturnsInputElement_UsesHtmlAttributes()
{
// Arrange
var expected = "<input class=\"HtmlEncode[[super text-box single-line password]]\" " +
"id=\"HtmlEncode[[FieldPrefix]]\" name=\"HtmlEncode[[FieldPrefix]]\" " +
"type=\"HtmlEncode[[password]]\" value=\"HtmlEncode[[Html attributes string]]\" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper<string>(model: null);
var viewData = helper.ViewData;
var templateInfo = viewData.TemplateInfo;
templateInfo.HtmlFieldPrefix = "FieldPrefix";
viewData["htmlAttributes"] = new { @class = "super", value = "Html attributes string" };
// Act
var result = DefaultEditorTemplates.PasswordTemplate(helper);
// Assert
Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
}
[Theory]
[MemberData(nameof(TemplateNameData))]
public void Editor_CallsExpectedHtmlHelper(string templateName, string expectedResult)
{
// Arrange
var model = new DefaultTemplatesUtilities.ObjectTemplateModel { Property1 = "True" };
var viewEngine = new Mock<ICompositeViewEngine>(MockBehavior.Strict);
viewEngine
.Setup(v => v.GetView(/*executingFilePath*/ null, It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound(string.Empty, Enumerable.Empty<string>()));
viewEngine
.Setup(v => v.FindView(It.IsAny<ActionContext>(), It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound(string.Empty, Enumerable.Empty<string>()));
var helper = DefaultTemplatesUtilities.GetHtmlHelper(
model,
viewEngine.Object,
innerHelper => new StubbyHtmlHelper(innerHelper));
helper.ViewData["Property1"] = "True";
// TemplateBuilder sets FormattedModelValue before calling TemplateRenderer and it's used in most templates.
helper.ViewData.TemplateInfo.FormattedModelValue = "Formatted string";
// Act
var result = helper.Editor(
"Property1",
templateName,
htmlFieldName: null,
additionalViewData: null);
// Assert
Assert.Equal(expectedResult, HtmlContentUtilities.HtmlContentToString(result));
}
[Theory]
[MemberData(nameof(TemplateNameData))]
public void EditorFor_CallsExpectedHtmlHelper(string templateName, string expectedResult)
{
// Arrange
var model = new DefaultTemplatesUtilities.ObjectTemplateModel { Property1 = "True" };
var viewEngine = new Mock<ICompositeViewEngine>(MockBehavior.Strict);
viewEngine
.Setup(v => v.GetView(/*executingFilePath*/ null, It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound(string.Empty, Enumerable.Empty<string>()));
viewEngine
.Setup(v => v.FindView(It.IsAny<ActionContext>(), It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound(string.Empty, Enumerable.Empty<string>()));
var helper = DefaultTemplatesUtilities.GetHtmlHelper(
model,
viewEngine.Object,
innerHelper => new StubbyHtmlHelper(innerHelper));
// TemplateBuilder sets FormattedModelValue before calling TemplateRenderer and it's used in most templates.
helper.ViewData.TemplateInfo.FormattedModelValue = "Formatted string";
// Act
var result = helper.EditorFor(
anotherModel => anotherModel.Property1,
templateName,
htmlFieldName: null,
additionalViewData: null);
// Assert
Assert.Equal(expectedResult, HtmlContentUtilities.HtmlContentToString(result));
}
[Theory]
[MemberData(nameof(TemplateNameData))]
public void Editor_CallsExpectedHtmlHelper_DataTypeName(string templateName, string expectedResult)
{
// Arrange
var model = new DefaultTemplatesUtilities.ObjectTemplateModel { Property1 = "True" };
var viewEngine = new Mock<ICompositeViewEngine>(MockBehavior.Strict);
viewEngine
.Setup(v => v.GetView(/*executingFilePath*/ null, It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound(string.Empty, Enumerable.Empty<string>()));
viewEngine
.Setup(v => v.FindView(It.IsAny<ActionContext>(), It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound(string.Empty, Enumerable.Empty<string>()));
var provider = new TestModelMetadataProvider();
provider.ForProperty<DefaultTemplatesUtilities.ObjectTemplateModel>("Property1").DisplayDetails(dd =>
{
dd.DataTypeName = templateName;
});
var helper = DefaultTemplatesUtilities.GetHtmlHelper(
model,
Mock.Of<IUrlHelper>(),
viewEngine.Object,
provider,
localizerFactory: null,
innerHelper => new StubbyHtmlHelper(innerHelper));
helper.ViewData["Property1"] = "True";
// TemplateBuilder sets FormattedModelValue before calling TemplateRenderer and it's used in most templates.
helper.ViewData.TemplateInfo.FormattedModelValue = "Formatted string";
// Act
var result = helper.Editor(
"Property1",
templateName,
htmlFieldName: null,
additionalViewData: null);
// Assert
Assert.Equal(expectedResult, HtmlContentUtilities.HtmlContentToString(result));
}
[Theory]
[MemberData(nameof(TemplateNameData))]
public void EditorFor_CallsExpectedHtmlHelper_DataTypeName(string templateName, string expectedResult)
{
// Arrange
var model = new DefaultTemplatesUtilities.ObjectTemplateModel { Property1 = "True" };
var viewEngine = new Mock<ICompositeViewEngine>(MockBehavior.Strict);
viewEngine
.Setup(v => v.GetView(/*executingFilePath*/ null, It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound(string.Empty, Enumerable.Empty<string>()));
viewEngine
.Setup(v => v.FindView(It.IsAny<ActionContext>(), It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound(string.Empty, Enumerable.Empty<string>()));
var provider = new TestModelMetadataProvider();
provider.ForProperty<DefaultTemplatesUtilities.ObjectTemplateModel>("Property1").DisplayDetails(dd =>
{
dd.DataTypeName = templateName;
});
var helper = DefaultTemplatesUtilities.GetHtmlHelper(
model,
Mock.Of<IUrlHelper>(),
viewEngine.Object,
provider,
localizerFactory: null,
innerHelper => new StubbyHtmlHelper(innerHelper));
// TemplateBuilder sets FormattedModelValue before calling TemplateRenderer and it's used in most templates.
helper.ViewData.TemplateInfo.FormattedModelValue = "Formatted string";
// Act
var result = helper.EditorFor(
anotherModel => anotherModel.Property1,
templateName,
htmlFieldName: null,
additionalViewData: null);
// Assert
Assert.Equal(expectedResult, HtmlContentUtilities.HtmlContentToString(result));
}
[Theory]
[MemberData(nameof(TemplateNameData))]
public void Editor_CallsExpectedHtmlHelper_TemplateHint(string templateName, string expectedResult)
{
// Arrange
var model = new DefaultTemplatesUtilities.ObjectTemplateModel { Property1 = "True" };
var viewEngine = new Mock<ICompositeViewEngine>(MockBehavior.Strict);
viewEngine
.Setup(v => v.GetView(/*executingFilePath*/ null, It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound(string.Empty, Enumerable.Empty<string>()));
viewEngine
.Setup(v => v.FindView(It.IsAny<ActionContext>(), It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound(string.Empty, Enumerable.Empty<string>()));
var provider = new TestModelMetadataProvider();
provider.ForProperty<DefaultTemplatesUtilities.ObjectTemplateModel>("Property1").DisplayDetails(dd =>
{
dd.TemplateHint = templateName;
});
var helper = DefaultTemplatesUtilities.GetHtmlHelper(
model,
Mock.Of<IUrlHelper>(),
viewEngine.Object,
provider,
localizerFactory: null,
innerHelper => new StubbyHtmlHelper(innerHelper));
helper.ViewData["Property1"] = "True";
// TemplateBuilder sets FormattedModelValue before calling TemplateRenderer and it's used in most templates.
helper.ViewData.TemplateInfo.FormattedModelValue = "Formatted string";
// Act
var result = helper.Editor(
"Property1",
templateName,
htmlFieldName: null,
additionalViewData: null);
// Assert
Assert.Equal(expectedResult, HtmlContentUtilities.HtmlContentToString(result));
}
[Theory]
[MemberData(nameof(TemplateNameData))]
public void EditorFor_CallsExpectedHtmlHelper_TemplateHint(string templateName, string expectedResult)
{
// Arrange
var model = new DefaultTemplatesUtilities.ObjectTemplateModel { Property1 = "True" };
var viewEngine = new Mock<ICompositeViewEngine>(MockBehavior.Strict);
viewEngine
.Setup(v => v.GetView(/*executingFilePath*/ null, It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound(string.Empty, Enumerable.Empty<string>()));
viewEngine
.Setup(v => v.FindView(It.IsAny<ActionContext>(), It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound(string.Empty, Enumerable.Empty<string>()));
var provider = new TestModelMetadataProvider();
provider.ForProperty<DefaultTemplatesUtilities.ObjectTemplateModel>("Property1").DisplayDetails(dd =>
{
dd.TemplateHint = templateName;
});
var helper = DefaultTemplatesUtilities.GetHtmlHelper(
model,
Mock.Of<IUrlHelper>(),
viewEngine.Object,
provider,
localizerFactory: null,
innerHelper => new StubbyHtmlHelper(innerHelper));
// TemplateBuilder sets FormattedModelValue before calling TemplateRenderer and it's used in most templates.
helper.ViewData.TemplateInfo.FormattedModelValue = "Formatted string";
// Act
var result = helper.EditorFor(
anotherModel => anotherModel.Property1,
templateName,
htmlFieldName: null,
additionalViewData: null);
// Assert
Assert.Equal(expectedResult, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void Editor_FindsViewDataMember()
{
// Arrange
var model = new DefaultTemplatesUtilities.ObjectTemplateModel { Property1 = "Model string" };
var viewEngine = new Mock<ICompositeViewEngine>(MockBehavior.Strict);
viewEngine
.Setup(v => v.GetView(/*executingFilePath*/ null, It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound(string.Empty, Enumerable.Empty<string>()));
viewEngine
.Setup(v => v.FindView(It.IsAny<ActionContext>(), It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound(string.Empty, Enumerable.Empty<string>()));
var helper = DefaultTemplatesUtilities.GetHtmlHelper(model, viewEngine.Object);
helper.ViewData["Property1"] = "ViewData string";
// Act
var result = helper.Editor("Property1");
// Assert
Assert.Equal(
"<input class=\"HtmlEncode[[text-box single-line]]\" id=\"HtmlEncode[[Property1]]\" name=\"HtmlEncode[[Property1]]\" type=\"HtmlEncode[[text]]\" value=\"HtmlEncode[[ViewData string]]\" />",
HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void Editor_InputTypeDateTime_RendersAsDateTime()
{
// Arrange
var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("DateTimeOffset");
var expectedInput = "<input class=\"HtmlEncode[[text-box single-line]]\" data-val=\"HtmlEncode[[true]]\" " +
$"data-val-required=\"HtmlEncode[[{requiredMessage}]]\" id=\"HtmlEncode[[FieldPrefix]]\" " +
"name=\"HtmlEncode[[FieldPrefix]]\" type=\"HtmlEncode[[datetime]]\" value=\"HtmlEncode[[2000-01-02T03:04:05.060+00:00]]\" />";
var offset = TimeSpan.FromHours(0);
var model = new DateTimeOffset(
year: 2000,
month: 1,
day: 2,
hour: 3,
minute: 4,
second: 5,
millisecond: 60,
offset: offset);
var viewEngine = new Mock<ICompositeViewEngine>(MockBehavior.Strict);
viewEngine
.Setup(v => v.GetView(/*executingFilePath*/ null, It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound(string.Empty, Enumerable.Empty<string>()));
viewEngine
.Setup(v => v.FindView(It.IsAny<ActionContext>(), It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound(string.Empty, Enumerable.Empty<string>()));
var provider = new TestModelMetadataProvider();
var helper = DefaultTemplatesUtilities.GetHtmlHelper(
model,
Mock.Of<IUrlHelper>(),
viewEngine.Object,
provider);
helper.ViewData.TemplateInfo.HtmlFieldPrefix = "FieldPrefix";
// Act
var result = helper.Editor(
string.Empty,
new { htmlAttributes = new { type = "datetime" } });
// Assert
Assert.Equal(expectedInput, HtmlContentUtilities.HtmlContentToString(result));
}
// Html5DateRenderingMode.Rfc3339 is enabled by default.
[Theory]
[InlineData(null, null, "2000-01-02T03:04:05.060-05:00", "text")]
[InlineData("date", null, "2000-01-02", "date")]
[InlineData("date", "{0:d}", "02/01/2000", "date")]
[InlineData("datetime", null, "2000-01-02T03:04:05.060", "datetime-local")]
[InlineData("datetime-local", null, "2000-01-02T03:04:05.060", "datetime-local")]
[InlineData("DateTimeOffset", null, "2000-01-02T03:04:05.060-05:00", "text")]
[InlineData("DateTimeOffset", "{0:o}", "2000-01-02T03:04:05.0600000-05:00", "text")]
[InlineData("time", null, "03:04:05.060", "time")]
[InlineData("time", "{0:t}", "03:04", "time")]
[InlineData("month", null, "2000-01", "month")]
[InlineData("month", "{0:yyyy-MM}", "2000-01", "month")]
[InlineData("week", null, "1999-W52", "week")]
[InlineData("week", "{0:yyyy-'W1'}", "2000-W1", "week")]
[ReplaceCulture]
public void Editor_FindsCorrectDateOrTimeTemplate_WithTimeOffset(
string dataTypeName,
string editFormatString,
string expectedValue,
string expectedType)
{
// Arrange
var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("DateTimeOffset");
var expectedInput = "<input class=\"HtmlEncode[[text-box single-line]]\" data-val=\"HtmlEncode[[true]]\" " +
$"data-val-required=\"HtmlEncode[[{requiredMessage}]]\" id=\"HtmlEncode[[FieldPrefix]]\" " +
"name=\"HtmlEncode[[FieldPrefix]]\" type=\"HtmlEncode[[" +
expectedType +
"]]\" value=\"HtmlEncode[[" + expectedValue + "]]\" />";
var offset = TimeSpan.FromHours(-5);
var model = new DateTimeOffset(
year: 2000,
month: 1,
day: 2,
hour: 3,
minute: 4,
second: 5,
millisecond: 60,
offset: offset);
var viewEngine = new Mock<ICompositeViewEngine>(MockBehavior.Strict);
viewEngine
.Setup(v => v.GetView(/*executingFilePath*/ null, It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound(string.Empty, Enumerable.Empty<string>()));
viewEngine
.Setup(v => v.FindView(It.IsAny<ActionContext>(), It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound(string.Empty, Enumerable.Empty<string>()));
var provider = new TestModelMetadataProvider();
provider.ForType<DateTimeOffset>().DisplayDetails(dd =>
{
dd.DataTypeName = dataTypeName;
dd.EditFormatString = editFormatString; // What [DataType] does for given type.
dd.HasNonDefaultEditFormat = true;
});
var helper = DefaultTemplatesUtilities.GetHtmlHelper(
model,
Mock.Of<IUrlHelper>(),
viewEngine.Object,
provider);
helper.ViewData.TemplateInfo.HtmlFieldPrefix = "FieldPrefix";
// Act
var result = helper.Editor(string.Empty);
// Assert
Assert.Equal(expectedInput, HtmlContentUtilities.HtmlContentToString(result));
}
// Html5DateRenderingMode.Rfc3339 can be disabled.
[Theory]
[InlineData(null, null, "02/01/2000 03:04:05 -05:00", "text")]
[InlineData("date", null, "02/01/2000 03:04:05 -05:00", "date")]
[InlineData("date", "{0:d}", "02/01/2000", "date")]
[InlineData("datetime", null, "02/01/2000 03:04:05 -05:00", "datetime-local")]
[InlineData("datetime-local", null, "02/01/2000 03:04:05 -05:00", "datetime-local")]
[InlineData("DateTimeOffset", null, "02/01/2000 03:04:05 -05:00", "text")]
[InlineData("DateTimeOffset", "{0:o}", "2000-01-02T03:04:05.0600000-05:00", "text")]
[InlineData("time", null, "02/01/2000 03:04:05 -05:00", "time")]
[InlineData("time", "{0:t}", "03:04", "time")]
[InlineData("month", null, "2000-01", "month")]
[InlineData("month", "{0:yyyy-MM}", "2000-01", "month")]
[InlineData("week", null, "1999-W52", "week")]
[InlineData("week", "{0:yyyy-'W1'}", "2000-W1", "week")]
[ReplaceCulture]
public void Editor_FindsCorrectDateOrTimeTemplate_WithTimeOffset_NotRfc3339(
string dataTypeName,
string editFormatString,
string expectedValue,
string expectedType)
{
// Arrange
var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("DateTimeOffset");
var expectedInput =
"<input class=\"HtmlEncode[[text-box single-line]]\" data-val=\"HtmlEncode[[true]]\" " +
$"data-val-required=\"HtmlEncode[[{requiredMessage}]]\" id=\"HtmlEncode[[FieldPrefix]]\" " +
"name=\"HtmlEncode[[FieldPrefix]]\" type=\"HtmlEncode[[" +
expectedType +
"]]\" value=\"HtmlEncode[[" + expectedValue + "]]\" />";
var offset = TimeSpan.FromHours(-5);
var model = new DateTimeOffset(
year: 2000,
month: 1,
day: 2,
hour: 3,
minute: 4,
second: 5,
millisecond: 60,
offset: offset);
var viewEngine = new Mock<ICompositeViewEngine>(MockBehavior.Strict);
viewEngine
.Setup(v => v.GetView(/*executingFilePath*/ null, It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound(string.Empty, Enumerable.Empty<string>()));
viewEngine
.Setup(v => v.FindView(It.IsAny<ActionContext>(), It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound(string.Empty, Enumerable.Empty<string>()));
var provider = new TestModelMetadataProvider();
provider.ForType<DateTimeOffset>().DisplayDetails(dd =>
{
dd.DataTypeName = dataTypeName;
dd.EditFormatString = editFormatString; // What [DataType] does for given type.
dd.HasNonDefaultEditFormat = true;
});
var helper = DefaultTemplatesUtilities.GetHtmlHelper(
model,
Mock.Of<IUrlHelper>(),
viewEngine.Object,
provider);
helper.Html5DateRenderingMode = Html5DateRenderingMode.CurrentCulture;
helper.ViewData.TemplateInfo.HtmlFieldPrefix = "FieldPrefix";
// Act
var result = helper.Editor(string.Empty);
// Assert
Assert.Equal(expectedInput, HtmlContentUtilities.HtmlContentToString(result));
}
// Html5DateRenderingMode.Rfc3339 is enabled by default.
[Theory]
[InlineData(null, null, "2000-01-02T03:04:05.060", "datetime-local")]
[InlineData("date", null, "2000-01-02", "date")]
[InlineData("date", "{0:d}", "02/01/2000", "date")]
[InlineData("datetime", null, "2000-01-02T03:04:05.060", "datetime-local")]
[InlineData("datetime-local", null, "2000-01-02T03:04:05.060", "datetime-local")]
[InlineData("DateTimeOffset", null, "2000-01-02T03:04:05.060Z", "text")]
[InlineData("DateTimeOffset", "{0:o}", "2000-01-02T03:04:05.0600000Z", "text")]
[InlineData("time", null, "03:04:05.060", "time")]
[InlineData("time", "{0:t}", "03:04", "time")]
[InlineData("month", null, "2000-01", "month")]
[InlineData("month", "{0:yyyy/MM}", "2000/01", "month")]
[InlineData("week", null, "1999-W52", "week")]
[InlineData("Week", "{0:yyyy/'W1'}", "2000/W1", "week")]
[ReplaceCulture]
public void Editor_FindsCorrectDateOrTimeTemplate_ForDateTime(
string dataTypeName,
string editFormatString,
string expectedValue,
string expectedType)
{
// Arrange
var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("DateTime");
var expectedInput = "<input class=\"HtmlEncode[[text-box single-line]]\" data-val=\"HtmlEncode[[true]]\" " +
$"data-val-required=\"HtmlEncode[[{requiredMessage}]]\" id=\"HtmlEncode[[FieldPrefix]]\" " +
"name=\"HtmlEncode[[FieldPrefix]]\" type=\"HtmlEncode[[" +
expectedType +
"]]\" value=\"HtmlEncode[[" + expectedValue + "]]\" />";
var model = new DateTime(
year: 2000,
month: 1,
day: 2,
hour: 3,
minute: 4,
second: 5,
millisecond: 60,
kind: DateTimeKind.Utc);
var viewEngine = new Mock<ICompositeViewEngine>(MockBehavior.Strict);
viewEngine
.Setup(v => v.GetView(/*executingFilePath*/ null, It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound(string.Empty, Enumerable.Empty<string>()));
viewEngine
.Setup(v => v.FindView(It.IsAny<ActionContext>(), It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound(string.Empty, Enumerable.Empty<string>()));
var provider = new TestModelMetadataProvider();
provider.ForType<DateTime>().DisplayDetails(dd =>
{
dd.DataTypeName = dataTypeName;
dd.EditFormatString = editFormatString; // What [DataType] does for given type.
dd.HasNonDefaultEditFormat = true;
});
var helper = DefaultTemplatesUtilities.GetHtmlHelper(
model,
Mock.Of<IUrlHelper>(),
viewEngine.Object,
provider);
helper.ViewData.TemplateInfo.HtmlFieldPrefix = "FieldPrefix";
// Act
var result = helper.Editor(string.Empty);
// Assert
Assert.Equal(expectedInput, HtmlContentUtilities.HtmlContentToString(result));
}
// Html5DateRenderingMode.Rfc3339 can be disabled.
[Theory]
[InlineData(null, null, "02/01/2000 03:04:05", "datetime-local")]
[InlineData("date", null, "02/01/2000 03:04:05", "date")]
[InlineData("date", "{0:d}", "02/01/2000", "date")]
[InlineData("datetime", null, "02/01/2000 03:04:05", "datetime-local")]
[InlineData("datetime-local", null, "02/01/2000 03:04:05", "datetime-local")]
[InlineData("DateTimeOffset", null, "02/01/2000 03:04:05", "text")]
[InlineData("DateTimeOffset", "{0:o}", "2000-01-02T03:04:05.0600000Z", "text")]
[InlineData("time", "{0:t}", "03:04", "time")]
[InlineData("month", null, "2000-01", "month")]
[InlineData("month", "{0:yyyy/MM}", "2000/01", "month")]
[InlineData("week", null, "1999-W52", "week")]
[InlineData("Week", "{0:yyyy/'W1'}", "2000/W1", "week")]
[ReplaceCulture]
public void Editor_FindsCorrectDateOrTimeTemplate_ForDateTimeNotRfc3339(
string dataTypeName,
string editFormatString,
string expectedValue,
string expectedType)
{
// Arrange
var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("DateTime");
var expectedInput =
"<input class=\"HtmlEncode[[text-box single-line]]\" data-val=\"HtmlEncode[[true]]\" " +
$"data-val-required=\"HtmlEncode[[{requiredMessage}]]\" id=\"HtmlEncode[[FieldPrefix]]\" " +
"name=\"HtmlEncode[[FieldPrefix]]\" type=\"HtmlEncode[[" +
expectedType +
"]]\" value=\"HtmlEncode[[" + expectedValue + "]]\" />";
var model = new DateTime(
year: 2000,
month: 1,
day: 2,
hour: 3,
minute: 4,
second: 5,
millisecond: 60,
kind: DateTimeKind.Utc);
var viewEngine = new Mock<ICompositeViewEngine>(MockBehavior.Strict);
viewEngine
.Setup(v => v.GetView(/*executingFilePath*/ null, It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound(string.Empty, Enumerable.Empty<string>()));
viewEngine
.Setup(v => v.FindView(It.IsAny<ActionContext>(), It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound(string.Empty, Enumerable.Empty<string>()));
var provider = new TestModelMetadataProvider();
provider.ForType<DateTime>().DisplayDetails(dd =>
{
dd.DataTypeName = dataTypeName;
dd.EditFormatString = editFormatString; // What [DataType] does for given type.
dd.HasNonDefaultEditFormat = true;
});
var helper = DefaultTemplatesUtilities.GetHtmlHelper(
model,
Mock.Of<IUrlHelper>(),
viewEngine.Object,
provider);
helper.Html5DateRenderingMode = Html5DateRenderingMode.CurrentCulture;
helper.ViewData.TemplateInfo.HtmlFieldPrefix = "FieldPrefix";
// Act
var result = helper.Editor(string.Empty);
// Assert
Assert.Equal(expectedInput, HtmlContentUtilities.HtmlContentToString(result));
}
[Theory]
[InlineData(null, Html5DateRenderingMode.CurrentCulture, "text")]
[InlineData(null, Html5DateRenderingMode.Rfc3339, "text")]
[InlineData("date", Html5DateRenderingMode.CurrentCulture, "date")]
[InlineData("date", Html5DateRenderingMode.Rfc3339, "date")]
[InlineData("datetime", Html5DateRenderingMode.CurrentCulture, "datetime-local")]
[InlineData("datetime", Html5DateRenderingMode.Rfc3339, "datetime-local")]
[InlineData("datetime-local", Html5DateRenderingMode.CurrentCulture, "datetime-local")]
[InlineData("datetime-local", Html5DateRenderingMode.Rfc3339, "datetime-local")]
[InlineData("time", Html5DateRenderingMode.CurrentCulture, "time")]
[InlineData("time", Html5DateRenderingMode.Rfc3339, "time")]
[InlineData("month", Html5DateRenderingMode.CurrentCulture, "month")]
[InlineData("month", Html5DateRenderingMode.Rfc3339, "month")]
[InlineData("week", Html5DateRenderingMode.CurrentCulture, "week")]
[InlineData("week", Html5DateRenderingMode.Rfc3339, "week")]
public void Editor_AppliesNonDefaultEditFormat(string dataTypeName, Html5DateRenderingMode renderingMode, string expectedType)
{
// Arrange
var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("DateTimeOffset");
var expectedInput = "<input class=\"HtmlEncode[[text-box single-line]]\" data-val=\"HtmlEncode[[true]]\" " +
$"data-val-required=\"HtmlEncode[[{requiredMessage}]]\" id=\"HtmlEncode[[FieldPrefix]]\" " +
"name=\"HtmlEncode[[FieldPrefix]]\" type=\"HtmlEncode[[" +
expectedType +
"]]\" value=\"HtmlEncode[[Formatted as 2000-01-02T03:04:05.0600000+00:00]]\" />";
var offset = TimeSpan.FromHours(0);
var model = new DateTimeOffset(
year: 2000,
month: 1,
day: 2,
hour: 3,
minute: 4,
second: 5,
millisecond: 60,
offset: offset);
var viewEngine = new Mock<ICompositeViewEngine>(MockBehavior.Strict);
viewEngine
.Setup(v => v.GetView(/*executingFilePath*/ null, It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound(string.Empty, Enumerable.Empty<string>()));
viewEngine
.Setup(v => v.FindView(It.IsAny<ActionContext>(), It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound(string.Empty, Enumerable.Empty<string>()));
var provider = new TestModelMetadataProvider();
provider.ForType<DateTimeOffset>().DisplayDetails(dd =>
{
dd.DataTypeName = dataTypeName;
dd.EditFormatString = "Formatted as {0:O}"; // What [DataType] does for given type.
dd.HasNonDefaultEditFormat = true;
});
var helper = DefaultTemplatesUtilities.GetHtmlHelper(
model,
Mock.Of<IUrlHelper>(),
viewEngine.Object,
provider);
helper.Html5DateRenderingMode = renderingMode; // Ignored due to HasNonDefaultEditFormat.
helper.ViewData.TemplateInfo.HtmlFieldPrefix = "FieldPrefix";
// Act
var result = helper.Editor(string.Empty);
// Assert
Assert.Equal(expectedInput, HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void EditorFor_FindsModel()
{
// Arrange
var model = new DefaultTemplatesUtilities.ObjectTemplateModel { Property1 = "Model string" };
var viewEngine = new Mock<ICompositeViewEngine>(MockBehavior.Strict);
viewEngine
.Setup(v => v.GetView(/*executingFilePath*/ null, It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound(string.Empty, Enumerable.Empty<string>()));
viewEngine
.Setup(v => v.FindView(It.IsAny<ActionContext>(), It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound(string.Empty, Enumerable.Empty<string>()));
var helper = DefaultTemplatesUtilities.GetHtmlHelper(model, viewEngine.Object);
helper.ViewData["Property1"] = "ViewData string";
// Act
var result = helper.EditorFor(m => m.Property1);
// Assert
Assert.Equal(
"<input class=\"HtmlEncode[[text-box single-line]]\" id=\"HtmlEncode[[Property1]]\" name=\"HtmlEncode[[Property1]]\" type=\"HtmlEncode[[text]]\" value=\"HtmlEncode[[Model string]]\" />",
HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void Editor_FindsModel_IfNoViewDataMember()
{
// Arrange
var model = new DefaultTemplatesUtilities.ObjectTemplateModel { Property1 = "Model string" };
var viewEngine = new Mock<ICompositeViewEngine>(MockBehavior.Strict);
viewEngine
.Setup(v => v.GetView(/*executingFilePath*/ null, It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound(string.Empty, Enumerable.Empty<string>()));
viewEngine
.Setup(v => v.FindView(It.IsAny<ActionContext>(), It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound(string.Empty, Enumerable.Empty<string>()));
var helper = DefaultTemplatesUtilities.GetHtmlHelper(model, viewEngine.Object);
// Act
var result = helper.Editor("Property1");
// Assert
Assert.Equal(
"<input class=\"HtmlEncode[[text-box single-line]]\" id=\"HtmlEncode[[Property1]]\" name=\"HtmlEncode[[Property1]]\" type=\"HtmlEncode[[text]]\" value=\"HtmlEncode[[Model string]]\" />",
HtmlContentUtilities.HtmlContentToString(result));
}
[Theory]
[InlineData(null)]
[InlineData("")]
public void EditorFor_FindsModel_EvenIfNullOrEmpty(string propertyValue)
{
// Arrange
var model = new DefaultTemplatesUtilities.ObjectTemplateModel { Property1 = propertyValue, };
var viewEngine = new Mock<ICompositeViewEngine>(MockBehavior.Strict);
viewEngine
.Setup(v => v.GetView(/*executingFilePath*/ null, It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound(string.Empty, Enumerable.Empty<string>()));
viewEngine
.Setup(v => v.FindView(It.IsAny<ActionContext>(), It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound(string.Empty, Enumerable.Empty<string>()));
var helper = DefaultTemplatesUtilities.GetHtmlHelper(model, viewEngine.Object);
helper.ViewData["Property1"] = "ViewData string";
// Act
var result = helper.EditorFor(m => m.Property1);
// Assert
Assert.Equal(
"<input class=\"HtmlEncode[[text-box single-line]]\" id=\"HtmlEncode[[Property1]]\" name=\"HtmlEncode[[Property1]]\" type=\"HtmlEncode[[text]]\" value=\"\" />",
HtmlContentUtilities.HtmlContentToString(result));
}
[Fact]
public void EditorFor_DoesNotWrapExceptionThrowsDuringViewRendering()
{
// Arrange
var expectedMessage = "my exception message";
var model = new DefaultTemplatesUtilities.ObjectTemplateModel { Property1 = "Test string", };
var view = new Mock<IView>();
view.Setup(v => v.RenderAsync(It.IsAny<ViewContext>()))
.Returns(Task.Run(() =>
{
throw new FormatException(expectedMessage);
}));
var viewEngine = new Mock<ICompositeViewEngine>(MockBehavior.Strict);
viewEngine
.Setup(v => v.GetView(/*executingFilePath*/ null, It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound(string.Empty, Enumerable.Empty<string>()));
viewEngine
.Setup(v => v.FindView(It.IsAny<ActionContext>(), It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.Found("test-view", view.Object));
var helper = DefaultTemplatesUtilities.GetHtmlHelper(model, viewEngine.Object);
helper.ViewData["Property1"] = "ViewData string";
// Act and Assert
var ex = Assert.Throws<FormatException>(() => helper.EditorFor(m => m.Property1));
Assert.Equal(expectedMessage, ex.Message);
}
[Fact]
public void EditorForModel_CallsFindView_WithExpectedPath()
{
// Arrange
var viewEngine = new Mock<ICompositeViewEngine>(MockBehavior.Strict);
viewEngine
.Setup(v => v.GetView(/*executingFilePath*/ null, It.IsAny<string>(), /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound(string.Empty, Enumerable.Empty<string>()));
viewEngine
.Setup(v => v.FindView(It.IsAny<ActionContext>(), "EditorTemplates/String", /*isMainPage*/ false))
.Returns(ViewEngineResult.Found(string.Empty, new Mock<IView>().Object))
.Verifiable();
var html = DefaultTemplatesUtilities.GetHtmlHelper(new object(), viewEngine: viewEngine.Object);
// Act & Assert
html.Editor(expression: string.Empty, templateName: null, htmlFieldName: null, additionalViewData: null);
viewEngine.Verify();
}
private class OrderedModel
{
[Display(Order = 10001)]
public string LastProperty { get; set; }
public string Property3 { get; set; }
public string Property1 { get; set; }
public string Property2 { get; set; }
[Display(Order = 23)]
public string OrderedProperty3 { get; set; }
[Display(Order = 23)]
public string OrderedProperty2 { get; set; }
[Display(Order = 23)]
public string OrderedProperty1 { get; set; }
}
private class StubbyHtmlHelper : IHtmlHelper, IViewContextAware
{
private readonly IHtmlHelper _innerHelper;
public StubbyHtmlHelper(IHtmlHelper innerHelper)
{
_innerHelper = innerHelper;
}
public Html5DateRenderingMode Html5DateRenderingMode
{
get { return _innerHelper.Html5DateRenderingMode; }
set { _innerHelper.Html5DateRenderingMode = value; }
}
public string IdAttributeDotReplacement
{
get { return _innerHelper.IdAttributeDotReplacement; }
}
public IModelMetadataProvider MetadataProvider
{
get { return _innerHelper.MetadataProvider; }
}
public dynamic ViewBag
{
get { return _innerHelper.ViewBag; }
}
public ViewContext ViewContext
{
get { return _innerHelper.ViewContext; }
}
public ViewDataDictionary ViewData
{
get { return _innerHelper.ViewData; }
}
public ITempDataDictionary TempData
{
get { return _innerHelper.TempData; }
}
public UrlEncoder UrlEncoder
{
get { return _innerHelper.UrlEncoder; }
}
public void Contextualize(ViewContext viewContext)
{
(_innerHelper as IViewContextAware)?.Contextualize(viewContext);
}
public IHtmlContent ActionLink(
string linkText,
string actionName,
string controllerName,
string protocol,
string hostname,
string fragment,
object routeValues,
object htmlAttributes)
{
throw new NotImplementedException();
}
public IHtmlContent AntiForgeryToken()
{
throw new NotImplementedException();
}
public MvcForm BeginForm(
string actionName,
string controllerName,
object routeValues,
FormMethod method,
bool? antiforgery,
object htmlAttributes)
{
throw new NotImplementedException();
}
public MvcForm BeginRouteForm(
string routeName,
object routeValues,
FormMethod method,
bool? antiforgery,
object htmlAttributes)
{
throw new NotImplementedException();
}
public IHtmlContent CheckBox(string name, bool? isChecked, object htmlAttributes)
{
return HelperName("__CheckBox__", htmlAttributes);
}
public IHtmlContent Display(
string expression,
string templateName,
string htmlFieldName,
object additionalViewData)
{
throw new NotImplementedException();
}
public string DisplayName(string expression)
{
throw new NotImplementedException();
}
public string DisplayText(string name)
{
throw new NotImplementedException();
}
public IHtmlContent DropDownList(
string name,
IEnumerable<SelectListItem> selectList,
string optionLabel,
object htmlAttributes)
{
return HelperName("__DropDownList__", htmlAttributes);
}
public IHtmlContent Editor(
string expression,
string templateName,
string htmlFieldName,
object additionalViewData)
{
return _innerHelper.Editor(expression, templateName, htmlFieldName, additionalViewData);
}
public string Encode(string value)
{
throw new NotImplementedException();
}
public string Encode(object value)
{
return _innerHelper.Encode(value);
}
public void EndForm()
{
throw new NotImplementedException();
}
public string FormatValue(object value, string format)
{
throw new NotImplementedException();
}
public string GenerateIdFromName(string name)
{
throw new NotImplementedException();
}
public IEnumerable<SelectListItem> GetEnumSelectList<TEnum>() where TEnum : struct
{
throw new NotImplementedException();
}
public IEnumerable<SelectListItem> GetEnumSelectList(Type enumType)
{
throw new NotImplementedException();
}
public IHtmlContent Hidden(string name, object value, object htmlAttributes)
{
return HelperName("__Hidden__", htmlAttributes);
}
public string Id(string name)
{
throw new NotImplementedException();
}
public IHtmlContent Label(string expression, string labelText, object htmlAttributes)
{
return HelperName("__Label__", htmlAttributes);
}
public IHtmlContent ListBox(string name, IEnumerable<SelectListItem> selectList, object htmlAttributes)
{
throw new NotImplementedException();
}
public string Name(string name)
{
throw new NotImplementedException();
}
public Task<IHtmlContent> PartialAsync(
string partialViewName,
object model,
ViewDataDictionary viewData)
{
throw new NotImplementedException();
}
public IHtmlContent Password(string name, object value, object htmlAttributes)
{
return HelperName("__Password__", htmlAttributes);
}
public IHtmlContent RadioButton(string name, object value, bool? isChecked, object htmlAttributes)
{
return HelperName("__RadioButton__", htmlAttributes);
}
public IHtmlContent Raw(object value)
{
throw new NotImplementedException();
}
public IHtmlContent Raw(string value)
{
throw new NotImplementedException();
}
public Task RenderPartialAsync(string partialViewName, object model, ViewDataDictionary viewData)
{
throw new NotImplementedException();
}
public IHtmlContent RouteLink(
string linkText,
string routeName,
string protocol,
string hostName,
string fragment,
object routeValues,
object htmlAttributes)
{
throw new NotImplementedException();
}
public IHtmlContent TextArea(string name, string value, int rows, int columns, object htmlAttributes)
{
return HelperName("__TextArea__", htmlAttributes);
}
public IHtmlContent TextBox(string name, object value, string format, object htmlAttributes)
{
return HelperName("__TextBox__", htmlAttributes);
}
public IHtmlContent ValidationMessage(string modelName, string message, object htmlAttributes, string tag)
{
return HelperName("__ValidationMessage__", htmlAttributes);
}
public IHtmlContent ValidationSummary(
bool excludePropertyErrors,
string message,
object htmlAttributes,
string tag)
{
throw new NotImplementedException();
}
public string Value(string name, string format)
{
throw new NotImplementedException();
}
private IHtmlContent HelperName(string name, object htmlAttributes)
{
var htmlAttributesDictionary = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
var htmlAttributesString =
string.Join(" ", htmlAttributesDictionary.Select(entry => $"{ entry.Key }='{ entry.Value }'"));
var helperName = $"{ name } { htmlAttributesString }";
return new HtmlString(helperName.TrimEnd());
}
}
}
}
| |
namespace AlfrescoPowerPoint2003
{
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 Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AlfrescoPane));
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.grpAuthetication = 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.chkUseCIFS = new System.Windows.Forms.CheckBox();
this.txtCIFSServer = new System.Windows.Forms.TextBox();
this.txtWebClientURL = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.pnlWebBrowser = new System.Windows.Forms.Panel();
this.lnkShowConfiguration = new System.Windows.Forms.LinkLabel();
this.webBrowser = new System.Windows.Forms.WebBrowser();
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.pnlConfiguration.SuspendLayout();
this.grpConfiguration.SuspendLayout();
this.grpAuthetication.SuspendLayout();
this.grpDetails.SuspendLayout();
this.pnlWebBrowser.SuspendLayout();
this.SuspendLayout();
//
// 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, 686);
this.pnlConfiguration.TabIndex = 2;
//
// 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 2003";
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.grpAuthetication);
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, 504);
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, 467);
this.btnDetailsOK.Name = "btnDetailsOK";
this.btnDetailsOK.Size = new System.Drawing.Size(100, 28);
this.btnDetailsOK.TabIndex = 8;
this.btnDetailsOK.Text = "Save Settings";
this.btnDetailsOK.UseVisualStyleBackColor = false;
this.btnDetailsOK.Click += new System.EventHandler(this.btnDetailsOK_Click);
//
// btnDetailsCancel
//
this.btnDetailsCancel.BackColor = System.Drawing.SystemColors.ButtonFace;
this.btnDetailsCancel.Location = new System.Drawing.Point(204, 467);
this.btnDetailsCancel.Name = "btnDetailsCancel";
this.btnDetailsCancel.Size = new System.Drawing.Size(75, 28);
this.btnDetailsCancel.TabIndex = 7;
this.btnDetailsCancel.Text = "Reset";
this.btnDetailsCancel.UseVisualStyleBackColor = false;
this.btnDetailsCancel.Click += new System.EventHandler(this.btnDetailsCancel_Click);
//
// grpAuthetication
//
this.grpAuthetication.Controls.Add(this.chkRememberAuth);
this.grpAuthetication.Controls.Add(this.txtPassword);
this.grpAuthetication.Controls.Add(this.label8);
this.grpAuthetication.Controls.Add(this.txtUsername);
this.grpAuthetication.Controls.Add(this.label1);
this.grpAuthetication.Location = new System.Drawing.Point(12, 273);
this.grpAuthetication.Name = "grpAuthetication";
this.grpAuthetication.Size = new System.Drawing.Size(267, 153);
this.grpAuthetication.TabIndex = 6;
this.grpAuthetication.TabStop = false;
this.grpAuthetication.Text = "Authentication (Leave blank for NTLM)";
//
// 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.chkUseCIFS);
this.grpDetails.Controls.Add(this.txtCIFSServer);
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, 146);
this.grpDetails.TabIndex = 4;
this.grpDetails.TabStop = false;
this.grpDetails.Text = "Location";
//
// chkUseCIFS
//
this.chkUseCIFS.AutoSize = true;
this.chkUseCIFS.Location = new System.Drawing.Point(9, 75);
this.chkUseCIFS.Name = "chkUseCIFS";
this.chkUseCIFS.Size = new System.Drawing.Size(131, 17);
this.chkUseCIFS.TabIndex = 11;
this.chkUseCIFS.Text = "Use CIFS Connection:";
this.chkUseCIFS.UseVisualStyleBackColor = true;
this.chkUseCIFS.CheckedChanged += new System.EventHandler(this.chkUseCIFS_CheckedChanged);
//
// txtCIFSServer
//
this.txtCIFSServer.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest;
this.txtCIFSServer.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.CustomSource;
this.txtCIFSServer.Location = new System.Drawing.Point(29, 98);
this.txtCIFSServer.Name = "txtCIFSServer";
this.txtCIFSServer.Size = new System.Drawing.Size(231, 20);
this.txtCIFSServer.TabIndex = 9;
this.tipOptional.SetToolTip(this.txtCIFSServer, "The UNC path, or mapped drive, to the Alfresco CIFS server.\r\ne.g. \\\\myserver_a\\al" +
"fresco\\");
this.txtCIFSServer.TextChanged += new System.EventHandler(this.txtCIFSServer_TextChanged);
//
// 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.\r\ne.g. http://myserver:8080/alfresco/");
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:";
//
// pnlWebBrowser
//
this.pnlWebBrowser.BackColor = System.Drawing.Color.White;
this.pnlWebBrowser.Controls.Add(this.lnkShowConfiguration);
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, 686);
this.pnlWebBrowser.TabIndex = 5;
//
// 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 = 5;
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);
//
// 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.Navigated += new System.Windows.Forms.WebBrowserNavigatedEventHandler(this.webBrowser_Navigated);
//
// 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";
//
// AlfrescoPane
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(292, 686);
this.Controls.Add(this.pnlConfiguration);
this.Controls.Add(this.pnlWebBrowser);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "AlfrescoPane";
this.ShowInTaskbar = false;
this.Text = "Alfresco";
this.TopMost = true;
this.Load += new System.EventHandler(this.AlfrescoPane_Load);
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.AlfrescoPane_FormClosing);
this.pnlConfiguration.ResumeLayout(false);
this.grpConfiguration.ResumeLayout(false);
this.grpAuthetication.ResumeLayout(false);
this.grpAuthetication.PerformLayout();
this.grpDetails.ResumeLayout(false);
this.grpDetails.PerformLayout();
this.pnlWebBrowser.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Panel pnlConfiguration;
private System.Windows.Forms.GroupBox grpConfiguration;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.GroupBox grpDetails;
private System.Windows.Forms.TextBox txtCIFSServer;
private System.Windows.Forms.TextBox txtWebClientURL;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.ToolTip tipGeneral;
private System.Windows.Forms.ToolTip tipMandatory;
private System.Windows.Forms.ToolTip tipOptional;
private System.Windows.Forms.LinkLabel lnkBackToBrowser;
private System.Windows.Forms.Button btnDetailsOK;
private System.Windows.Forms.Button btnDetailsCancel;
private System.Windows.Forms.GroupBox grpAuthetication;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.TextBox txtUsername;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.CheckBox chkRememberAuth;
private System.Windows.Forms.TextBox txtPassword;
private System.Windows.Forms.Panel pnlWebBrowser;
private System.Windows.Forms.LinkLabel lnkShowConfiguration;
private System.Windows.Forms.WebBrowser webBrowser;
private System.Windows.Forms.CheckBox chkUseCIFS;
}
}
| |
namespace XenAdmin.SettingsPanels
{
partial class WlbAdvancedSettingsPage
{
/// <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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(WlbAdvancedSettingsPage));
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.labelOptAgr = new System.Windows.Forms.Label();
this.labelHistData = new System.Windows.Forms.Label();
this.labelRepSub = new System.Windows.Forms.Label();
this.labelVmMigInt = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.labelRecSev = new System.Windows.Forms.Label();
this.panelVmMigInt = new System.Windows.Forms.FlowLayoutPanel();
this.numericUpDownRelocationInterval = new System.Windows.Forms.NumericUpDown();
this.labelRelocationUnit = new System.Windows.Forms.Label();
this.labelRelocationDefault = new System.Windows.Forms.Label();
this.labelRecCnt = new System.Windows.Forms.Label();
this.panelRecCnt = new System.Windows.Forms.FlowLayoutPanel();
this.numericUpDownPollInterval = new System.Windows.Forms.NumericUpDown();
this.labelRecommendationIntervalUnit = new System.Windows.Forms.Label();
this.labelRecommendationIntervalDefault = new System.Windows.Forms.Label();
this.panelRecSev = new System.Windows.Forms.FlowLayoutPanel();
this.comboBoxOptimizationSeverity = new System.Windows.Forms.ComboBox();
this.labelRecommendationSeverityDefault = new System.Windows.Forms.Label();
this.panelOptAgr = new System.Windows.Forms.FlowLayoutPanel();
this.comboBoxAutoBalanceAggressiveness = new System.Windows.Forms.ComboBox();
this.labelAutoBalanceAggressivenessDefault = new System.Windows.Forms.Label();
this.panelHistData = new System.Windows.Forms.FlowLayoutPanel();
this.numericUpDownGroomingPeriod = new System.Windows.Forms.NumericUpDown();
this.labelGroomingUnits = new System.Windows.Forms.Label();
this.labelGroomingDefault = new System.Windows.Forms.Label();
this.panelRepSub = new System.Windows.Forms.FlowLayoutPanel();
this.labelSMTPServer = new System.Windows.Forms.Label();
this.textBoxSMTPServer = new System.Windows.Forms.TextBox();
this.LabelSmtpPort = new System.Windows.Forms.Label();
this.TextBoxSMTPServerPort = new System.Windows.Forms.TextBox();
this.sectionHeaderLabelRepSub = new XenAdmin.Controls.SectionHeaderLabel();
this.sectionHeaderLabelHistData = new XenAdmin.Controls.SectionHeaderLabel();
this.sectionHeaderLabelOptAgr = new XenAdmin.Controls.SectionHeaderLabel();
this.sectionHeaderLabelRecSev = new XenAdmin.Controls.SectionHeaderLabel();
this.sectionHeaderLabelVmMigInt = new XenAdmin.Controls.SectionHeaderLabel();
this.sectionHeaderLabelRecCnt = new XenAdmin.Controls.SectionHeaderLabel();
this.labelAuditTrail = new System.Windows.Forms.Label();
this.sectionHeaderLabelAuditTrail = new XenAdmin.Controls.SectionHeaderLabel();
this.comboBoxPoolAuditTrailLevel = new System.Windows.Forms.ComboBox();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.auditTrailPanel = new System.Windows.Forms.FlowLayoutPanel();
this.poolAuditTrailNote = new System.Windows.Forms.Label();
this.tableLayoutPanel1.SuspendLayout();
this.panelVmMigInt.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownRelocationInterval)).BeginInit();
this.panelRecCnt.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownPollInterval)).BeginInit();
this.panelRecSev.SuspendLayout();
this.panelOptAgr.SuspendLayout();
this.panelHistData.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownGroomingPeriod)).BeginInit();
this.panelRepSub.SuspendLayout();
this.auditTrailPanel.SuspendLayout();
this.SuspendLayout();
//
// tableLayoutPanel1
//
resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1");
this.tableLayoutPanel1.Controls.Add(this.labelAuditTrail, 0, 23);
this.tableLayoutPanel1.Controls.Add(this.sectionHeaderLabelAuditTrail, 0, 22);
this.tableLayoutPanel1.Controls.Add(this.label2, 0, 21);
this.tableLayoutPanel1.Controls.Add(this.sectionHeaderLabelRepSub, 0, 16);
this.tableLayoutPanel1.Controls.Add(this.sectionHeaderLabelHistData, 0, 13);
this.tableLayoutPanel1.Controls.Add(this.sectionHeaderLabelOptAgr, 0, 10);
this.tableLayoutPanel1.Controls.Add(this.labelOptAgr, 0, 11);
this.tableLayoutPanel1.Controls.Add(this.labelHistData, 0, 14);
this.tableLayoutPanel1.Controls.Add(this.sectionHeaderLabelRecSev, 0, 7);
this.tableLayoutPanel1.Controls.Add(this.labelRepSub, 0, 17);
this.tableLayoutPanel1.Controls.Add(this.sectionHeaderLabelVmMigInt, 0, 1);
this.tableLayoutPanel1.Controls.Add(this.labelVmMigInt, 0, 2);
this.tableLayoutPanel1.Controls.Add(this.label1, 0, 0);
this.tableLayoutPanel1.Controls.Add(this.labelRecSev, 0, 8);
this.tableLayoutPanel1.Controls.Add(this.panelVmMigInt, 0, 3);
this.tableLayoutPanel1.Controls.Add(this.sectionHeaderLabelRecCnt, 0, 4);
this.tableLayoutPanel1.Controls.Add(this.labelRecCnt, 0, 5);
this.tableLayoutPanel1.Controls.Add(this.panelRecCnt, 0, 6);
this.tableLayoutPanel1.Controls.Add(this.panelRecSev, 0, 9);
this.tableLayoutPanel1.Controls.Add(this.panelOptAgr, 0, 12);
this.tableLayoutPanel1.Controls.Add(this.panelHistData, 0, 15);
this.tableLayoutPanel1.Controls.Add(this.panelRepSub, 0, 18);
this.tableLayoutPanel1.Controls.Add(this.auditTrailPanel, 0, 24);
this.tableLayoutPanel1.Controls.Add(this.label3, 0, 20);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
//
// labelAuditTrail
//
resources.ApplyResources(this.labelAuditTrail, "labelAuditTrail");
this.labelAuditTrail.BackColor = System.Drawing.Color.Transparent;
this.labelAuditTrail.Name = "labelAuditTrail";
//
// sectionHeaderLabelAuditTrail
//
resources.ApplyResources(this.sectionHeaderLabelAuditTrail, "sectionHeaderLabelAuditTrail");
this.sectionHeaderLabelAuditTrail.FocusControl = this.comboBoxPoolAuditTrailLevel;
this.sectionHeaderLabelAuditTrail.LineColor = System.Drawing.SystemColors.ActiveBorder;
this.sectionHeaderLabelAuditTrail.LineLocation = XenAdmin.Controls.SectionHeaderLabel.VerticalAlignment.Middle;
this.sectionHeaderLabelAuditTrail.Name = "sectionHeaderLabelAuditTrail";
//
// comboBoxPoolAuditTrailLevel
//
this.comboBoxPoolAuditTrailLevel.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxPoolAuditTrailLevel.FormattingEnabled = true;
this.comboBoxPoolAuditTrailLevel.Items.AddRange(new object[] {
resources.GetString("comboBoxPoolAuditTrailLevel.Items"),
resources.GetString("comboBoxPoolAuditTrailLevel.Items1"),
resources.GetString("comboBoxPoolAuditTrailLevel.Items2")});
resources.ApplyResources(this.comboBoxPoolAuditTrailLevel, "comboBoxPoolAuditTrailLevel");
this.comboBoxPoolAuditTrailLevel.Name = "comboBoxPoolAuditTrailLevel";
this.comboBoxPoolAuditTrailLevel.SelectedIndexChanged += new System.EventHandler(this.comboBoxPoolAuditTrailLevel_SelectedIndexChanged);
//
// label2
//
resources.ApplyResources(this.label2, "label2");
this.label2.Name = "label2";
//
// labelOptAgr
//
resources.ApplyResources(this.labelOptAgr, "labelOptAgr");
this.labelOptAgr.Name = "labelOptAgr";
//
// labelHistData
//
resources.ApplyResources(this.labelHistData, "labelHistData");
this.labelHistData.BackColor = System.Drawing.Color.Transparent;
this.labelHistData.MaximumSize = new System.Drawing.Size(533, 45);
this.labelHistData.Name = "labelHistData";
//
// labelRepSub
//
resources.ApplyResources(this.labelRepSub, "labelRepSub");
this.labelRepSub.BackColor = System.Drawing.Color.Transparent;
this.labelRepSub.Name = "labelRepSub";
//
// labelVmMigInt
//
resources.ApplyResources(this.labelVmMigInt, "labelVmMigInt");
this.labelVmMigInt.BackColor = System.Drawing.Color.Transparent;
this.labelVmMigInt.Name = "labelVmMigInt";
//
// label1
//
resources.ApplyResources(this.label1, "label1");
this.label1.Name = "label1";
//
// labelRecSev
//
resources.ApplyResources(this.labelRecSev, "labelRecSev");
this.labelRecSev.Name = "labelRecSev";
//
// panelVmMigInt
//
resources.ApplyResources(this.panelVmMigInt, "panelVmMigInt");
this.panelVmMigInt.Controls.Add(this.numericUpDownRelocationInterval);
this.panelVmMigInt.Controls.Add(this.labelRelocationUnit);
this.panelVmMigInt.Controls.Add(this.labelRelocationDefault);
this.panelVmMigInt.Name = "panelVmMigInt";
//
// numericUpDownRelocationInterval
//
resources.ApplyResources(this.numericUpDownRelocationInterval, "numericUpDownRelocationInterval");
this.numericUpDownRelocationInterval.Maximum = new decimal(new int[] {
260,
0,
0,
0});
this.numericUpDownRelocationInterval.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.numericUpDownRelocationInterval.Name = "numericUpDownRelocationInterval";
this.numericUpDownRelocationInterval.Value = new decimal(new int[] {
1,
0,
0,
0});
this.numericUpDownRelocationInterval.ValueChanged += new System.EventHandler(this.numericUpDown_ValueChanged);
this.numericUpDownRelocationInterval.KeyUp += new System.Windows.Forms.KeyEventHandler(this.numericUpDownRelocationInterval_KeyUp);
//
// labelRelocationUnit
//
resources.ApplyResources(this.labelRelocationUnit, "labelRelocationUnit");
this.labelRelocationUnit.Name = "labelRelocationUnit";
//
// labelRelocationDefault
//
resources.ApplyResources(this.labelRelocationDefault, "labelRelocationDefault");
this.labelRelocationDefault.ForeColor = System.Drawing.Color.Gray;
this.labelRelocationDefault.Name = "labelRelocationDefault";
//
// labelRecCnt
//
resources.ApplyResources(this.labelRecCnt, "labelRecCnt");
this.labelRecCnt.Name = "labelRecCnt";
//
// panelRecCnt
//
resources.ApplyResources(this.panelRecCnt, "panelRecCnt");
this.panelRecCnt.Controls.Add(this.numericUpDownPollInterval);
this.panelRecCnt.Controls.Add(this.labelRecommendationIntervalUnit);
this.panelRecCnt.Controls.Add(this.labelRecommendationIntervalDefault);
this.panelRecCnt.Name = "panelRecCnt";
//
// numericUpDownPollInterval
//
resources.ApplyResources(this.numericUpDownPollInterval, "numericUpDownPollInterval");
this.numericUpDownPollInterval.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.numericUpDownPollInterval.Name = "numericUpDownPollInterval";
this.numericUpDownPollInterval.Value = new decimal(new int[] {
1,
0,
0,
0});
this.numericUpDownPollInterval.ValueChanged += new System.EventHandler(this.numericUpDownPollInterval_ValueChanged);
//
// labelRecommendationIntervalUnit
//
resources.ApplyResources(this.labelRecommendationIntervalUnit, "labelRecommendationIntervalUnit");
this.labelRecommendationIntervalUnit.Name = "labelRecommendationIntervalUnit";
//
// labelRecommendationIntervalDefault
//
resources.ApplyResources(this.labelRecommendationIntervalDefault, "labelRecommendationIntervalDefault");
this.labelRecommendationIntervalDefault.ForeColor = System.Drawing.Color.Gray;
this.labelRecommendationIntervalDefault.Name = "labelRecommendationIntervalDefault";
//
// panelRecSev
//
resources.ApplyResources(this.panelRecSev, "panelRecSev");
this.panelRecSev.Controls.Add(this.comboBoxOptimizationSeverity);
this.panelRecSev.Controls.Add(this.labelRecommendationSeverityDefault);
this.panelRecSev.Name = "panelRecSev";
//
// comboBoxOptimizationSeverity
//
this.comboBoxOptimizationSeverity.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxOptimizationSeverity.FormattingEnabled = true;
this.comboBoxOptimizationSeverity.Items.AddRange(new object[] {
resources.GetString("comboBoxOptimizationSeverity.Items"),
resources.GetString("comboBoxOptimizationSeverity.Items1"),
resources.GetString("comboBoxOptimizationSeverity.Items2"),
resources.GetString("comboBoxOptimizationSeverity.Items3")});
resources.ApplyResources(this.comboBoxOptimizationSeverity, "comboBoxOptimizationSeverity");
this.comboBoxOptimizationSeverity.Name = "comboBoxOptimizationSeverity";
this.comboBoxOptimizationSeverity.SelectedIndexChanged += new System.EventHandler(this.comboBoxOptimizationSeverity_SelectedIndexChanged);
//
// labelRecommendationSeverityDefault
//
resources.ApplyResources(this.labelRecommendationSeverityDefault, "labelRecommendationSeverityDefault");
this.labelRecommendationSeverityDefault.ForeColor = System.Drawing.Color.Gray;
this.labelRecommendationSeverityDefault.Name = "labelRecommendationSeverityDefault";
//
// panelOptAgr
//
resources.ApplyResources(this.panelOptAgr, "panelOptAgr");
this.panelOptAgr.Controls.Add(this.comboBoxAutoBalanceAggressiveness);
this.panelOptAgr.Controls.Add(this.labelAutoBalanceAggressivenessDefault);
this.panelOptAgr.Name = "panelOptAgr";
//
// comboBoxAutoBalanceAggressiveness
//
this.comboBoxAutoBalanceAggressiveness.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxAutoBalanceAggressiveness.FormattingEnabled = true;
this.comboBoxAutoBalanceAggressiveness.Items.AddRange(new object[] {
resources.GetString("comboBoxAutoBalanceAggressiveness.Items"),
resources.GetString("comboBoxAutoBalanceAggressiveness.Items1"),
resources.GetString("comboBoxAutoBalanceAggressiveness.Items2")});
resources.ApplyResources(this.comboBoxAutoBalanceAggressiveness, "comboBoxAutoBalanceAggressiveness");
this.comboBoxAutoBalanceAggressiveness.Name = "comboBoxAutoBalanceAggressiveness";
this.comboBoxAutoBalanceAggressiveness.SelectedIndexChanged += new System.EventHandler(this.comboBoxAutoBalanceAggressiveness_SelectedIndexChanged);
//
// labelAutoBalanceAggressivenessDefault
//
resources.ApplyResources(this.labelAutoBalanceAggressivenessDefault, "labelAutoBalanceAggressivenessDefault");
this.labelAutoBalanceAggressivenessDefault.ForeColor = System.Drawing.Color.Gray;
this.labelAutoBalanceAggressivenessDefault.Name = "labelAutoBalanceAggressivenessDefault";
//
// panelHistData
//
resources.ApplyResources(this.panelHistData, "panelHistData");
this.panelHistData.Controls.Add(this.numericUpDownGroomingPeriod);
this.panelHistData.Controls.Add(this.labelGroomingUnits);
this.panelHistData.Controls.Add(this.labelGroomingDefault);
this.panelHistData.Name = "panelHistData";
//
// numericUpDownGroomingPeriod
//
resources.ApplyResources(this.numericUpDownGroomingPeriod, "numericUpDownGroomingPeriod");
this.numericUpDownGroomingPeriod.Maximum = new decimal(new int[] {
260,
0,
0,
0});
this.numericUpDownGroomingPeriod.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.numericUpDownGroomingPeriod.Name = "numericUpDownGroomingPeriod";
this.numericUpDownGroomingPeriod.Value = new decimal(new int[] {
1,
0,
0,
0});
this.numericUpDownGroomingPeriod.ValueChanged += new System.EventHandler(this.numericUpDown_ValueChanged);
//
// labelGroomingUnits
//
resources.ApplyResources(this.labelGroomingUnits, "labelGroomingUnits");
this.labelGroomingUnits.Name = "labelGroomingUnits";
//
// labelGroomingDefault
//
resources.ApplyResources(this.labelGroomingDefault, "labelGroomingDefault");
this.labelGroomingDefault.ForeColor = System.Drawing.Color.Gray;
this.labelGroomingDefault.Name = "labelGroomingDefault";
//
// panelRepSub
//
resources.ApplyResources(this.panelRepSub, "panelRepSub");
this.panelRepSub.Controls.Add(this.labelSMTPServer);
this.panelRepSub.Controls.Add(this.textBoxSMTPServer);
this.panelRepSub.Controls.Add(this.LabelSmtpPort);
this.panelRepSub.Controls.Add(this.TextBoxSMTPServerPort);
this.panelRepSub.Name = "panelRepSub";
//
// labelSMTPServer
//
resources.ApplyResources(this.labelSMTPServer, "labelSMTPServer");
this.labelSMTPServer.Name = "labelSMTPServer";
//
// textBoxSMTPServer
//
resources.ApplyResources(this.textBoxSMTPServer, "textBoxSMTPServer");
this.textBoxSMTPServer.Name = "textBoxSMTPServer";
this.textBoxSMTPServer.TextChanged += new System.EventHandler(this.textBoxSMTPServer_TextChanged);
//
// LabelSmtpPort
//
resources.ApplyResources(this.LabelSmtpPort, "LabelSmtpPort");
this.LabelSmtpPort.Name = "LabelSmtpPort";
//
// TextBoxSMTPServerPort
//
resources.ApplyResources(this.TextBoxSMTPServerPort, "TextBoxSMTPServerPort");
this.TextBoxSMTPServerPort.Name = "TextBoxSMTPServerPort";
//
// sectionHeaderLabelRepSub
//
resources.ApplyResources(this.sectionHeaderLabelRepSub, "sectionHeaderLabelRepSub");
this.sectionHeaderLabelRepSub.FocusControl = this.textBoxSMTPServer;
this.sectionHeaderLabelRepSub.LineColor = System.Drawing.SystemColors.ActiveBorder;
this.sectionHeaderLabelRepSub.LineLocation = XenAdmin.Controls.SectionHeaderLabel.VerticalAlignment.Middle;
this.sectionHeaderLabelRepSub.MinimumSize = new System.Drawing.Size(0, 14);
this.sectionHeaderLabelRepSub.Name = "sectionHeaderLabelRepSub";
//
// sectionHeaderLabelHistData
//
resources.ApplyResources(this.sectionHeaderLabelHistData, "sectionHeaderLabelHistData");
this.sectionHeaderLabelHistData.FocusControl = this.numericUpDownGroomingPeriod;
this.sectionHeaderLabelHistData.LineColor = System.Drawing.SystemColors.ActiveBorder;
this.sectionHeaderLabelHistData.LineLocation = XenAdmin.Controls.SectionHeaderLabel.VerticalAlignment.Middle;
this.sectionHeaderLabelHistData.MinimumSize = new System.Drawing.Size(0, 14);
this.sectionHeaderLabelHistData.Name = "sectionHeaderLabelHistData";
//
// sectionHeaderLabelOptAgr
//
resources.ApplyResources(this.sectionHeaderLabelOptAgr, "sectionHeaderLabelOptAgr");
this.sectionHeaderLabelOptAgr.FocusControl = this.comboBoxAutoBalanceAggressiveness;
this.sectionHeaderLabelOptAgr.LineColor = System.Drawing.SystemColors.ActiveBorder;
this.sectionHeaderLabelOptAgr.LineLocation = XenAdmin.Controls.SectionHeaderLabel.VerticalAlignment.Middle;
this.sectionHeaderLabelOptAgr.MinimumSize = new System.Drawing.Size(0, 14);
this.sectionHeaderLabelOptAgr.Name = "sectionHeaderLabelOptAgr";
//
// sectionHeaderLabelRecSev
//
resources.ApplyResources(this.sectionHeaderLabelRecSev, "sectionHeaderLabelRecSev");
this.sectionHeaderLabelRecSev.FocusControl = this.comboBoxOptimizationSeverity;
this.sectionHeaderLabelRecSev.LineColor = System.Drawing.SystemColors.ActiveBorder;
this.sectionHeaderLabelRecSev.LineLocation = XenAdmin.Controls.SectionHeaderLabel.VerticalAlignment.Middle;
this.sectionHeaderLabelRecSev.MinimumSize = new System.Drawing.Size(0, 14);
this.sectionHeaderLabelRecSev.Name = "sectionHeaderLabelRecSev";
//
// sectionHeaderLabelVmMigInt
//
resources.ApplyResources(this.sectionHeaderLabelVmMigInt, "sectionHeaderLabelVmMigInt");
this.sectionHeaderLabelVmMigInt.FocusControl = this.numericUpDownRelocationInterval;
this.sectionHeaderLabelVmMigInt.LineColor = System.Drawing.SystemColors.ActiveBorder;
this.sectionHeaderLabelVmMigInt.LineLocation = XenAdmin.Controls.SectionHeaderLabel.VerticalAlignment.Middle;
this.sectionHeaderLabelVmMigInt.MinimumSize = new System.Drawing.Size(0, 14);
this.sectionHeaderLabelVmMigInt.Name = "sectionHeaderLabelVmMigInt";
//
// sectionHeaderLabelRecCnt
//
resources.ApplyResources(this.sectionHeaderLabelRecCnt, "sectionHeaderLabelRecCnt");
this.sectionHeaderLabelRecCnt.FocusControl = this.numericUpDownPollInterval;
this.sectionHeaderLabelRecCnt.LineColor = System.Drawing.SystemColors.ActiveBorder;
this.sectionHeaderLabelRecCnt.LineLocation = XenAdmin.Controls.SectionHeaderLabel.VerticalAlignment.Middle;
this.sectionHeaderLabelRecCnt.MinimumSize = new System.Drawing.Size(0, 14);
this.sectionHeaderLabelRecCnt.Name = "sectionHeaderLabelRecCnt";
//
// auditTrailPanel
//
this.auditTrailPanel.Controls.Add(this.comboBoxPoolAuditTrailLevel);
this.auditTrailPanel.Controls.Add(this.poolAuditTrailNote);
resources.ApplyResources(this.auditTrailPanel, "auditTrailPanel");
this.auditTrailPanel.Name = "auditTrailPanel";
//
// poolAuditTrailNote
//
resources.ApplyResources(this.poolAuditTrailNote, "poolAuditTrailNote");
this.poolAuditTrailNote.ForeColor = System.Drawing.Color.Gray;
this.poolAuditTrailNote.Name = "poolAuditTrailNote";
// label3
//
this.label3.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
resources.ApplyResources(this.label3, "label3");
this.label3.Name = "label3";
//
// WlbAdvancedSettingsPage
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.BackColor = System.Drawing.SystemColors.Window;
this.Controls.Add(this.tableLayoutPanel1);
this.Name = "WlbAdvancedSettingsPage";
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
this.panelVmMigInt.ResumeLayout(false);
this.panelVmMigInt.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownRelocationInterval)).EndInit();
this.panelRecCnt.ResumeLayout(false);
this.panelRecCnt.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownPollInterval)).EndInit();
this.panelRecSev.ResumeLayout(false);
this.panelRecSev.PerformLayout();
this.panelOptAgr.ResumeLayout(false);
this.panelOptAgr.PerformLayout();
this.panelHistData.ResumeLayout(false);
this.panelHistData.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownGroomingPeriod)).EndInit();
this.panelRepSub.ResumeLayout(false);
this.panelRepSub.PerformLayout();
this.auditTrailPanel.ResumeLayout(false);
this.auditTrailPanel.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label labelHistData;
private System.Windows.Forms.Label labelGroomingUnits;
private System.Windows.Forms.Label labelGroomingDefault;
private System.Windows.Forms.NumericUpDown numericUpDownGroomingPeriod;
private System.Windows.Forms.Label labelRepSub;
private System.Windows.Forms.Label labelSMTPServer;
private System.Windows.Forms.TextBox textBoxSMTPServer;
private System.Windows.Forms.ComboBox comboBoxOptimizationSeverity;
private System.Windows.Forms.ComboBox comboBoxAutoBalanceAggressiveness;
private System.Windows.Forms.Label labelRecSev;
private System.Windows.Forms.Label labelRecommendationIntervalUnit;
private System.Windows.Forms.NumericUpDown numericUpDownPollInterval;
private System.Windows.Forms.Label labelRecCnt;
private System.Windows.Forms.Label labelRecommendationSeverityDefault;
private System.Windows.Forms.Label labelRecommendationIntervalDefault;
private System.Windows.Forms.Label labelOptAgr;
private System.Windows.Forms.Label labelAutoBalanceAggressivenessDefault;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label LabelSmtpPort;
private System.Windows.Forms.TextBox TextBoxSMTPServerPort;
private System.Windows.Forms.FlowLayoutPanel panelVmMigInt;
private System.Windows.Forms.Label labelVmMigInt;
private System.Windows.Forms.NumericUpDown numericUpDownRelocationInterval;
private System.Windows.Forms.Label labelRelocationUnit;
private System.Windows.Forms.Label labelRelocationDefault;
private XenAdmin.Controls.SectionHeaderLabel sectionHeaderLabelVmMigInt;
private XenAdmin.Controls.SectionHeaderLabel sectionHeaderLabelRecCnt;
private XenAdmin.Controls.SectionHeaderLabel sectionHeaderLabelRecSev;
private System.Windows.Forms.FlowLayoutPanel panelRecCnt;
private System.Windows.Forms.FlowLayoutPanel panelRecSev;
private XenAdmin.Controls.SectionHeaderLabel sectionHeaderLabelOptAgr;
private System.Windows.Forms.FlowLayoutPanel panelOptAgr;
private XenAdmin.Controls.SectionHeaderLabel sectionHeaderLabelRepSub;
private XenAdmin.Controls.SectionHeaderLabel sectionHeaderLabelHistData;
private System.Windows.Forms.FlowLayoutPanel panelHistData;
private System.Windows.Forms.FlowLayoutPanel panelRepSub;
private System.Windows.Forms.Label labelAuditTrail;
private Controls.SectionHeaderLabel sectionHeaderLabelAuditTrail;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.FlowLayoutPanel auditTrailPanel;
private System.Windows.Forms.ComboBox comboBoxPoolAuditTrailLevel;
private System.Windows.Forms.Label poolAuditTrailNote;
private System.Windows.Forms.Label label3;
}
}
| |
/*
* Copyright (c) 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 OpenMetaverse.Packets;
namespace OpenMetaverse
{
[Serializable]
public class TerrainPatch
{
#region Enums and Structs
public enum LayerType : byte
{
Land = 0x4C,
Water = 0x57,
Wind = 0x37,
Cloud = 0x38
}
public struct GroupHeader
{
public int Stride;
public int PatchSize;
public LayerType Type;
}
public struct Header
{
public float DCOffset;
public int Range;
public int QuantWBits;
public int PatchIDs;
public uint WordBits;
public int X
{
get { return PatchIDs >> 5; }
set { PatchIDs += (value << 5); }
}
public int Y
{
get { return PatchIDs & 0x1F; }
set { PatchIDs |= value & 0x1F; }
}
}
#endregion Enums and Structs
/// <summary>X position of this patch</summary>
public int X;
/// <summary>Y position of this patch</summary>
public int Y;
/// <summary>A 16x16 array of floats holding decompressed layer data</summary>
public float[] Data;
}
public static class TerrainCompressor
{
public const int PATCHES_PER_EDGE = 16;
public const int END_OF_PATCHES = 97;
private const float OO_SQRT2 = 0.7071067811865475244008443621049f;
private const int STRIDE = 264;
private const int ZERO_CODE = 0x0;
private const int ZERO_EOB = 0x2;
private const int POSITIVE_VALUE = 0x6;
private const int NEGATIVE_VALUE = 0x7;
private static readonly float[] DequantizeTable16 = new float[16 * 16];
private static readonly float[] DequantizeTable32 = new float[16 * 16];
private static readonly float[] CosineTable16 = new float[16 * 16];
//private static readonly float[] CosineTable32 = new float[16 * 16];
private static readonly int[] CopyMatrix16 = new int[16 * 16];
private static readonly int[] CopyMatrix32 = new int[16 * 16];
private static readonly float[] QuantizeTable16 = new float[16 * 16];
static TerrainCompressor()
{
// Initialize the decompression tables
BuildDequantizeTable16();
SetupCosines16();
BuildCopyMatrix16();
BuildQuantizeTable16();
}
public static LayerDataPacket CreateLayerDataPacket(TerrainPatch[] patches, TerrainPatch.LayerType type)
{
LayerDataPacket layer = new LayerDataPacket();
layer.LayerID.Type = (byte)type;
TerrainPatch.GroupHeader header = new TerrainPatch.GroupHeader();
header.Stride = STRIDE;
header.PatchSize = 16;
header.Type = type;
// Should be enough to fit even the most poorly packed data
byte[] data = new byte[patches.Length * 16 * 16 * 2];
BitPack bitpack = new BitPack(data, 0);
bitpack.PackBits(header.Stride, 16);
bitpack.PackBits(header.PatchSize, 8);
bitpack.PackBits((int)header.Type, 8);
for (int i = 0; i < patches.Length; i++)
CreatePatch(bitpack, patches[i].Data, patches[i].X, patches[i].Y);
bitpack.PackBits(END_OF_PATCHES, 8);
layer.LayerData.Data = new byte[bitpack.BytePos + 1];
Buffer.BlockCopy(bitpack.Data, 0, layer.LayerData.Data, 0, bitpack.BytePos + 1);
return layer;
}
/// <summary>
/// Creates a LayerData packet for compressed land data given a full
/// simulator heightmap and an array of indices of patches to compress
/// </summary>
/// <param name="heightmap">A 256 * 256 array of floating point values
/// specifying the height at each meter in the simulator</param>
/// <param name="patches">Array of indexes in the 16x16 grid of patches
/// for this simulator. For example if 1 and 17 are specified, patches
/// x=1,y=0 and x=1,y=1 are sent</param>
/// <returns></returns>
public static LayerDataPacket CreateLandPacket(float[] heightmap, int[] patches)
{
LayerDataPacket layer = new LayerDataPacket();
layer.LayerID.Type = (byte)TerrainPatch.LayerType.Land;
TerrainPatch.GroupHeader header = new TerrainPatch.GroupHeader();
header.Stride = STRIDE;
header.PatchSize = 16;
header.Type = TerrainPatch.LayerType.Land;
byte[] data = new byte[1536];
BitPack bitpack = new BitPack(data, 0);
bitpack.PackBits(header.Stride, 16);
bitpack.PackBits(header.PatchSize, 8);
bitpack.PackBits((int)header.Type, 8);
for (int i = 0; i < patches.Length; i++)
CreatePatchFromHeightmap(bitpack, heightmap, patches[i] % 16, (patches[i] - (patches[i] % 16)) / 16);
bitpack.PackBits(END_OF_PATCHES, 8);
layer.LayerData.Data = new byte[bitpack.BytePos + 1];
Buffer.BlockCopy(bitpack.Data, 0, layer.LayerData.Data, 0, bitpack.BytePos + 1);
return layer;
}
public static LayerDataPacket CreateLandPacket(float[] patchData, int x, int y)
{
LayerDataPacket layer = new LayerDataPacket();
layer.LayerID.Type = (byte)TerrainPatch.LayerType.Land;
TerrainPatch.GroupHeader header = new TerrainPatch.GroupHeader();
header.Stride = STRIDE;
header.PatchSize = 16;
header.Type = TerrainPatch.LayerType.Land;
byte[] data = new byte[1536];
BitPack bitpack = new BitPack(data, 0);
bitpack.PackBits(header.Stride, 16);
bitpack.PackBits(header.PatchSize, 8);
bitpack.PackBits((int)header.Type, 8);
CreatePatch(bitpack, patchData, x, y);
bitpack.PackBits(END_OF_PATCHES, 8);
layer.LayerData.Data = new byte[bitpack.BytePos + 1];
Buffer.BlockCopy(bitpack.Data, 0, layer.LayerData.Data, 0, bitpack.BytePos + 1);
return layer;
}
public static LayerDataPacket CreateLandPacket(float[,] patchData, int x, int y)
{
LayerDataPacket layer = new LayerDataPacket();
layer.LayerID.Type = (byte)TerrainPatch.LayerType.Land;
TerrainPatch.GroupHeader header = new TerrainPatch.GroupHeader();
header.Stride = STRIDE;
header.PatchSize = 16;
header.Type = TerrainPatch.LayerType.Land;
byte[] data = new byte[1536];
BitPack bitpack = new BitPack(data, 0);
bitpack.PackBits(header.Stride, 16);
bitpack.PackBits(header.PatchSize, 8);
bitpack.PackBits((int)header.Type, 8);
CreatePatch(bitpack, patchData, x, y);
bitpack.PackBits(END_OF_PATCHES, 8);
layer.LayerData.Data = new byte[bitpack.BytePos + 1];
Buffer.BlockCopy(bitpack.Data, 0, layer.LayerData.Data, 0, bitpack.BytePos + 1);
return layer;
}
public static void CreatePatch(BitPack output, float[] patchData, int x, int y)
{
if (patchData.Length != 16 * 16)
throw new ArgumentException("Patch data must be a 16x16 array");
TerrainPatch.Header header = PrescanPatch(patchData);
header.QuantWBits = 136;
header.PatchIDs = (y & 0x1F);
header.PatchIDs += (x << 5);
// NOTE: No idea what prequant and postquant should be or what they do
int[] patch = CompressPatch(patchData, header, 10);
int wbits = EncodePatchHeader(output, header, patch);
EncodePatch(output, patch, 0, wbits);
}
public static void CreatePatch(BitPack output, float[,] patchData, int x, int y)
{
if (patchData.Length != 16 * 16)
throw new ArgumentException("Patch data must be a 16x16 array");
TerrainPatch.Header header = PrescanPatch(patchData);
header.QuantWBits = 136;
header.PatchIDs = (y & 0x1F);
header.PatchIDs += (x << 5);
// NOTE: No idea what prequant and postquant should be or what they do
int[] patch = CompressPatch(patchData, header, 10);
int wbits = EncodePatchHeader(output, header, patch);
EncodePatch(output, patch, 0, wbits);
}
/// <summary>
/// Add a patch of terrain to a BitPacker
/// </summary>
/// <param name="output">BitPacker to write the patch to</param>
/// <param name="heightmap">Heightmap of the simulator, must be a 256 *
/// 256 float array</param>
/// <param name="x">X offset of the patch to create, valid values are
/// from 0 to 15</param>
/// <param name="y">Y offset of the patch to create, valid values are
/// from 0 to 15</param>
public static void CreatePatchFromHeightmap(BitPack output, float[] heightmap, int x, int y)
{
if (heightmap.Length != 256 * 256)
throw new ArgumentException("Heightmap data must be 256x256");
if (x < 0 || x > 15 || y < 0 || y > 15)
throw new ArgumentException("X and Y patch offsets must be from 0 to 15");
TerrainPatch.Header header = PrescanPatch(heightmap, x, y);
header.QuantWBits = 136;
header.PatchIDs = (y & 0x1F);
header.PatchIDs += (x << 5);
// NOTE: No idea what prequant and postquant should be or what they do
int[] patch = CompressPatch(heightmap, x, y, header, 10);
int wbits = EncodePatchHeader(output, header, patch);
EncodePatch(output, patch, 0, wbits);
}
private static TerrainPatch.Header PrescanPatch(float[] patch)
{
TerrainPatch.Header header = new TerrainPatch.Header();
float zmax = -99999999.0f;
float zmin = 99999999.0f;
for (int j = 0; j < 16; j++)
{
for (int i = 0; i < 16; i++)
{
float val = patch[j * 16 + i];
if (val > zmax) zmax = val;
if (val < zmin) zmin = val;
}
}
header.DCOffset = zmin;
header.Range = (int)((zmax - zmin) + 1.0f);
return header;
}
private static TerrainPatch.Header PrescanPatch(float[,] patch)
{
TerrainPatch.Header header = new TerrainPatch.Header();
float zmax = -99999999.0f;
float zmin = 99999999.0f;
for (int j = 0; j < 16; j++)
{
for (int i = 0; i < 16; i++)
{
float val = patch[j, i];
if (val > zmax) zmax = val;
if (val < zmin) zmin = val;
}
}
header.DCOffset = zmin;
header.Range = (int)((zmax - zmin) + 1.0f);
return header;
}
private static TerrainPatch.Header PrescanPatch(float[] heightmap, int patchX, int patchY)
{
TerrainPatch.Header header = new TerrainPatch.Header();
float zmax = -99999999.0f;
float zmin = 99999999.0f;
for (int j = patchY * 16; j < (patchY + 1) * 16; j++)
{
for (int i = patchX * 16; i < (patchX + 1) * 16; i++)
{
float val = heightmap[j * 256 + i];
if (val > zmax) zmax = val;
if (val < zmin) zmin = val;
}
}
header.DCOffset = zmin;
header.Range = (int)((zmax - zmin) + 1.0f);
return header;
}
public static TerrainPatch.Header DecodePatchHeader(BitPack bitpack)
{
TerrainPatch.Header header = new TerrainPatch.Header();
// Quantized word bits
header.QuantWBits = bitpack.UnpackBits(8);
if (header.QuantWBits == END_OF_PATCHES)
return header;
// DC offset
header.DCOffset = bitpack.UnpackFloat();
// Range
header.Range = bitpack.UnpackBits(16);
// Patch IDs (10 bits)
header.PatchIDs = bitpack.UnpackBits(10);
// Word bits
header.WordBits = (uint)((header.QuantWBits & 0x0f) + 2);
return header;
}
private static int EncodePatchHeader(BitPack output, TerrainPatch.Header header, int[] patch)
{
int temp;
int wbits = (header.QuantWBits & 0x0f) + 2;
uint maxWbits = (uint)wbits + 5;
uint minWbits = ((uint)wbits >> 1);
wbits = (int)minWbits;
for (int i = 0; i < patch.Length; i++)
{
temp = patch[i];
if (temp != 0)
{
// Get the absolute value
if (temp < 0) temp *= -1;
for (int j = (int)maxWbits; j > (int)minWbits; j--)
{
if ((temp & (1 << j)) != 0)
{
if (j > wbits) wbits = j;
break;
}
}
}
}
wbits += 1;
header.QuantWBits &= 0xf0;
if (wbits > 17 || wbits < 2)
{
Logger.Log("Bits needed per word in EncodePatchHeader() are outside the allowed range",
Helpers.LogLevel.Error);
}
header.QuantWBits |= (wbits - 2);
output.PackBits(header.QuantWBits, 8);
output.PackFloat(header.DCOffset);
output.PackBits(header.Range, 16);
output.PackBits(header.PatchIDs, 10);
return wbits;
}
private static void IDCTColumn16(float[] linein, float[] lineout, int column)
{
float total;
int usize;
for (int n = 0; n < 16; n++)
{
total = OO_SQRT2 * linein[column];
for (int u = 1; u < 16; u++)
{
usize = u * 16;
total += linein[usize + column] * CosineTable16[usize + n];
}
lineout[16 * n + column] = total;
}
}
private static void IDCTLine16(float[] linein, float[] lineout, int line)
{
const float oosob = 2.0f / 16.0f;
int lineSize = line * 16;
float total;
for (int n = 0; n < 16; n++)
{
total = OO_SQRT2 * linein[lineSize];
for (int u = 1; u < 16; u++)
{
total += linein[lineSize + u] * CosineTable16[u * 16 + n];
}
lineout[lineSize + n] = total * oosob;
}
}
private static void DCTLine16(float[] linein, float[] lineout, int line)
{
float total = 0.0f;
int lineSize = line * 16;
for (int n = 0; n < 16; n++)
{
total += linein[lineSize + n];
}
lineout[lineSize] = OO_SQRT2 * total;
for (int u = 1; u < 16; u++)
{
total = 0.0f;
for (int n = 0; n < 16; n++)
{
total += linein[lineSize + n] * CosineTable16[u * 16 + n];
}
lineout[lineSize + u] = total;
}
}
private static void DCTColumn16(float[] linein, int[] lineout, int column)
{
float total = 0.0f;
const float oosob = 2.0f / 16.0f;
for (int n = 0; n < 16; n++)
{
total += linein[16 * n + column];
}
lineout[CopyMatrix16[column]] = (int)(OO_SQRT2 * total * oosob * QuantizeTable16[column]);
for (int u = 1; u < 16; u++)
{
total = 0.0f;
for (int n = 0; n < 16; n++)
{
total += linein[16 * n + column] * CosineTable16[u * 16 + n];
}
lineout[CopyMatrix16[16 * u + column]] = (int)(total * oosob * QuantizeTable16[16 * u + column]);
}
}
public static void DecodePatch(int[] patches, BitPack bitpack, TerrainPatch.Header header, int size)
{
int temp;
for (int n = 0; n < size * size; n++)
{
// ?
temp = bitpack.UnpackBits(1);
if (temp != 0)
{
// Value or EOB
temp = bitpack.UnpackBits(1);
if (temp != 0)
{
// Value
temp = bitpack.UnpackBits(1);
if (temp != 0)
{
// Negative
temp = bitpack.UnpackBits((int)header.WordBits);
patches[n] = temp * -1;
}
else
{
// Positive
temp = bitpack.UnpackBits((int)header.WordBits);
patches[n] = temp;
}
}
else
{
// Set the rest to zero
// TODO: This might not be necessary
for (int o = n; o < size * size; o++)
{
patches[o] = 0;
}
break;
}
}
else
{
patches[n] = 0;
}
}
}
private static void EncodePatch(BitPack output, int[] patch, int postquant, int wbits)
{
int temp;
bool eob;
if (postquant > 16 * 16 || postquant < 0)
{
Logger.Log("Postquant is outside the range of allowed values in EncodePatch()", Helpers.LogLevel.Error);
return;
}
if (postquant != 0) patch[16 * 16 - postquant] = 0;
for (int i = 0; i < 16 * 16; i++)
{
eob = false;
temp = patch[i];
if (temp == 0)
{
eob = true;
for (int j = i; j < 16 * 16 - postquant; j++)
{
if (patch[j] != 0)
{
eob = false;
break;
}
}
if (eob)
{
output.PackBits(ZERO_EOB, 2);
return;
}
else
{
output.PackBits(ZERO_CODE, 1);
}
}
else
{
if (temp < 0)
{
temp *= -1;
if (temp > (1 << wbits)) temp = (1 << wbits);
output.PackBits(NEGATIVE_VALUE, 3);
output.PackBits(temp, wbits);
}
else
{
if (temp > (1 << wbits)) temp = (1 << wbits);
output.PackBits(POSITIVE_VALUE, 3);
output.PackBits(temp, wbits);
}
}
}
}
public static float[] DecompressPatch(int[] patches, TerrainPatch.Header header, TerrainPatch.GroupHeader group)
{
float[] block = new float[group.PatchSize * group.PatchSize];
float[] output = new float[group.PatchSize * group.PatchSize];
int prequant = (header.QuantWBits >> 4) + 2;
int quantize = 1 << prequant;
float ooq = 1.0f / (float)quantize;
float mult = ooq * (float)header.Range;
float addval = mult * (float)(1 << (prequant - 1)) + header.DCOffset;
if (group.PatchSize == 16)
{
for (int n = 0; n < 16 * 16; n++)
{
block[n] = patches[CopyMatrix16[n]] * DequantizeTable16[n];
}
float[] ftemp = new float[16 * 16];
for (int o = 0; o < 16; o++)
IDCTColumn16(block, ftemp, o);
for (int o = 0; o < 16; o++)
IDCTLine16(ftemp, block, o);
}
else
{
for (int n = 0; n < 32 * 32; n++)
{
block[n] = patches[CopyMatrix32[n]] * DequantizeTable32[n];
}
Logger.Log("Implement IDCTPatchLarge", Helpers.LogLevel.Error);
}
for (int j = 0; j < block.Length; j++)
{
output[j] = block[j] * mult + addval;
}
return output;
}
private static int[] CompressPatch(float[] patchData, TerrainPatch.Header header, int prequant)
{
float[] block = new float[16 * 16];
int wordsize = prequant;
float oozrange = 1.0f / (float)header.Range;
float range = (float)(1 << prequant);
float premult = oozrange * range;
float sub = (float)(1 << (prequant - 1)) + header.DCOffset * premult;
header.QuantWBits = wordsize - 2;
header.QuantWBits |= (prequant - 2) << 4;
int k = 0;
for (int j = 0; j < 16; j++)
{
for (int i = 0; i < 16; i++)
block[k++] = patchData[j * 16 + i] * premult - sub;
}
float[] ftemp = new float[16 * 16];
int[] itemp = new int[16 * 16];
for (int o = 0; o < 16; o++)
DCTLine16(block, ftemp, o);
for (int o = 0; o < 16; o++)
DCTColumn16(ftemp, itemp, o);
return itemp;
}
private static int[] CompressPatch(float[,] patchData, TerrainPatch.Header header, int prequant)
{
float[] block = new float[16 * 16];
int wordsize = prequant;
float oozrange = 1.0f / (float)header.Range;
float range = (float)(1 << prequant);
float premult = oozrange * range;
float sub = (float)(1 << (prequant - 1)) + header.DCOffset * premult;
header.QuantWBits = wordsize - 2;
header.QuantWBits |= (prequant - 2) << 4;
int k = 0;
for (int j = 0; j < 16; j++)
{
for (int i = 0; i < 16; i++)
block[k++] = patchData[j, i] * premult - sub;
}
float[] ftemp = new float[16 * 16];
int[] itemp = new int[16 * 16];
for (int o = 0; o < 16; o++)
DCTLine16(block, ftemp, o);
for (int o = 0; o < 16; o++)
DCTColumn16(ftemp, itemp, o);
return itemp;
}
private static int[] CompressPatch(float[] heightmap, int patchX, int patchY, TerrainPatch.Header header, int prequant)
{
float[] block = new float[16 * 16];
int wordsize = prequant;
float oozrange = 1.0f / (float)header.Range;
float range = (float)(1 << prequant);
float premult = oozrange * range;
float sub = (float)(1 << (prequant - 1)) + header.DCOffset * premult;
header.QuantWBits = wordsize - 2;
header.QuantWBits |= (prequant - 2) << 4;
int k = 0;
for (int j = patchY * 16; j < (patchY + 1) * 16; j++)
{
for (int i = patchX * 16; i < (patchX + 1) * 16; i++)
block[k++] = heightmap[j * 256 + i] * premult - sub;
}
float[] ftemp = new float[16 * 16];
int[] itemp = new int[16 * 16];
for (int o = 0; o < 16; o++)
DCTLine16(block, ftemp, o);
for (int o = 0; o < 16; o++)
DCTColumn16(ftemp, itemp, o);
return itemp;
}
#region Initialization
private static void BuildDequantizeTable16()
{
for (int j = 0; j < 16; j++)
{
for (int i = 0; i < 16; i++)
{
DequantizeTable16[j * 16 + i] = 1.0f + 2.0f * (float)(i + j);
}
}
}
private static void BuildQuantizeTable16()
{
for (int j = 0; j < 16; j++)
{
for (int i = 0; i < 16; i++)
{
QuantizeTable16[j * 16 + i] = 1.0f / (1.0f + 2.0f * ((float)i + (float)j));
}
}
}
private static void SetupCosines16()
{
const float hposz = (float)Math.PI * 0.5f / 16.0f;
for (int u = 0; u < 16; u++)
{
for (int n = 0; n < 16; n++)
{
CosineTable16[u * 16 + n] = (float)Math.Cos((2.0f * (float)n + 1.0f) * (float)u * hposz);
}
}
}
private static void BuildCopyMatrix16()
{
bool diag = false;
bool right = true;
int i = 0;
int j = 0;
int count = 0;
while (i < 16 && j < 16)
{
CopyMatrix16[j * 16 + i] = count++;
if (!diag)
{
if (right)
{
if (i < 16 - 1) i++;
else j++;
right = false;
diag = true;
}
else
{
if (j < 16 - 1) j++;
else i++;
right = true;
diag = true;
}
}
else
{
if (right)
{
i++;
j--;
if (i == 16 - 1 || j == 0) diag = false;
}
else
{
i--;
j++;
if (j == 16 - 1 || i == 0) diag = false;
}
}
}
}
#endregion Initialization
}
}
| |
/*
* 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.Reflection;
using System.Collections.Generic;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Region.CoreModules.Framework.InterfaceCommander;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.PhysicsModules.SharedBase;
namespace OpenSim.Region.OptionalModules.PhysicsParameters
{
/// <summary>
/// </summary>
/// <remarks>
/// </remarks>
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "PhysicsParameters")]
public class PhysicsParameters : ISharedRegionModule
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// private static string LogHeader = "[PHYSICS PARAMETERS]";
private List<Scene> m_scenes = new List<Scene>();
private static bool m_commandsLoaded = false;
#region ISharedRegionModule
public string Name { get { return "Runtime Physics Parameter Module"; } }
public Type ReplaceableInterface { get { return null; } }
public void Initialise(IConfigSource source)
{
// m_log.DebugFormat("{0}: INITIALIZED MODULE", LogHeader);
}
public void PostInitialise()
{
// m_log.DebugFormat("[{0}: POST INITIALIZED MODULE", LogHeader);
InstallInterfaces();
}
public void Close()
{
// m_log.DebugFormat("{0}: CLOSED MODULE", LogHeader);
}
public void AddRegion(Scene scene)
{
// m_log.DebugFormat("{0}: REGION {1} ADDED", LogHeader, scene.RegionInfo.RegionName);
m_scenes.Add(scene);
}
public void RemoveRegion(Scene scene)
{
// m_log.DebugFormat("{0}: REGION {1} REMOVED", LogHeader, scene.RegionInfo.RegionName);
if (m_scenes.Contains(scene))
m_scenes.Remove(scene);
}
public void RegionLoaded(Scene scene)
{
// m_log.DebugFormat("{0}: REGION {1} LOADED", LogHeader, scene.RegionInfo.RegionName);
}
#endregion INonSharedRegionModule
private const string getInvocation = "physics get [<param>|ALL]";
private const string setInvocation = "physics set <param> [<value>|TRUE|FALSE] [localID|ALL]";
private const string listInvocation = "physics list";
private void InstallInterfaces()
{
if (!m_commandsLoaded)
{
MainConsole.Instance.Commands.AddCommand(
"Regions", false, "physics set",
setInvocation,
"Set physics parameter from currently selected region",
ProcessPhysicsSet);
MainConsole.Instance.Commands.AddCommand(
"Regions", false, "physics get",
getInvocation,
"Get physics parameter from currently selected region",
ProcessPhysicsGet);
MainConsole.Instance.Commands.AddCommand(
"Regions", false, "physics list",
listInvocation,
"List settable physics parameters",
ProcessPhysicsList);
m_commandsLoaded = true;
}
}
// TODO: extend get so you can get a value from an individual localID
private void ProcessPhysicsGet(string module, string[] cmdparms)
{
if (cmdparms.Length != 3)
{
WriteError("Parameter count error. Invocation: " + getInvocation);
return;
}
string parm = cmdparms[2];
if (SceneManager.Instance == null || SceneManager.Instance.CurrentScene == null)
{
WriteError("Error: no region selected. Use 'change region' to select a region.");
return;
}
Scene scene = SceneManager.Instance.CurrentScene;
IPhysicsParameters physScene = scene.PhysicsScene as IPhysicsParameters;
if (physScene != null)
{
if (parm.ToLower() == "all")
{
foreach (PhysParameterEntry ppe in physScene.GetParameterList())
{
string val = string.Empty;
if (physScene.GetPhysicsParameter(ppe.name, out val))
{
WriteOut(" {0}/{1} = {2}", scene.RegionInfo.RegionName, ppe.name, val);
}
else
{
WriteOut(" {0}/{1} = {2}", scene.RegionInfo.RegionName, ppe.name, "unknown");
}
}
}
else
{
string val = string.Empty;
if (physScene.GetPhysicsParameter(parm, out val))
{
WriteOut(" {0}/{1} = {2}", scene.RegionInfo.RegionName, parm, val);
}
else
{
WriteError("Failed fetch of parameter '{0}' from region '{1}'", parm, scene.RegionInfo.RegionName);
}
}
}
else
{
WriteError("Region '{0}' physics engine has no gettable physics parameters", scene.RegionInfo.RegionName);
}
return;
}
private void ProcessPhysicsSet(string module, string[] cmdparms)
{
if (cmdparms.Length < 4 || cmdparms.Length > 5)
{
WriteError("Parameter count error. Invocation: " + getInvocation);
return;
}
string parm = "xxx";
string valparm = String.Empty;
uint localID = (uint)PhysParameterEntry.APPLY_TO_NONE; // set default value
try
{
parm = cmdparms[2];
valparm = cmdparms[3].ToLower();
if (cmdparms.Length > 4)
{
if (cmdparms[4].ToLower() == "all")
localID = (uint)PhysParameterEntry.APPLY_TO_ALL;
else
localID = uint.Parse(cmdparms[2], Culture.NumberFormatInfo);
}
}
catch
{
WriteError(" Error parsing parameters. Invocation: " + setInvocation);
return;
}
if (SceneManager.Instance == null || SceneManager.Instance.CurrentScene == null)
{
WriteError("Error: no region selected. Use 'change region' to select a region.");
return;
}
Scene scene = SceneManager.Instance.CurrentScene;
IPhysicsParameters physScene = scene.PhysicsScene as IPhysicsParameters;
if (physScene != null)
{
if (!physScene.SetPhysicsParameter(parm, valparm, localID))
{
WriteError("Failed set of parameter '{0}' for region '{1}'", parm, scene.RegionInfo.RegionName);
}
}
else
{
WriteOut("Region '{0}'s physics engine has no settable physics parameters", scene.RegionInfo.RegionName);
}
return;
}
private void ProcessPhysicsList(string module, string[] cmdparms)
{
if (SceneManager.Instance == null || SceneManager.Instance.CurrentScene == null)
{
WriteError("Error: no region selected. Use 'change region' to select a region.");
return;
}
Scene scene = SceneManager.Instance.CurrentScene;
IPhysicsParameters physScene = scene.PhysicsScene as IPhysicsParameters;
if (physScene != null)
{
WriteOut("Available physics parameters:");
PhysParameterEntry[] parms = physScene.GetParameterList();
foreach (PhysParameterEntry ent in parms)
{
WriteOut(" {0}: {1}", ent.name, ent.desc);
}
}
else
{
WriteError("Current regions's physics engine has no settable physics parameters");
}
return;
}
private void WriteOut(string msg, params object[] args)
{
// m_log.InfoFormat(msg, args);
MainConsole.Instance.OutputFormat(msg, args);
}
private void WriteError(string msg, params object[] args)
{
// m_log.ErrorFormat(msg, args);
MainConsole.Instance.OutputFormat(msg, args);
}
}
}
| |
/*
* Copyright 2016 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;
namespace FlatBuffers.Test
{
[FlatBuffersTestClass]
public class FlatBufferBuilderTests
{
private FlatBufferBuilder CreateBuffer(bool forceDefaults = true)
{
var fbb = new FlatBufferBuilder(16) {ForceDefaults = forceDefaults};
fbb.StartObject(1);
return fbb;
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WithForceDefaults_WhenAddBool_AndDefaultValue_OffsetIncreasesBySize()
{
var fbb = CreateBuffer();
var storedOffset = fbb.Offset;
fbb.AddBool(0, false, false);
var endOffset = fbb.Offset;
Assert.AreEqual(sizeof(bool), endOffset-storedOffset);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WithForceDefaults_WhenAddSByte_AndDefaultValue_OffsetIncreasesBySize()
{
var fbb = CreateBuffer();
var storedOffset = fbb.Offset;
fbb.AddSbyte(0, 0, 0);
var endOffset = fbb.Offset;
Assert.AreEqual(sizeof(sbyte), endOffset - storedOffset);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WithForceDefaults_WhenAddByte_AndDefaultValue_OffsetIncreasesBySize()
{
var fbb = CreateBuffer();
var storedOffset = fbb.Offset;
fbb.AddByte(0, 0, 0);
var endOffset = fbb.Offset;
Assert.AreEqual(sizeof(byte), endOffset - storedOffset);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WithForceDefaults_WhenAddShort_AndDefaultValue_OffsetIncreasesBySize()
{
var fbb = CreateBuffer();
var storedOffset = fbb.Offset;
fbb.AddShort(0, 0, 0);
var endOffset = fbb.Offset;
Assert.AreEqual(sizeof(short), endOffset - storedOffset);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WithForceDefaults_WhenAddUShort_AndDefaultValue_OffsetIncreasesBySize()
{
var fbb = CreateBuffer();
var storedOffset = fbb.Offset;
fbb.AddUshort(0, 0, 0);
var endOffset = fbb.Offset;
Assert.AreEqual(sizeof(ushort), endOffset - storedOffset);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WithForceDefaults_WhenAddInt_AndDefaultValue_OffsetIncreasesBySize()
{
var fbb = CreateBuffer();
var storedOffset = fbb.Offset;
fbb.AddInt(0, 0, 0);
var endOffset = fbb.Offset;
Assert.AreEqual(sizeof(int), endOffset - storedOffset);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WithForceDefaults_WhenAddUInt_AndDefaultValue_OffsetIncreasesBySize()
{
var fbb = CreateBuffer();
var storedOffset = fbb.Offset;
fbb.AddUint(0, 0, 0);
var endOffset = fbb.Offset;
Assert.AreEqual(sizeof(uint), endOffset - storedOffset);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WithForceDefaults_WhenAddLong_AndDefaultValue_OffsetIncreasesBySize()
{
var fbb = CreateBuffer();
var storedOffset = fbb.Offset;
fbb.AddLong(0, 0, 0);
var endOffset = fbb.Offset;
Assert.AreEqual(sizeof(long), endOffset - storedOffset);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WithForceDefaults_WhenAddULong_AndDefaultValue_OffsetIncreasesBySize()
{
var fbb = CreateBuffer();
var storedOffset = fbb.Offset;
fbb.AddUlong(0, 0, 0);
var endOffset = fbb.Offset;
Assert.AreEqual(sizeof(ulong), endOffset - storedOffset);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WithForceDefaults_WhenAddFloat_AndDefaultValue_OffsetIncreasesBySize()
{
var fbb = CreateBuffer();
var storedOffset = fbb.Offset;
fbb.AddFloat(0, 0, 0);
var endOffset = fbb.Offset;
Assert.AreEqual(sizeof(float), endOffset - storedOffset);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WithForceDefaults_WhenAddDouble_AndDefaultValue_OffsetIncreasesBySize()
{
var fbb = CreateBuffer();
var storedOffset = fbb.Offset;
fbb.AddDouble(0, 0, 0);
var endOffset = fbb.Offset;
Assert.AreEqual(sizeof(double), endOffset - storedOffset);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WhenAddBool_AndDefaultValue_OffsetIsUnchanged()
{
var fbb = CreateBuffer(false);
var storedOffset = fbb.Offset;
fbb.AddBool(0, false, false);
var endOffset = fbb.Offset;
Assert.AreEqual(endOffset, storedOffset);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WhenAddSByte_AndDefaultValue_OffsetIsUnchanged()
{
var fbb = CreateBuffer(false);
var storedOffset = fbb.Offset;
fbb.AddSbyte(0, 0, 0);
var endOffset = fbb.Offset;
Assert.AreEqual(endOffset, storedOffset);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WhenAddByte_AndDefaultValue_OffsetIsUnchanged()
{
var fbb = CreateBuffer(false);
var storedOffset = fbb.Offset;
fbb.AddByte(0, 0, 0);
var endOffset = fbb.Offset;
Assert.AreEqual(endOffset, storedOffset);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WhenAddShort_AndDefaultValue_OffsetIsUnchanged()
{
var fbb = CreateBuffer(false);
var storedOffset = fbb.Offset;
fbb.AddShort(0, 0, 0);
var endOffset = fbb.Offset;
Assert.AreEqual(endOffset, storedOffset);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WhenAddUShort_AndDefaultValue_OffsetIsUnchanged()
{
var fbb = CreateBuffer(false);
var storedOffset = fbb.Offset;
fbb.AddUshort(0, 0, 0);
var endOffset = fbb.Offset;
Assert.AreEqual(endOffset, storedOffset);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WhenAddInt_AndDefaultValue_OffsetIsUnchanged()
{
var fbb = CreateBuffer(false);
var storedOffset = fbb.Offset;
fbb.AddInt(0, 0, 0);
var endOffset = fbb.Offset;
Assert.AreEqual(endOffset, storedOffset);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WhenAddUInt_AndDefaultValue_OffsetIsUnchanged()
{
var fbb = CreateBuffer(false);
var storedOffset = fbb.Offset;
fbb.AddUint(0, 0, 0);
var endOffset = fbb.Offset;
Assert.AreEqual(endOffset, storedOffset);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WhenAddLong_AndDefaultValue_OffsetIsUnchanged()
{
var fbb = CreateBuffer(false);
var storedOffset = fbb.Offset;
fbb.AddLong(0, 0, 0);
var endOffset = fbb.Offset;
Assert.AreEqual(endOffset, storedOffset);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WhenAddULong_AndDefaultValue_OffsetIsUnchanged()
{
var fbb = CreateBuffer(false);
var storedOffset = fbb.Offset;
fbb.AddUlong(0, 0, 0);
var endOffset = fbb.Offset;
Assert.AreEqual(endOffset, storedOffset);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WhenAddFloat_AndDefaultValue_OffsetIsUnchanged()
{
var fbb = CreateBuffer(false);
var storedOffset = fbb.Offset;
fbb.AddFloat(0, 0, 0);
var endOffset = fbb.Offset;
Assert.AreEqual(endOffset, storedOffset);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WhenAddDouble_AndDefaultValue_OffsetIsUnchanged()
{
var fbb = CreateBuffer(false);
var storedOffset = fbb.Offset;
fbb.AddDouble(0, 0, 0);
var endOffset = fbb.Offset;
Assert.AreEqual(endOffset, storedOffset);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_Add_Array_Float()
{
var fbb = CreateBuffer(false);
var storedOffset = fbb.Offset;
const int len = 9;
// Construct the data array
var data = new float[len];
data[0] = 1.0079F;
data[1] = 4.0026F;
data[2] = 6.941F;
data[3] = 9.0122F;
data[4] = 10.811F;
data[5] = 12.0107F;
data[6] = 14.0067F;
data[7] = 15.9994F;
data[8] = 18.9984F;
fbb.Add(data);
var endOffset = fbb.Offset;
Assert.AreEqual(endOffset, storedOffset + sizeof(float) * data.Length);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_Add_Array_Bool()
{
var fbb = CreateBuffer(false);
var storedOffset = fbb.Offset;
const int len = 9;
// Construct the data array
var data = new bool[len];
data[0] = true;
data[1] = true;
data[2] = false;
data[3] = true;
data[4] = false;
data[5] = true;
data[6] = true;
data[7] = true;
data[8] = false;
fbb.Add(data);
var endOffset = fbb.Offset;
Assert.AreEqual(endOffset, storedOffset + sizeof(bool) * data.Length);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_Add_Array_Double()
{
var fbb = CreateBuffer(false);
var storedOffset = fbb.Offset;
const int len = 9;
// Construct the data array
var data = new double[len];
data[0] = 1.0079;
data[1] = 4.0026;
data[2] = 6.941;
data[3] = 9.0122;
data[4] = 10.811;
data[5] = 12.0107;
data[6] = 14.0067;
data[7] = 15.9994;
data[8] = 18.9984;
fbb.Add(data);
var endOffset = fbb.Offset;
Assert.AreEqual(endOffset, storedOffset + sizeof(double) * data.Length);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_Add_Array_Null_Throws()
{
var fbb = CreateBuffer(false);
// Construct the data array
float[] data = null;
Assert.Throws<ArgumentNullException>(() => fbb.Add(data));
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_Add_Array_Empty_Noop()
{
var fbb = CreateBuffer(false);
var storedOffset = fbb.Offset;
// Construct an empty data array
float[] data = new float[0];
fbb.Add(data);
// Make sure the offset didn't change since nothing
// was really added
var endOffset = fbb.Offset;
Assert.AreEqual(endOffset, storedOffset);
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.Windows.Forms;
using OpenLiveWriter.ApplicationFramework.Preferences;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.CoreServices.Layout;
using OpenLiveWriter.Localization;
namespace OpenLiveWriter.SpellChecker
{
/// <summary>
/// Summary description for SpellingOptions.
/// </summary>
public class SpellingPreferencesPanel : PreferencesPanel
{
//private GroupBox groupBoxInternationalDictionaries;
private GroupBox _groupBoxGeneralOptions;
private CheckBox _checkBoxIgnoreUppercase;
private CheckBox _checkBoxIgnoreNumbers;
//private PictureBox pictureBoxInternationalDictionaries;
//private Label labelDictionary;
/// <summary>
/// Required designer variable.
/// </summary>
private Container components = null;
private CheckBox _checkBoxCheckBeforePublish;
private CheckBox _checkBoxRealTimeChecking;
private CheckBox _checkBoxAutoCorrect;
private System.Windows.Forms.Label _labelDictionaryLanguage;
private System.Windows.Forms.ComboBox _comboBoxLanguage;
private SpellingPreferences spellingPreferences;
public SpellingPreferencesPanel()
: this(new SpellingPreferences())
{
}
public SpellingPreferencesPanel(SpellingPreferences preferences)
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
_labelDictionaryLanguage.Text = Res.Get(StringId.DictionaryLanguageLabel);
_groupBoxGeneralOptions.Text = Res.Get(StringId.SpellingPrefOptions);
_checkBoxRealTimeChecking.Text = Res.Get(StringId.SpellingPrefReal);
_checkBoxIgnoreNumbers.Text = Res.Get(StringId.SpellingPrefNum);
_checkBoxIgnoreUppercase.Text = Res.Get(StringId.SpellingPrefUpper);
_checkBoxCheckBeforePublish.Text = Res.Get(StringId.SpellingPrefPub);
_checkBoxAutoCorrect.Text = Res.Get(StringId.SpellingPrefAuto);
PanelName = Res.Get(StringId.SpellingPrefName);
// set panel bitmap
PanelBitmap = _spellingPanelBitmap;
// initialize preferences
spellingPreferences = preferences;
spellingPreferences.PreferencesModified += new EventHandler(spellingPreferences_PreferencesModified);
// core options
_checkBoxIgnoreUppercase.Checked = spellingPreferences.IgnoreUppercase;
_checkBoxIgnoreNumbers.Checked = spellingPreferences.IgnoreWordsWithNumbers;
_checkBoxCheckBeforePublish.Checked = spellingPreferences.CheckSpellingBeforePublish;
_checkBoxRealTimeChecking.Checked = spellingPreferences.RealTimeSpellChecking;
_checkBoxAutoCorrect.Checked = spellingPreferences.EnableAutoCorrect;
// initialize language combo
_comboBoxLanguage.BeginUpdate();
_comboBoxLanguage.Items.Clear();
SpellingCheckerLanguage currentLanguage = spellingPreferences.Language;
SpellingLanguageEntry[] languages = SpellingSettings.GetInstalledLanguages();
Array.Sort(languages, new SentryLanguageEntryComparer(CultureInfo.CurrentUICulture));
foreach (SpellingLanguageEntry language in languages)
{
int index = _comboBoxLanguage.Items.Add(language);
if (language.Language == currentLanguage)
_comboBoxLanguage.SelectedIndex = index;
}
// defend against invalid value
if (_comboBoxLanguage.SelectedIndex == -1)
{
Debug.Fail("Language in registry not supported!");
}
_comboBoxLanguage.EndUpdate();
ManageSpellingOptions();
// hookup to changed events to update preferences
_checkBoxIgnoreUppercase.CheckedChanged += new EventHandler(checkBoxIgnoreUppercase_CheckedChanged);
_checkBoxIgnoreNumbers.CheckedChanged += new EventHandler(checkBoxIgnoreNumbers_CheckedChanged);
_checkBoxCheckBeforePublish.CheckedChanged += new EventHandler(checkBoxCheckBeforePublish_CheckedChanged);
_checkBoxRealTimeChecking.CheckedChanged += new EventHandler(checkBoxRealTimeChecking_CheckedChanged);
_checkBoxAutoCorrect.CheckedChanged += new EventHandler(checkBoxAutoCorrect_CheckedChanged);
_comboBoxLanguage.SelectedIndexChanged += new EventHandler(comboBoxLanguage_SelectedIndexChanged);
}
private void ManageSpellingOptions()
{
bool enabled = _comboBoxLanguage.SelectedIndex != 0; // "None"
_checkBoxIgnoreUppercase.Enabled = enabled;
_checkBoxIgnoreNumbers.Enabled = enabled;
_checkBoxCheckBeforePublish.Enabled = enabled;
_checkBoxRealTimeChecking.Enabled = enabled;
_checkBoxAutoCorrect.Enabled = enabled;
}
private class SentryLanguageEntryComparer : IComparer
{
private CultureInfo cultureInfo;
public SentryLanguageEntryComparer(CultureInfo cultureInfo)
{
this.cultureInfo = cultureInfo;
}
public int Compare(object x, object y)
{
return string.Compare(
((SpellingLanguageEntry)x).DisplayName,
((SpellingLanguageEntry)y).DisplayName,
true,
cultureInfo);
}
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
DisplayHelper.AutoFitSystemCombo(_comboBoxLanguage, _comboBoxLanguage.Width,
_groupBoxGeneralOptions.Width - _comboBoxLanguage.Left - 8,
false);
LayoutHelper.FixupGroupBox(8, _groupBoxGeneralOptions);
}
/// <summary>
/// Save data
/// </summary>
public override void Save()
{
if (spellingPreferences.IsModified())
spellingPreferences.Save();
}
/// <summary>
/// flagsPreferences_PreferencesModified event handler.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">An EventArgs that contains the event data.</param>
private void spellingPreferences_PreferencesModified(object sender, EventArgs e)
{
OnModified(EventArgs.Empty);
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
private const string SPELLING_IMAGE_PATH = "Images.";
//private Bitmap spellingDictionariesBitmap = ResourceHelper.LoadAssemblyResourceBitmap( SPELLING_IMAGE_PATH + "SpellingDictionaries.png") ;
private readonly Bitmap _spellingPanelBitmap = ResourceHelper.LoadAssemblyResourceBitmap(SPELLING_IMAGE_PATH + "SpellingPanelBitmapSmall.png");
#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._groupBoxGeneralOptions = new System.Windows.Forms.GroupBox();
this._comboBoxLanguage = new System.Windows.Forms.ComboBox();
this._labelDictionaryLanguage = new System.Windows.Forms.Label();
this._checkBoxRealTimeChecking = new System.Windows.Forms.CheckBox();
this._checkBoxIgnoreNumbers = new System.Windows.Forms.CheckBox();
this._checkBoxIgnoreUppercase = new System.Windows.Forms.CheckBox();
this._checkBoxCheckBeforePublish = new System.Windows.Forms.CheckBox();
this._checkBoxAutoCorrect = new System.Windows.Forms.CheckBox();
this._groupBoxGeneralOptions.SuspendLayout();
this.SuspendLayout();
//
// _groupBoxGeneralOptions
//
this._groupBoxGeneralOptions.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this._groupBoxGeneralOptions.Controls.Add(this._comboBoxLanguage);
this._groupBoxGeneralOptions.Controls.Add(this._labelDictionaryLanguage);
this._groupBoxGeneralOptions.Controls.Add(this._checkBoxRealTimeChecking);
this._groupBoxGeneralOptions.Controls.Add(this._checkBoxIgnoreNumbers);
this._groupBoxGeneralOptions.Controls.Add(this._checkBoxIgnoreUppercase);
this._groupBoxGeneralOptions.Controls.Add(this._checkBoxCheckBeforePublish);
this._groupBoxGeneralOptions.Controls.Add(this._checkBoxAutoCorrect);
this._groupBoxGeneralOptions.FlatStyle = System.Windows.Forms.FlatStyle.System;
this._groupBoxGeneralOptions.Location = new System.Drawing.Point(8, 32);
this._groupBoxGeneralOptions.Name = "_groupBoxGeneralOptions";
this._groupBoxGeneralOptions.Size = new System.Drawing.Size(345, 189);
this._groupBoxGeneralOptions.TabIndex = 1;
this._groupBoxGeneralOptions.TabStop = false;
this._groupBoxGeneralOptions.Text = "General options";
//
// _comboBoxLanguage
//
this._comboBoxLanguage.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this._comboBoxLanguage.Location = new System.Drawing.Point(48, 37);
this._comboBoxLanguage.Name = "_comboBoxLanguage";
this._comboBoxLanguage.Size = new System.Drawing.Size(195, 21);
this._comboBoxLanguage.TabIndex = 1;
//
// _labelDictionaryLanguage
//
this._labelDictionaryLanguage.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this._labelDictionaryLanguage.AutoSize = true;
this._labelDictionaryLanguage.FlatStyle = System.Windows.Forms.FlatStyle.System;
this._labelDictionaryLanguage.Location = new System.Drawing.Point(16, 18);
this._labelDictionaryLanguage.Name = "_labelDictionaryLanguage";
this._labelDictionaryLanguage.Size = new System.Drawing.Size(106, 13);
this._labelDictionaryLanguage.TabIndex = 0;
this._labelDictionaryLanguage.Text = "Dictionary &language:";
//
// _checkBoxRealTimeChecking
//
this._checkBoxRealTimeChecking.FlatStyle = System.Windows.Forms.FlatStyle.System;
this._checkBoxRealTimeChecking.Location = new System.Drawing.Point(16, 65);
this._checkBoxRealTimeChecking.Name = "_checkBoxRealTimeChecking";
this._checkBoxRealTimeChecking.Size = new System.Drawing.Size(323, 18);
this._checkBoxRealTimeChecking.TabIndex = 2;
this._checkBoxRealTimeChecking.Text = "Use &real time spell checking (squiggles)";
//
// _checkBoxIgnoreNumbers
//
this._checkBoxIgnoreNumbers.FlatStyle = System.Windows.Forms.FlatStyle.System;
this._checkBoxIgnoreNumbers.Location = new System.Drawing.Point(16, 111);
this._checkBoxIgnoreNumbers.Name = "_checkBoxIgnoreNumbers";
this._checkBoxIgnoreNumbers.Size = new System.Drawing.Size(323, 18);
this._checkBoxIgnoreNumbers.TabIndex = 4;
this._checkBoxIgnoreNumbers.Text = "Ignore words with &numbers";
//
// _checkBoxIgnoreUppercase
//
this._checkBoxIgnoreUppercase.FlatStyle = System.Windows.Forms.FlatStyle.System;
this._checkBoxIgnoreUppercase.Location = new System.Drawing.Point(16, 88);
this._checkBoxIgnoreUppercase.Name = "_checkBoxIgnoreUppercase";
this._checkBoxIgnoreUppercase.Size = new System.Drawing.Size(323, 18);
this._checkBoxIgnoreUppercase.TabIndex = 3;
this._checkBoxIgnoreUppercase.Text = "Ignore words in &UPPERCASE";
//
// _checkBoxCheckBeforePublish
//
this._checkBoxCheckBeforePublish.FlatStyle = System.Windows.Forms.FlatStyle.System;
this._checkBoxCheckBeforePublish.Location = new System.Drawing.Point(16, 134);
this._checkBoxCheckBeforePublish.Name = "_checkBoxCheckBeforePublish";
this._checkBoxCheckBeforePublish.Size = new System.Drawing.Size(323, 18);
this._checkBoxCheckBeforePublish.TabIndex = 5;
this._checkBoxCheckBeforePublish.Text = "Check spelling before &publishing";
//
// _checkBoxAutoCorrect
//
this._checkBoxAutoCorrect.FlatStyle = System.Windows.Forms.FlatStyle.System;
this._checkBoxAutoCorrect.Location = new System.Drawing.Point(16, 157);
this._checkBoxAutoCorrect.Name = "_checkBoxAutoCorrect";
this._checkBoxAutoCorrect.Size = new System.Drawing.Size(323, 18);
this._checkBoxAutoCorrect.TabIndex = 6;
this._checkBoxAutoCorrect.Text = "Automatically &correct common capitalization and spelling mistakes";
//
// SpellingPreferencesPanel
//
this.AccessibleName = "Spelling";
this.Controls.Add(this._groupBoxGeneralOptions);
this.Name = "SpellingPreferencesPanel";
this.PanelName = "Spelling";
this.Controls.SetChildIndex(this._groupBoxGeneralOptions, 0);
this._groupBoxGeneralOptions.ResumeLayout(false);
this._groupBoxGeneralOptions.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private void checkBoxIgnoreUppercase_CheckedChanged(object sender, EventArgs e)
{
spellingPreferences.IgnoreUppercase = _checkBoxIgnoreUppercase.Checked;
}
private void checkBoxIgnoreNumbers_CheckedChanged(object sender, EventArgs e)
{
spellingPreferences.IgnoreWordsWithNumbers = _checkBoxIgnoreNumbers.Checked;
}
private void checkBoxCheckBeforePublish_CheckedChanged(object sender, EventArgs e)
{
spellingPreferences.CheckSpellingBeforePublish = _checkBoxCheckBeforePublish.Checked;
}
private void checkBoxRealTimeChecking_CheckedChanged(object sender, EventArgs e)
{
spellingPreferences.RealTimeSpellChecking = _checkBoxRealTimeChecking.Checked;
}
private void checkBoxAutoCorrect_CheckedChanged(object sender, EventArgs e)
{
spellingPreferences.EnableAutoCorrect = _checkBoxAutoCorrect.Checked;
}
private void comboBoxLanguage_SelectedIndexChanged(object sender, EventArgs e)
{
spellingPreferences.Language = (_comboBoxLanguage.SelectedItem as SpellingLanguageEntry).Language;
ManageSpellingOptions();
}
}
}
| |
//=============================================================================
// System : Sandcastle Help File Builder Plug-Ins
// File : CompletionNotificationPlugIn.cs
// Author : Eric Woodruff ([email protected])
// Updated : 08/12/2008
// Note : Copyright 2007-2008, Eric Woodruff, All rights reserved
// Compiler: Microsoft Visual C#
//
// This file contains a plug-in designed to run after the build completes to
// send notification of the completion status via e-mail. The log file can
// be sent as an attachment.
//
// This code is published under the Microsoft Public License (Ms-PL). A copy
// of the license should be distributed with the code. It can also be found
// at the project website: http://SHFB.CodePlex.com. This notice, the
// author's name, and all copyright notices must remain intact in all
// applications, documentation, and source files.
//
// Version Date Who Comments
// ============================================================================
// 1.5.2.0 09/09/2007 EFW Created the code
// 1.6.0.6 03/09/2008 EFW Added support for log file XSL transform
//=============================================================================
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Web;
using System.Windows.Forms;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
using SandcastleBuilder.Utils;
using SandcastleBuilder.Utils.BuildEngine;
using SandcastleBuilder.Utils.PlugIn;
namespace SandcastleBuilder.PlugIns
{
/// <summary>
/// This plug-in class is designed to run after the build completes to
/// send notification of the completion status via e-mail. The log file
/// can be sent as an attachment.
/// </summary>
public class CompletionNotificationPlugIn : IPlugIn
{
#region Private data members
private ExecutionPointCollection executionPoints;
private BuildProcess builder;
private bool attachLogOnSuccess, attachLogOnFailure;
private string smtpServer, fromEMailAddress, successEMailAddress,
failureEMailAddress, xslTransformFile;
private UserCredentials credentials;
private int smtpPort;
#endregion
#region IPlugIn implementation
//=====================================================================
// IPlugIn implementation
/// <summary>
/// This read-only property returns a friendly name for the plug-in
/// </summary>
public string Name
{
get { return "Completion Notification"; }
}
/// <summary>
/// This read-only property returns the version of the plug-in
/// </summary>
public Version Version
{
get
{
// Use the assembly version
Assembly asm = Assembly.GetExecutingAssembly();
FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(
asm.Location);
return new Version(fvi.ProductVersion);
}
}
/// <summary>
/// This read-only property returns the copyright information for the
/// plug-in.
/// </summary>
public string Copyright
{
get
{
// Use the assembly copyright
Assembly asm = Assembly.GetExecutingAssembly();
AssemblyCopyrightAttribute copyright =
(AssemblyCopyrightAttribute)Attribute.GetCustomAttribute(
asm, typeof(AssemblyCopyrightAttribute));
return copyright.Copyright;
}
}
/// <summary>
/// This read-only property returns a brief description of the plug-in
/// </summary>
public string Description
{
get
{
return "This plug-in is used to send notification of the " +
"build completion status via e-mail. The log file can " +
"be sent as an attachment.";
}
}
/// <summary>
/// This plug-in does not run in partial builds
/// </summary>
public bool RunsInPartialBuild
{
get { return false; }
}
/// <summary>
/// This read-only property returns a collection of execution points
/// that define when the plug-in should be invoked during the build
/// process.
/// </summary>
public ExecutionPointCollection ExecutionPoints
{
get
{
if(executionPoints == null)
{
executionPoints = new ExecutionPointCollection();
executionPoints.Add(new ExecutionPoint(
BuildStep.Completed, ExecutionBehaviors.After));
executionPoints.Add(new ExecutionPoint(
BuildStep.Canceled, ExecutionBehaviors.After));
executionPoints.Add(new ExecutionPoint(
BuildStep.Failed, ExecutionBehaviors.After));
}
return executionPoints;
}
}
/// <summary>
/// This method is used by the Sandcastle Help File Builder to let the
/// plug-in perform its own configuration.
/// </summary>
/// <param name="project">A reference to the active project</param>
/// <param name="currentConfig">The current configuration XML fragment</param>
/// <returns>A string containing the new configuration XML fragment</returns>
/// <remarks>The configuration data will be stored in the help file
/// builder project.</remarks>
public string ConfigurePlugIn(SandcastleProject project,
string currentConfig)
{
using(CompletionNotificationConfigDlg dlg =
new CompletionNotificationConfigDlg(currentConfig))
{
if(dlg.ShowDialog() == DialogResult.OK)
currentConfig = dlg.Configuration;
}
return currentConfig;
}
/// <summary>
/// This method is used to initialize the plug-in at the start of the
/// build process.
/// </summary>
/// <param name="buildProcess">A reference to the current build
/// process.</param>
/// <param name="configuration">The configuration data that the plug-in
/// should use to initialize itself.</param>
/// <exception cref="BuilderException">This is thrown if the plug-in
/// configuration is not valid.</exception>
public void Initialize(BuildProcess buildProcess,
XPathNavigator configuration)
{
XPathNavigator root, node;
string value;
builder = buildProcess;
attachLogOnSuccess = false;
attachLogOnFailure = true;
smtpServer = successEMailAddress = failureEMailAddress =
xslTransformFile = String.Empty;
credentials = new UserCredentials();
smtpPort = 25;
builder.ReportProgress("{0} Version {1}\r\n{2}",
this.Name, this.Version, this.Copyright);
root = configuration.SelectSingleNode("configuration");
if(root.IsEmptyElement)
throw new BuilderException("CNP0001", "The Completion " +
"Notification plug-in has not been configured yet");
node = root.SelectSingleNode("smtpServer");
if(node != null)
{
smtpServer = node.GetAttribute("host", String.Empty).Trim();
value = node.GetAttribute("port", String.Empty);
if(!Int32.TryParse(value, out smtpPort))
smtpPort = 25;
}
credentials = UserCredentials.FromXPathNavigator(root);
node = root.SelectSingleNode("fromEMail");
if(node != null)
fromEMailAddress = node.GetAttribute("address",
String.Empty).Trim();
node = root.SelectSingleNode("successEMail");
if(node != null)
{
successEMailAddress = node.GetAttribute("address",
String.Empty).Trim();
attachLogOnSuccess = Convert.ToBoolean(node.GetAttribute(
"attachLog", String.Empty), CultureInfo.InvariantCulture);
}
node = root.SelectSingleNode("failureEMail");
if(node != null)
{
failureEMailAddress = node.GetAttribute("address",
String.Empty).Trim();
attachLogOnFailure = Convert.ToBoolean(node.GetAttribute(
"attachLog", String.Empty), CultureInfo.InvariantCulture);
}
node = root.SelectSingleNode("xslTransform");
if(node != null)
xslTransformFile = builder.TransformText(
node.GetAttribute("filename", String.Empty).Trim());
if((!credentials.UseDefaultCredentials &&
(credentials.UserName.Length == 0 ||
credentials.Password.Length == 0)) ||
failureEMailAddress.Length == 0)
throw new BuilderException("CNP0002", "The Completion " +
"Notification plug-in has an invalid configuration");
}
/// <summary>
/// This method is used to execute the plug-in during the build process
/// </summary>
/// <param name="context">The current execution context</param>
/// <remarks>Since this runs after completion of the build and the
/// log file is closed, any progress messages reported here will not
/// appear in it, just in the output window on the main form.</remarks>
public void Execute(ExecutionContext context)
{
MailMessage msg = null;
string logFilename = null;
// There is nothing to do on completion if there is no success
// e-mail address.
if(context.BuildStep == BuildStep.Completed &&
successEMailAddress.Length == 0)
{
context.Executed = false;
return;
}
try
{
logFilename = builder.LogFilename;
// Run the log file through an XSL transform first?
if(!String.IsNullOrEmpty(xslTransformFile) &&
File.Exists(logFilename))
logFilename = this.TransformLogFile();
msg = new MailMessage();
msg.IsBodyHtml = false;
msg.Subject = String.Format(CultureInfo.InvariantCulture,
"Build {0}: {1}", context.BuildStep,
builder.ProjectFilename);
if(fromEMailAddress.Length != 0)
msg.From = new MailAddress(fromEMailAddress);
else
msg.From = new MailAddress("[email protected]");
if(context.BuildStep == BuildStep.Completed)
{
msg.To.Add(successEMailAddress);
if(attachLogOnSuccess && File.Exists(logFilename))
msg.Attachments.Add(new Attachment(logFilename));
}
else
{
msg.To.Add(failureEMailAddress);
if(attachLogOnFailure && File.Exists(logFilename))
msg.Attachments.Add(new Attachment(logFilename));
}
msg.Body = String.Format(CultureInfo.InvariantCulture,
"Build {0}: {1}{2}\r\nBuild output is located at {3}\r\n",
context.BuildStep, builder.ProjectFolder,
builder.ProjectFilename, builder.OutputFolder);
if(context.BuildStep != BuildStep.Completed ||
builder.CurrentProject.KeepLogFile)
msg.Body += "Build details can be found in the log file " +
builder.LogFilename + "\r\n";
SmtpClient smtp = new SmtpClient();
if(smtpServer.Length != 0)
{
smtp.Host = smtpServer;
smtp.Port = smtpPort;
}
if(!credentials.UseDefaultCredentials)
smtp.Credentials = new NetworkCredential(
credentials.UserName, credentials.Password);
smtp.Send(msg);
builder.ReportProgress("The build notification e-mail was " +
"sent successfully to {0}", msg.To[0].Address);
}
catch(FormatException)
{
builder.ReportProgress("Failed to send build notification " +
"e-mail! The e-mail addresses '{0}' appears to be " +
"invalid.", msg.To[0]);
}
catch(SmtpFailedRecipientException recipEx)
{
builder.ReportProgress("Failed to send build notification " +
"e-mail! A problem occurred trying to send the e-mail " +
"to the recipient '{0}': {1}", recipEx.FailedRecipient,
recipEx.Message);
}
catch(SmtpException smtpEx)
{
System.Diagnostics.Debug.WriteLine(smtpEx.ToString());
builder.ReportProgress("Failed to send build notification " +
"e-mail! A problem occurred trying to connect to the " +
"e-mail server. Details:\r\n{0}\r\n", smtpEx.ToString());
}
finally
{
if(msg != null)
msg.Dispose();
// Delete the transformed log file if it exists
if(!String.IsNullOrEmpty(logFilename) &&
logFilename.EndsWith(".html", StringComparison.OrdinalIgnoreCase))
File.Delete(logFilename);
}
}
#endregion
#region IDisposable implementation
//=====================================================================
// IDisposable implementation
/// <summary>
/// This handles garbage collection to ensure proper disposal of the
/// plug-in if not done explicity with <see cref="Dispose()"/>.
/// </summary>
~CompletionNotificationPlugIn()
{
this.Dispose(false);
}
/// <summary>
/// This implements the Dispose() interface to properly dispose of
/// the plug-in object.
/// </summary>
/// <overloads>There are two overloads for this method.</overloads>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// This can be overridden by derived classes to add their own
/// disposal code if necessary.
/// </summary>
/// <param name="disposing">Pass true to dispose of the managed
/// and unmanaged resources or false to just dispose of the
/// unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
// Nothing to dispose of in this one
}
#endregion
#region Helper method
//=====================================================================
/// <summary>
/// This is used to run the log file through an XSL transform so that
/// it is more readable.
/// </summary>
/// <returns>The transformed log filename</returns>
private string TransformLogFile()
{
XslCompiledTransform xslTransform;
XsltSettings settings;
XmlReaderSettings readerSettings;
XmlWriterSettings writerSettings;
XmlReader reader = null;
XmlWriter writer = null;
StringReader sr = null;
StringBuilder sb = null;
string html = null, logFile = Path.ChangeExtension(
builder.LogFilename, ".html");
try
{
// Read in the log text we'll prefix it it with the error
// message if the transform fails.
using(StreamReader srdr = new StreamReader(builder.LogFilename))
{
html = srdr.ReadToEnd();
}
// Transform the log into something more readable
readerSettings = new XmlReaderSettings();
readerSettings.ProhibitDtd = false;
readerSettings.CloseInput = true;
xslTransform = new XslCompiledTransform();
settings = new XsltSettings(true, true);
xslTransform.Load(XmlReader.Create(xslTransformFile,
readerSettings), settings, new XmlUrlResolver());
sr = new StringReader(html);
reader = XmlReader.Create(sr, readerSettings);
writerSettings = xslTransform.OutputSettings.Clone();
writerSettings.CloseOutput = true;
writerSettings.Indent = false;
sb = new StringBuilder(10240);
writer = XmlWriter.Create(sb, writerSettings);
xslTransform.Transform(reader, writer);
writer.Flush();
html = sb.ToString();
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
// Just use the raw data prefixed with the error message
html = String.Format(CultureInfo.CurrentCulture,
"<pre><b>An error occurred trying to transform the log " +
"file '{0}'</b>:\r\n{1}\r\n\r\n<b>Log Content:</b>\r\n" +
"{2}</pre>", builder.LogFilename, ex.Message,
HttpUtility.HtmlEncode(html));
}
finally
{
if(reader != null)
reader.Close();
if(writer != null)
writer.Close();
if(sr != null)
sr.Close();
}
using(StreamWriter sw = new StreamWriter(logFile, false,
Encoding.UTF8))
{
sw.Write(html);
}
return logFile;
}
#endregion
}
}
| |
/*
| Version 10.1.84
| Copyright 2013 Esri
|
| Licensed under the Apache License, Version 2.0 (the "License");
| you may not use this file except in compliance with the License.
| You may obtain a copy of the License at
|
| http://www.apache.org/licenses/LICENSE-2.0
|
| Unless required by applicable law or agreed to in writing, software
| distributed under the License is distributed on an "AS IS" BASIS,
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
| See the License for the specific language governing permissions and
| limitations under the License.
*/
using System;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using ESRI.ArcLogistics.DomainObjects.Attributes;
using ESRI.ArcLogistics.DomainObjects.Validation;
namespace ESRI.ArcLogistics.DomainObjects
{
/// <summary>
/// TimeIntervalBreak class represents a base abstract class for other breaks
/// with specific interval.
/// </summary>
public abstract class TimeIntervalBreak : Break
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <c>TimeIntervalBreak</c> class.
/// </summary>
protected TimeIntervalBreak()
{ }
#endregion // Constructors
#region Public static properties
/// <summary>
/// Gets name of the TimeInterval property.
/// </summary>
public static string PropertyNameTimeInterval
{
get { return PROP_NAME_TIMEINTERVAL; }
}
#endregion // Public static properties
#region Public members
/// <summary>
/// Time interval in hours.
/// </summary>
/// <remarks>It is a time interval (in hours) from previous break (or route start if a
/// break is the first) that must be spent before this break takes place on a route.</remarks>
[TimeIntervalValidator]
[DomainProperty("DomainPropertyNameInterval")]
[UnitPropertyAttribute(Unit.Hour, Unit.Hour, Unit.Hour)]
public double TimeInterval
{
get { return _timeInterval; }
set
{
if (_timeInterval == value)
return;
_timeInterval = value;
_NotifyPropertyChanged(PROP_NAME_TIMEINTERVAL);
}
}
/// <summary>
/// Returns a string representation of the break information.
/// </summary>
/// <returns>Break's string.</returns>
public override string ToString()
{
return string.Format(Properties.Resources.BreakIntervalFormat,
base.ToString(),
TimeInterval.ToString());
}
#endregion // Public members
#region Internal Properties
internal double DefaultTimeInterval
{
get
{
return DEFAULT_TIME_INTERVAL;
}
}
#endregion
#region Internal overrided methods
/// <summary>
/// Check that both breaks have same types and same Duration and TimeInterval values.
/// </summary>
/// <param name="breakObject">Brake to compare with this.</param>
/// <returns>'True' if breaks types and Duration and TimeInterval
/// values are the same, 'false' otherwise.</returns>
internal override bool EqualsByValue(Break breakObject)
{
TimeIntervalBreak breakToCompare = breakObject as TimeIntervalBreak;
return breakToCompare != null && base.EqualsByValue(breakObject) &&
breakToCompare.TimeInterval == this.TimeInterval;
}
/// <summary>
/// Converts state of this instance to its equivalent string representation.
/// </summary>
/// <returns>The string representation of the value of this instance.</returns>
internal override string ConvertToString()
{
var result = new StringBuilder();
CultureInfo cultureInfo = CultureInfo.GetCultureInfo(CommonHelpers.STORAGE_CULTURE);
// 0. Current version
result.Append(VERSION_CURR.ToString());
// 1. Duration
result.Append(CommonHelpers.SEPARATOR);
result.Append(Duration.ToString(cultureInfo));
// 2. Interval
result.Append(CommonHelpers.SEPARATOR);
result.Append(TimeInterval.ToString(cultureInfo));
return result.ToString();
}
/// <summary>
/// Method occured, when breaks collection changed. Need for validation.
/// </summary>
/// <param name="sender">Ignored.</param>
/// <param name="e">Ignored.</param>
protected override void BreaksCollectionChanged(object sender,
System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
// If breaks collection changed - raise notify property
// changed for "TimeInterval" property for all breaks in this collection.
_NotifyPropertyChanged(PropertyNameTimeInterval);
}
#endregion // Internal overrided methods
#region Protected methods
/// <summary>
/// Converts the string representation of a break to break's values.
/// </summary>
/// <param name="context">String representation of a break.</param>
/// <param name="intervalBreak">Parsed break's.</param>
protected static void _Parse(string context, TimeIntervalBreak intervalBreak)
{
Debug.Assert(!string.IsNullOrEmpty(context));
char[] valuesSeparator = new char[1] { CommonHelpers.SEPARATOR };
string[] values = context.Split(valuesSeparator, StringSplitOptions.None);
Debug.Assert(3 == values.Length);
CultureInfo cultureInfo = CultureInfo.GetCultureInfo(CommonHelpers.STORAGE_CULTURE);
int index = 0;
// 0. Current version, now not used
// 1. Duration
intervalBreak.Duration = double.Parse(values[++index], cultureInfo);
// 2. Interval
intervalBreak.TimeInterval = double.Parse(values[++index], cultureInfo);
}
/// <summary>
/// Copies all the breaks's data to the target interval break.
/// </summary>
/// <param name="intervalBreak">Target interval break.</param>
protected void _CopyTo(TimeIntervalBreak intervalBreak)
{
intervalBreak.Duration = this.Duration;
intervalBreak.TimeInterval = this.TimeInterval;
}
#endregion // Protected methods
#region Private constants
/// <summary>
/// Name of the TimeInterval property.
/// </summary>
private const string PROP_NAME_TIMEINTERVAL = "TimeInterval";
/// <summary>
/// Storage schema version 1.
/// </summary>
private const int VERSION_1 = 0x00000001;
/// <summary>
/// Storage schema current version.
/// </summary>
private const int VERSION_CURR = VERSION_1;
/// <summary>
/// Default break's time interval.
/// </summary>
private const double DEFAULT_TIME_INTERVAL = 4;
#endregion // Private constants
#region Private members
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Time interval.
/// </summary>
private double _timeInterval;
#endregion // Private members
}
/// <summary>
/// Class that represents a drive time break.
/// Specify how long a person can drive before the break is required.
/// (Note that only travel time is limited, not other times like wait and service times).
/// </summary>
public class DriveTimeBreak : TimeIntervalBreak
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <c>DriveTimeBreak</c> class.
/// </summary>
public DriveTimeBreak()
{
Duration = DefautDuration;
TimeInterval = DefaultTimeInterval;
}
#endregion
#region ICloneable members
/// <summary>
/// Clones the <c>TimeWindowBreak</c> object.
/// </summary>
/// <returns>Cloned object.</returns>
public override object Clone()
{
var obj = new DriveTimeBreak();
_CopyTo(obj);
return obj;
}
#endregion // ICloneable members
#region Internal overrided methods
/// <summary>
/// Converts the string representation of a break to break internal state equivalent.
/// </summary>
/// <param name="context">String representation of a break.</param>
internal override void InitFromString(string context)
{
if (null != context)
_Parse(context, this);
}
#endregion // Internal overrided methods
}
/// <summary>
/// Class that represents a work time break.
/// Specifies how long a person can work before a break is required.
/// This breaks always accumulate work time from the beginning of the route, including any
/// service time at the start depot (which includes travel time and all service times;
/// it excludes wait time, however).
/// </summary>
public class WorkTimeBreak : TimeIntervalBreak
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <c>WorkTimeBreak</c> class.
/// </summary>
public WorkTimeBreak()
{
Duration = DefautDuration;
TimeInterval = DefaultTimeInterval;
}
#endregion
#region ICloneable members
/// <summary>
/// Clones the <c>TimeWindowBreak</c> object.
/// </summary>
/// <returns>Cloned object.</returns>
public override object Clone()
{
var obj = new WorkTimeBreak();
_CopyTo(obj);
return obj;
}
#endregion
#region Internal overrided methods
/// <summary>
/// Converts the string representation of a break to break internal state equivalent.
/// </summary>
/// <param name="context">String representation of a break.</param>
internal override void InitFromString(string context)
{
if (null != context)
_Parse(context, this);
}
#endregion
}
}
| |
namespace MichaelJBaird.Themes.JQMobile.Controls
{
#region using
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using BlogEngine.Core;
using BlogEngine.Core.Web.Controls;
using BlogEngine.Core.Web.Extensions;
#endregion
/// <summary>
/// The comment view.
/// </summary>
public partial class CommentView : UserControl, ICallbackEventHandler
{
#region Constants and Fields
/// <summary>
/// The callback.
/// </summary>
private string callback;
/// <summary>
/// The nesting supported.
/// </summary>
private bool? nestingSupported;
/// <summary>
/// Initializes a new instance of the <see cref = "CommentView" /> class.
/// </summary>
public CommentView()
{
this.NameInputId = string.Empty;
this.DefaultName = string.Empty;
}
#endregion
#region Properties
/// <summary>
/// Gets a value indicating whether NestingSupported.
/// </summary>
public bool NestingSupported
{
get
{
if (!this.nestingSupported.HasValue)
{
if (!BlogSettings.Instance.IsCommentNestingEnabled)
{
this.nestingSupported = false;
}
else
{
var path = string.Format(
"{0}themes/{1}/CommentView.ascx", Utils.ApplicationRelativeWebRoot, BlogSettings.Instance.GetThemeWithAdjustments(null));
// test comment control for nesting placeholder (for backwards compatibility with older themes)
var commentTester = (CommentViewBase)this.LoadControl(path);
var subComments = commentTester.FindControl("phSubComments") as PlaceHolder;
this.nestingSupported = subComments != null;
}
}
return this.nestingSupported.Value;
}
}
/// <summary>
/// Gets or sets the post from which the comments are parsed.
/// </summary>
public Post Post { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [any captcha enabled].
/// </summary>
/// <value><c>true</c> if [any captcha enabled]; otherwise, <c>false</c>.</value>
protected bool AnyCaptchaEnabled { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [any captcha necessary].
/// </summary>
/// <value><c>true</c> if [any captcha necessary]; otherwise, <c>false</c>.</value>
protected bool AnyCaptchaNecessary { get; set; }
/// <summary>
/// Gets or sets the comment counter.
/// </summary>
/// <value>The comment counter.</value>
protected int CommentCounter { get; set; }
/// <summary>
/// Gets or sets the default name.
/// </summary>
/// <value>The default name.</value>
protected string DefaultName { get; set; }
/// <summary>
/// Gets or sets the name input id.
/// </summary>
/// <value>The name input id.</value>
protected string NameInputId { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [re captcha enabled].
/// </summary>
/// <value><c>true</c> if [re captcha enabled]; otherwise, <c>false</c>.</value>
protected bool ReCaptchaEnabled { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [simple captcha enabled].
/// </summary>
/// <value>
/// <c>true</c> if [simple captcha enabled]; otherwise, <c>false</c>.
/// </value>
protected bool SimpleCaptchaEnabled { get; set; }
#endregion
#region Public Methods
/// <summary>
/// Resolves the region based on the browser language.
/// </summary>
/// <returns>
/// The region info.
/// </returns>
public static RegionInfo ResolveRegion()
{
var languages = HttpContext.Current.Request.UserLanguages;
if (languages == null || languages.Length == 0)
{
return new RegionInfo(CultureInfo.CurrentCulture.LCID);
}
try
{
var language = languages[0].ToLowerInvariant().Trim();
var culture = CultureInfo.CreateSpecificCulture(language);
return new RegionInfo(culture.LCID);
}
catch (ArgumentException)
{
try
{
return new RegionInfo(CultureInfo.CurrentCulture.LCID);
}
catch (ArgumentException)
{
// the googlebot sometimes gives a culture LCID of 127 which is invalid
// so assume US english if invalid LCID
return new RegionInfo(1033);
}
}
}
/// <summary>
/// Binds the country dropdown list with countries retrieved
/// from the .NET Framework.
/// </summary>
public void BindCountries()
{
var dic = new StringDictionary();
var col = new List<string>();
foreach (
var ri in CultureInfo.GetCultures(CultureTypes.SpecificCultures).Select(ci => new RegionInfo(ci.Name)))
{
if (!dic.ContainsKey(ri.EnglishName))
{
dic.Add(ri.EnglishName, ri.TwoLetterISORegionName.ToLowerInvariant());
}
if (!col.Contains(ri.EnglishName))
{
col.Add(ri.EnglishName);
}
}
// Add custom cultures
if (!dic.ContainsValue("bd"))
{
dic.Add("Bangladesh", "bd");
col.Add("Bangladesh");
}
if (!dic.ContainsValue("bm"))
{
dic.Add("Bermuda", "bm");
col.Add("Bermuda");
}
col.Sort();
this.ddlCountry.Items.Add(new ListItem("[Not specified]", string.Empty));
foreach (var key in col)
{
this.ddlCountry.Items.Add(new ListItem(key, dic[key]));
}
if (this.ddlCountry.SelectedIndex == 0)
{
this.ddlCountry.SelectedValue = ResolveRegion().TwoLetterISORegionName.ToLowerInvariant();
this.SetFlagImageUrl();
}
}
#endregion
#region Implemented Interfaces
#region ICallbackEventHandler
/// <summary>
/// Returns the results of a callback event that targets a control.
/// </summary>
/// <returns>
/// The result of the callback.
/// </returns>
public string GetCallbackResult()
{
return this.callback;
}
/// <summary>
/// Processes a callback event that targets a control.
/// </summary>
/// <param name="eventArgument">
/// A string that represents an event argument to pass to the event handler.
/// </param>
public void RaiseCallbackEvent(string eventArgument)
{
if (!BlogSettings.Instance.IsCommentsEnabled || !Security.IsAuthorizedTo(Rights.CreateComments))
{
return;
}
var args = eventArgument.Split(new[] { "-|-" }, StringSplitOptions.None);
var author = args[0];
var email = args[1];
var website = args[2];
var country = args[3];
var content = args[4];
var notify = bool.Parse(args[5]);
var preview = bool.Parse(args[6]);
var sentCaptcha = args[7];
// If there is no "reply to" comment, args[8] is empty
var replyToCommentId = String.IsNullOrEmpty(args[8]) ? Guid.Empty : new Guid(args[8]);
var avatar = args[9];
var recaptchaResponse = args[10];
var recaptchaChallenge = args[11];
var simpleCaptchaChallenge = args[12];
this.recaptcha.UserUniqueIdentifier = this.hfCaptcha.Value;
if (!preview && this.AnyCaptchaEnabled && this.AnyCaptchaNecessary)
{
if (this.ReCaptchaEnabled)
{
if (!this.recaptcha.ValidateAsync(recaptchaResponse, recaptchaChallenge))
{
this.callback = "RecaptchaIncorrect";
return;
}
}
else
{
this.simplecaptcha.Validate(simpleCaptchaChallenge);
if (!this.simplecaptcha.IsValid)
{
this.callback = "SimpleCaptchaIncorrect";
return;
}
}
}
var storedCaptcha = this.hfCaptcha.Value;
if (sentCaptcha != storedCaptcha)
{
return;
}
var comment = new Comment
{
Id = Guid.NewGuid(),
ParentId = replyToCommentId,
Author = this.Server.HtmlEncode(author),
Email = email,
Content = this.Server.HtmlEncode(content),
IP = this.Request.UserHostAddress,
Country = country,
DateCreated = DateTime.Now,
Parent = this.Post,
IsApproved = !BlogSettings.Instance.EnableCommentsModeration,
Avatar = avatar.Trim()
};
if (Security.IsAuthenticated && BlogSettings.Instance.TrustAuthenticatedUsers)
{
comment.IsApproved = true;
}
if (BlogSettings.Instance.EnableWebsiteInComments)
{
if (website.Trim().Length > 0)
{
if (!website.ToLowerInvariant().Contains("://"))
{
website = string.Format("http://{0}", website);
}
Uri url;
if (Uri.TryCreate(website, UriKind.Absolute, out url))
{
comment.Website = url;
}
}
}
if (!preview)
{
if (notify && !this.Post.NotificationEmails.Contains(email))
{
this.Post.NotificationEmails.Add(email);
}
else if (!notify && this.Post.NotificationEmails.Contains(email))
{
this.Post.NotificationEmails.Remove(email);
}
this.Post.AddComment(comment);
this.SetCookie(author, email, website, country);
if (this.ReCaptchaEnabled)
{
this.recaptcha.UpdateLog(comment);
}
}
var path = string.Format(
"{0}themes/{1}/CommentView.ascx", Utils.ApplicationRelativeWebRoot, BlogSettings.Instance.GetThemeWithAdjustments(null));
var control = (CommentViewBase)this.LoadControl(path);
control.Comment = comment;
control.Post = this.Post;
control.RenderComment();
using (var sw = new StringWriter())
{
control.RenderControl(new HtmlTextWriter(sw));
this.callback = sw.ToString();
}
}
#endregion
#endregion
#region Methods
/// <summary>
/// Displays a delete link to visitors that is authenticated
/// using the default membership provider.
/// </summary>
/// <param name="id">
/// The id of the comment.
/// </param>
/// <returns>
/// The admin link.
/// </returns>
protected string AdminLink(string id)
{
if (Security.IsAuthenticated)
{
var sb = new StringBuilder();
foreach (var comment in this.Post.Comments.Where(comment => comment.Id.ToString() == id))
{
sb.AppendFormat(" | <a href=\"mailto:{0}\">{0}</a>", comment.Email);
}
if (Security.IsAuthorizedTo(Rights.ModerateComments))
{
const string ConfirmDelete = "Are you sure you want to delete the comment?";
sb.AppendFormat(
" | <a href=\"?deletecomment={0}\" onclick=\"return confirm('{1}?')\">{2}</a>",
id,
ConfirmDelete,
"Delete");
}
return sb.ToString();
}
return string.Empty;
}
/// <summary>
/// Displays BBCodes dynamically loaded from settings.
/// </summary>
/// <returns>
/// The bb codes.
/// </returns>
protected string BBCodes()
{
try
{
var sb = new StringBuilder();
var settings = ExtensionManager.GetSettings("BBCode");
if (settings != null)
{
var table = settings.GetDataTable();
foreach (DataRow row in table.Rows)
{
var code = (string)row["Code"];
var title = string.Format("[{0}][/{1}]", code, code);
sb.AppendFormat(
"<a title=\"{0}\" href=\"javascript:void(BlogEngine.addBbCode('{1}'))\">{2}</a>",
title,
code,
code);
}
}
return sb.ToString();
}
catch (Exception)
{
return string.Empty;
}
}
/// <summary>
/// Raises the <see cref="E:System.Web.UI.Control.Load"/> event.
/// </summary>
/// <param name="e">
/// The <see cref="T:System.EventArgs"/> object that contains the event data.
/// </param>
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
bool isOdd = true;
if (this.Post == null)
{
this.Response.Redirect(Utils.RelativeWebRoot);
return;
}
this.NameInputId = string.Format("txtName{0}", DateTime.Now.Ticks);
this.EnableCaptchas();
if (this.Page.IsPostBack)
{
}
if (!this.Page.IsPostBack && !this.Page.IsCallback)
{
if (Security.IsAuthorizedTo(Rights.ModerateComments))
{
if (this.Request.QueryString["deletecomment"] != null)
{
this.DeleteComment();
}
else if (this.Request.QueryString["deletecommentandchildren"] != null)
{
this.DeleteCommentAndChildren();
}
else if (!string.IsNullOrEmpty(this.Request.QueryString["approvecomment"]))
{
this.ApproveComment();
}
else if (!string.IsNullOrEmpty(this.Request.QueryString["approveallcomments"]))
{
this.ApproveAllComments();
}
}
var path = string.Format(
"{0}themes/{1}/CommentView.ascx", Utils.ApplicationRelativeWebRoot, BlogSettings.Instance.GetThemeWithAdjustments(null));
bool canViewUnpublishedPosts = Security.IsAuthorizedTo(AuthorizationCheck.HasAny, new[] { Rights.ViewUnmoderatedComments, Rights.ModerateComments });
if (this.NestingSupported)
{
// newer, nested comments
if (this.Post != null)
{
this.AddNestedComments(path, this.Post.NestedComments, this.phComments, canViewUnpublishedPosts);
}
}
else
{
// old, non nested code
// Add approved Comments
isOdd = true;
foreach (var comment in
this.Post.Comments.Where(
comment => comment.Email != "pingback" && comment.Email != "trackback"))
{
if (comment.IsApproved)
{
this.CommentCounter++;
}
if (!comment.IsApproved && BlogSettings.Instance.EnableCommentsModeration)
{
continue;
}
isOdd = !isOdd;
var control = (CommentViewBase)this.LoadControl(path);
control.Comment = comment;
control.Post = this.Post;
control.IsOdd = isOdd;
this.phComments.Controls.Add(control);
}
// Add unapproved comments
if (canViewUnpublishedPosts)
{
foreach (var comment in this.Post.Comments)
{
if (comment.Email == "pingback" || comment.Email == "trackback")
{
continue;
}
if (comment.IsApproved)
{
continue;
}
isOdd = !isOdd;
var control = (CommentViewBase)this.LoadControl(path);
control.Comment = comment;
control.Post = this.Post;
control.IsOdd = isOdd;
this.phComments.Controls.Add(control);
}
}
}
var pingbacks = new List<CommentViewBase>();
isOdd = true;
foreach (var comment in this.Post.Comments)
{
var control = (CommentViewBase)this.LoadControl(path);
if (comment.Email != "pingback" && comment.Email != "trackback")
{
continue;
}
isOdd = !isOdd;
control.Comment = comment;
control.Post = this.Post;
control.IsOdd = isOdd;
pingbacks.Add(control);
}
if (pingbacks.Count > 0)
{
var litTrackback = new Literal();
var sb = new StringBuilder();
sb.AppendFormat("<h3 id=\"trackbackheader\">Pingbacks and trackbacks ({0})", pingbacks.Count);
sb.Append(
"<a id=\"trackbacktoggle\" style=\"float:right;width:20px;height:20px;border:1px solid #ccc;text-decoration:none;text-align:center\"");
sb.Append(" href=\"javascript:toggle_visibility('trackbacks','trackbacktoggle');\">+</a>");
sb.Append("</h3><div id=\"trackbacks\" style=\"display:none\">");
litTrackback.Text = sb.ToString();
this.phTrckbacks.Controls.Add(litTrackback);
foreach (var c in pingbacks)
{
this.phTrckbacks.Controls.Add(c);
}
var closingDiv = new Literal { Text = @"</div>" };
this.phTrckbacks.Controls.Add(closingDiv);
}
else
{
this.phTrckbacks.Visible = false;
}
if (BlogSettings.Instance.IsCommentsEnabled && Security.IsAuthorizedTo(Rights.CreateComments))
{
if (this.Post != null &&
(!this.Post.HasCommentsEnabled ||
(BlogSettings.Instance.DaysCommentsAreEnabled > 0 &&
this.Post.DateCreated.AddDays(BlogSettings.Instance.DaysCommentsAreEnabled) <
DateTime.Now.Date)))
{
this.phAddComment.Visible = false;
this.lbCommentsDisabled.Visible = true;
}
this.BindCountries();
this.GetCookie();
this.recaptcha.UserUniqueIdentifier = this.hfCaptcha.Value = Guid.NewGuid().ToString();
}
else
{
this.phAddComment.Visible = false;
}
}
this.Page.ClientScript.GetCallbackEventReference(this, "arg", null, string.Empty);
}
/// <summary>
/// Adds the nested comments.
/// </summary>
/// <param name="path">
/// The path string.
/// </param>
/// <param name="nestedComments">
/// The nested comments.
/// </param>
/// <param name="commentsPlaceHolder">
/// The comments place holder.
/// </param>
private void AddNestedComments(string path, IEnumerable<Comment> nestedComments, Control commentsPlaceHolder, bool canViewUnpublishedPosts)
{
bool enableCommentModeration = BlogSettings.Instance.EnableCommentsModeration;
bool isOdd = true;
foreach (var comment in nestedComments)
{
if ((!comment.IsApproved && enableCommentModeration) &&
(comment.IsApproved || !canViewUnpublishedPosts))
{
continue;
}
// if comment is spam, only authorized can see it
if (comment.IsSpam && !canViewUnpublishedPosts)
{
continue;
}
if (comment.Email == "pingback" || comment.Email == "trackback")
{
continue;
}
isOdd = !isOdd;
var control = (CommentViewBase)this.LoadControl(path);
control.Comment = comment;
control.Post = this.Post;
control.IsOdd = isOdd;
if (comment.IsApproved)
{
this.CommentCounter++;
}
if (comment.Comments.Count > 0)
{
// find the next placeholder and add the subcomments to it
var subCommentsPlaceHolder = control.FindControl("phSubComments") as PlaceHolder;
if (subCommentsPlaceHolder != null)
{
this.AddNestedComments(path, comment.Comments, subCommentsPlaceHolder, canViewUnpublishedPosts);
}
}
commentsPlaceHolder.Controls.Add(control);
}
}
/// <summary>
/// Approves all comments.
/// </summary>
private void ApproveAllComments()
{
Security.DemandUserHasRight(Rights.ModerateComments, true);
this.Post.ApproveAllComments();
var index = this.Request.RawUrl.IndexOf("?");
var url = this.Request.RawUrl.Substring(0, index);
this.Response.Redirect(url, true);
}
/// <summary>
/// Approves the comment.
/// </summary>
private void ApproveComment()
{
Security.DemandUserHasRight(Rights.ModerateComments, true);
foreach (var comment in
this.Post.NotApprovedComments.Where(
comment => comment.Id == new Guid(this.Request.QueryString["approvecomment"])))
{
this.Post.ApproveComment(comment);
var index = this.Request.RawUrl.IndexOf("?");
var url = this.Request.RawUrl.Substring(0, index);
this.Response.Redirect(url, true);
}
}
/// <summary>
/// Collects the comment to delete.
/// </summary>
/// <param name="comment">
/// The comment.
/// </param>
/// <param name="commentsToDelete">
/// The comments to delete.
/// </param>
private void CollectCommentToDelete(Comment comment, List<Comment> commentsToDelete)
{
commentsToDelete.Add(comment);
// recursive collection
foreach (var subComment in comment.Comments)
{
this.CollectCommentToDelete(subComment, commentsToDelete);
}
}
/// <summary>
/// Deletes the comment.
/// </summary>
private void DeleteComment()
{
Security.DemandUserHasRight(Rights.ModerateComments, true);
foreach (var comment in
this.Post.Comments.Where(comment => comment.Id == new Guid(this.Request.QueryString["deletecomment"])))
{
this.Post.RemoveComment(comment);
var index = this.Request.RawUrl.IndexOf("?");
var url = string.Format("{0}#comment", this.Request.RawUrl.Substring(0, index));
this.Response.Redirect(url, true);
}
}
/// <summary>
/// Deletes the comment and children.
/// </summary>
private void DeleteCommentAndChildren()
{
Security.DemandUserHasRight(Rights.ModerateComments, true);
var deletecommentandchildren = new Guid(this.Request.QueryString["deletecommentandchildren"]);
foreach (var comment in this.Post.Comments)
{
if (comment.Id != deletecommentandchildren)
{
continue;
}
// collect comments to delete first so the Nesting isn't lost
var commentsToDelete = new List<Comment>();
this.CollectCommentToDelete(comment, commentsToDelete);
foreach (var commentToDelete in commentsToDelete)
{
this.Post.RemoveComment(commentToDelete);
}
var index = this.Request.RawUrl.IndexOf("?");
var url = string.Format("{0}#comment", this.Request.RawUrl.Substring(0, index));
this.Response.Redirect(url, true);
}
}
/// <summary>
/// Enables the captchas.
/// </summary>
private void EnableCaptchas()
{
this.ReCaptchaEnabled = ExtensionManager.ExtensionEnabled("Recaptcha");
this.SimpleCaptchaEnabled = ExtensionManager.ExtensionEnabled("SimpleCaptcha");
if (this.ReCaptchaEnabled && this.SimpleCaptchaEnabled)
{
var simpleCaptchaExtension = ExtensionManager.GetExtension("SimpleCaptcha");
var recaptchaExtension = ExtensionManager.GetExtension("Recaptcha");
if (simpleCaptchaExtension.Priority < recaptchaExtension.Priority)
{
this.EnableRecaptcha();
}
else
{
this.EnableSimpleCaptcha();
}
}
else if (this.ReCaptchaEnabled)
{
this.EnableRecaptcha();
}
else if (this.SimpleCaptchaEnabled)
{
this.EnableSimpleCaptcha();
}
}
/// <summary>
/// Enables the recaptcha.
/// </summary>
private void EnableRecaptcha()
{
this.AnyCaptchaEnabled = true;
this.AnyCaptchaNecessary = this.recaptcha.RecaptchaNecessary;
this.recaptcha.Visible = true;
this.simplecaptcha.Visible = false;
this.SimpleCaptchaEnabled = false;
}
/// <summary>
/// Enables the simple captcha.
/// </summary>
private void EnableSimpleCaptcha()
{
this.AnyCaptchaEnabled = true;
this.AnyCaptchaNecessary = this.simplecaptcha.SimpleCaptchaNecessary;
this.simplecaptcha.Visible = true;
this.recaptcha.Visible = false;
this.ReCaptchaEnabled = false;
}
/// <summary>
/// Gets the cookie with visitor information if any is set.
/// Then fills the contact information fields in the form.
/// </summary>
private void GetCookie()
{
var cookie = this.Request.Cookies["comment"];
try
{
if (cookie != null)
{
this.DefaultName = this.Server.UrlDecode(cookie.Values["name"]);
this.txtEmail.Text = cookie.Values["email"];
this.txtWebsite.Text = cookie.Values["url"];
this.ddlCountry.SelectedValue = cookie.Values["country"];
this.SetFlagImageUrl();
}
else if (Security.IsAuthenticated)
{
var user = Membership.GetUser();
if (user != null)
{
this.DefaultName = user.UserName;
this.txtEmail.Text = user.Email;
}
this.txtWebsite.Text = this.Request.Url.Host;
}
}
catch (Exception)
{
// Couldn't retrieve info on the visitor/user
}
}
/// <summary>
/// Sets a cookie with the entered visitor information
/// so it can be prefilled on next visit.
/// </summary>
/// <param name="name">
/// The cookie name.
/// </param>
/// <param name="email">
/// The email.
/// </param>
/// <param name="website">
/// The website.
/// </param>
/// <param name="country">
/// The country.
/// </param>
private void SetCookie(string name, string email, string website, string country)
{
var cookie = new HttpCookie("comment") { Expires = DateTime.Now.AddMonths(24) };
cookie.Values.Add("name", this.Server.UrlEncode(name.Trim()));
cookie.Values.Add("email", email.Trim());
cookie.Values.Add("url", website.Trim());
cookie.Values.Add("country", country);
this.Response.Cookies.Add(cookie);
}
/// <summary>
/// Sets the flag image URL.
/// </summary>
private void SetFlagImageUrl()
{
//this.imgFlag.ImageUrl = !string.IsNullOrEmpty(this.ddlCountry.SelectedValue)
// ? string.Format(
// "{0}pics/flags/{1}.png",
// Utils.RelativeWebRoot,
// this.ddlCountry.SelectedValue)
// : string.Format("{0}pics/pixel.png", Utils.RelativeWebRoot);
}
#endregion
}
}
| |
//
// GalleryRemote.cs
//
// Author:
// Larry Ewing <[email protected]>
// Stephane Delcroix <sdelcroix*novell.com>
//
// Copyright (C) 2004-2008 Novell, Inc.
// Copyright (C) 2004-2007 Larry Ewing
// Copyright (C) 2006-2008 Stephane Delcroix
//
// 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.Net;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Specialized;
using System.Web;
using Mono.Unix;
using FSpot;
using FSpot.Core;
using FSpot.UI.Dialog;
using Hyena;
using Hyena.Widgets;
/* These classes are based off the documentation at
*
* http://codex.gallery2.org/index.php/Gallery_Remote:Protocol
*/
namespace FSpot.Exporters.Gallery {
public enum AlbumPermission : byte
{
None = 0,
Add = 1,
Write = 2,
Delete = 4,
DeleteAlbum = 8,
CreateSubAlbum = 16
}
public class Album : IComparable {
public int RefNum;
public string Name = null;
public string Title = null;
public string Summary = null;
public int ParentRefNum;
public int ResizeSize;
public int ThumbSize;
public ArrayList Images = null;
public string BaseURL;
Gallery gallery;
public AlbumPermission Perms = AlbumPermission.None;
public Album Parent {
get {
if (ParentRefNum != 0)
return gallery.LookupAlbum (ParentRefNum);
else
return null;
}
}
protected ArrayList parents = null;
public ArrayList Parents {
get {
if (parents != null)
return parents;
if (Parent == null) {
parents = new ArrayList ();
} else {
parents = Parent.Parents.Clone () as ArrayList;
parents.Add (Parent.RefNum);
}
return parents;
}
}
public Gallery Gallery {
get { return gallery; }
}
public Album (Gallery gallery, string name, int ref_num)
{
Name = name;
this.gallery = gallery;
this.RefNum = ref_num;
Images = new ArrayList ();
}
public void Rename (string name)
{
gallery.MoveAlbum (this, name);
}
public void Add (IPhoto item)
{
Add (item, item.DefaultVersion.Uri.LocalPath);
}
public int Add (IPhoto item, string path)
{
if (item == null)
Log.Warning ("NO PHOTO");
return gallery.AddItem (this,
path,
Path.GetFileName (item.DefaultVersion.Uri.LocalPath),
item.Name,
item.Description,
true);
}
public string GetUrl ()
{
return gallery.GetAlbumUrl(this);
}
public int CompareTo (Object obj)
{
Album other = obj as Album;
int numThis = this.Parents.Count;
int numOther = other.Parents.Count;
int thisVal = -1, otherVal = -1;
//find where they first differ
int maxIters = Math.Min (numThis, numOther);
int i = 0;
while (i < maxIters) {
thisVal = (int)this.Parents[i];
otherVal = (int)other.Parents[i];
if (thisVal != otherVal) {
break;
}
i++;
}
int retVal;
if (i < numThis && i < numOther) {
//Parentage differed
retVal = thisVal.CompareTo (otherVal);
} else if (i < numThis) {
//other shorter
thisVal = (int)this.Parents[i];
retVal = thisVal.CompareTo (other.RefNum);
//if equal, we want to make the shorter one come first
if (retVal == 0)
retVal = 1;
} else if (i < numOther) {
//this shorter
otherVal = (int)other.Parents[i];
retVal = this.RefNum.CompareTo (otherVal);
//if equal, we want to make the shorter one come first
if (retVal == 0)
retVal = -1;
} else {
//children of the same parent
retVal = this.RefNum.CompareTo (other.RefNum);
}
return retVal;
}
}
public class Image {
public string Name;
public int RawWidth;
public int RawHeight;
public string ResizedName;
public int ResizedWidth;
public int ResizedHeight;
public string ThumbName;
public int ThumbWidth;
public int ThumbHeight;
public int RawFilesize;
public string Caption;
public string Description;
public int Clicks;
public Album Owner;
public string Url;
public Image (Album album, string name) {
Name = name;
Owner = album;
}
}
public enum ResultCode {
Success = 0,
MajorVersionInvalid = 101,
MajorMinorVersionInvalid = 102,
VersionFormatInvalid = 103,
VersionMissing = 104,
PasswordWrong = 201,
LoginMissing = 202,
UnknownComand = 301,
NoAddPermission = 401,
NoFilename = 402,
UploadPhotoFailed = 403,
NoWritePermission = 404,
NoCreateAlbumPermission = 501,
CreateAlbumFailed = 502,
// This result is specific to this implementation
UnknownResponse = 1000
}
public class GalleryException : System.Exception {
string response_text;
public string ResponseText {
get { return response_text; }
}
public GalleryException (string text) : base (text)
{
}
public GalleryException (string text, string full_response) : base (text)
{
response_text = full_response;
}
}
public class GalleryCommandException : GalleryException {
ResultCode status;
public GalleryCommandException (string status_text, ResultCode result) : base (status_text) {
status = result;
}
public ResultCode Status {
get {
return status;
}
}
}
public abstract class Gallery
{
protected Uri uri;
public Uri Uri{
get {
return uri;
}
}
protected string name;
public string Name {
get {
return name;
}
set {
name = value;
}
}
string auth_token;
public string AuthToken {
get {
return auth_token;
}
set {
auth_token = value;
}
}
protected GalleryVersion version;
public GalleryVersion Version {
get {
return version;
}
}
protected ArrayList albums;
public ArrayList Albums{
get {
return albums;
}
}
public bool expect_continue = true;
protected CookieContainer cookies = null;
public FSpot.ProgressItem Progress = null;
public abstract void Login (string username, string passwd);
public abstract ArrayList FetchAlbums ();
public abstract ArrayList FetchAlbumsPrune ();
public abstract bool MoveAlbum (Album album, string end_name);
public abstract int AddItem (Album album, string path, string filename, string caption, string description, bool autorotate);
//public abstract Album AlbumProperties (string album);
public abstract bool NewAlbum (string parent_name, string name, string title, string description);
public abstract ArrayList FetchAlbumImages (Album album, bool include_ablums);
public abstract string GetAlbumUrl (Album album);
public Gallery (string name)
{
this.name = name;
cookies = new CookieContainer ();
albums = new ArrayList ();
}
public static GalleryVersion DetectGalleryVersion (string url)
{
//Figure out if the url is for G1 or G2
Log.Debug ("Detecting Gallery version");
GalleryVersion version;
if (url.EndsWith (Gallery1.script_name)) {
version = GalleryVersion.Version1;
} else if (url.EndsWith (Gallery2.script_name)) {
version = GalleryVersion.Version2;
} else {
//check what script is available on the server
FormClient client = new FormClient ();
try {
client.Submit (new Uri (Gallery.FixUrl (url, Gallery1.script_name)));
version = GalleryVersion.Version1;
} catch (System.Net.WebException) {
try {
client.Submit (new Uri (Gallery.FixUrl (url, Gallery2.script_name)));
version = GalleryVersion.Version2;
} catch (System.Net.WebException) {
//Uh oh, neither version detected
version = GalleryVersion.VersionUnknown;
}
}
}
Log.Debug ("Detected: " + version.ToString());
return version;
}
public bool IsConnected ()
{
bool retVal = true;
//Console.WriteLine ("^^^^^^^Checking IsConnected");
foreach (Cookie cookie in cookies.GetCookies(Uri)) {
bool isExpired = cookie.Expired;
//Console.WriteLine (cookie.Name + " " + (isExpired ? "expired" : "valid"));
if (isExpired)
retVal = false;
}
//return cookies.GetCookies(Uri).Count > 0;
return retVal;
}
//Reads until it finds the start of the response
protected StreamReader findResponse (HttpWebResponse response)
{
StreamReader reader = new StreamReader (response.GetResponseStream (), Encoding.UTF8);
if (reader == null)
throw new GalleryException (Catalog.GetString ("Error reading server response"));
string line;
string full_response = null;
while ((line = reader.ReadLine ()) != null) {
full_response += line;
if (line.IndexOf ("#__GR2PROTO__", 0) > -1)
break;
}
if (line == null) {
// failed to find the response
throw new GalleryException (Catalog.GetString ("Server returned response without Gallery content"), full_response);
}
return reader;
}
protected string [] GetNextLine (StreamReader reader)
{
char [] value_split = new char [1] {'='};
bool haveLine = false;
string[] array = null;
while(!haveLine) {
string line = reader.ReadLine ();
//Console.WriteLine ("READING: " + line);
if (line != null) {
array = line.Split (value_split, 2);
haveLine = !LineIgnored (array);
}
else {
//end of input
return null;
}
}
return array;
}
private bool LineIgnored (string[] line)
{
if (line[0].StartsWith ("debug")) {
return true;
} else if (line[0].StartsWith ("can_create_root")) {
return true;
} else {
return false;
}
}
protected bool ParseLogin (HttpWebResponse response)
{
string [] data;
StreamReader reader = null;
ResultCode status = ResultCode.UnknownResponse;
string status_text = "Error: Unable to parse server response";
try {
reader = findResponse (response);
while ((data = GetNextLine (reader)) != null) {
if (data[0] == "status") {
status = (ResultCode) int.Parse (data [1]);
} else if (data[0].StartsWith ("status_text")) {
status_text = data[1];
Log.DebugFormat ("StatusText : {0}", data[1]);
} else if (data[0].StartsWith ("server_version")) {
//FIXME we should use the to determine what capabilities the server has
} else if (data[0].StartsWith ("auth_token")) {
AuthToken = data[1];
} else {
Log.DebugFormat ("Unparsed Line in ParseLogin(): {0}={1}", data[0], data[1]);
}
}
//Console.WriteLine ("Found: {0} cookies", response.Cookies.Count);
if (status != ResultCode.Success) {
Log.Debug (status_text);
throw new GalleryCommandException (status_text, status);
}
return true;
} finally {
if (reader != null)
reader.Close ();
response.Close ();
}
}
public ArrayList ParseFetchAlbums (HttpWebResponse response)
{
//Console.WriteLine ("in ParseFetchAlbums()");
string [] data;
StreamReader reader = null;
ResultCode status = ResultCode.UnknownResponse;
string status_text = "Error: Unable to parse server response";
albums = new ArrayList ();
try {
Album current_album = null;
reader = findResponse (response);
while ((data = GetNextLine (reader)) != null) {
//Console.WriteLine ("Parsing Line: {0}={1}", data[0], data[1]);
if (data[0] == "status") {
status = (ResultCode) int.Parse (data [1]);
} else if (data[0].StartsWith ("status_text")) {
status_text = data[1];
Log.DebugFormat ("StatusText : {0}", data[1]);
} else if (data[0].StartsWith ("album.name")) {
//this is the URL name
int ref_num = -1;
if (this.Version == GalleryVersion.Version1) {
string [] segments = data[0].Split (new char[1]{'.'});
ref_num = int.Parse (segments[segments.Length -1]);
} else {
ref_num = int.Parse (data[1]);
}
current_album = new Album (this, data[1], ref_num);
albums.Add (current_album);
//Console.WriteLine ("current_album: " + data[1]);
} else if (data[0].StartsWith ("album.title")) {
//this is the display name
current_album.Title = data[1];
} else if (data[0].StartsWith ("album.summary")) {
current_album.Summary = data[1];
} else if (data[0].StartsWith ("album.parent")) {
//FetchAlbums and G2 FetchAlbumsPrune return ints
//G1 FetchAlbumsPrune returns album names (and 0 for root albums)
try {
current_album.ParentRefNum = int.Parse (data[1]);
} catch (System.FormatException) {
current_album.ParentRefNum = LookupAlbum (data[1]).RefNum;
}
//Console.WriteLine ("album.parent data[1]: " + data[1]);
} else if (data[0].StartsWith ("album.resize_size")) {
current_album.ResizeSize = int.Parse (data[1]);
} else if (data[0].StartsWith ("album.thumb_size")) {
current_album.ThumbSize = int.Parse (data[1]);
} else if (data[0].StartsWith ("album.info.extrafields")) {
//ignore, this is the album description
} else if (data[0].StartsWith ("album.perms.add")) {
if (data[1] == "true")
current_album.Perms |= AlbumPermission.Add;
} else if (data[0].StartsWith ("album.perms.write")) {
if (data[1] == "true")
current_album.Perms |= AlbumPermission.Write;
} else if (data[0].StartsWith ("album.perms.del_item")) {
if (data[1] == "true")
current_album.Perms |= AlbumPermission.Delete;
} else if (data[0].StartsWith ("album.perms.del_alb")) {
if (data[1] == "true")
current_album.Perms |= AlbumPermission.DeleteAlbum;
} else if (data[0].StartsWith ("album.perms.create_sub")) {
if (data[1] == "true")
current_album.Perms |= AlbumPermission.CreateSubAlbum;
} else if (data[0].StartsWith ("album_count")) {
if (Albums.Count != int.Parse (data[1]))
Log.Warning ("Parsed album count does not match album_count. Something is amiss");
} else if (data[0].StartsWith ("auth_token")) {
AuthToken = data [1];
} else {
Log.DebugFormat ("Unparsed Line in ParseFetchAlbums(): {0}={1}", data[0], data[1]);
}
}
//Console.WriteLine ("Found: {0} cookies", response.Cookies.Count);
if (status != ResultCode.Success) {
Log.Debug (status_text);
throw new GalleryCommandException (status_text, status);
}
//Console.WriteLine (After parse albums.Count + " albums parsed");
return albums;
} finally {
if (reader != null)
reader.Close ();
response.Close ();
}
}
public int ParseAddItem (HttpWebResponse response)
{
string [] data;
StreamReader reader = null;
ResultCode status = ResultCode.UnknownResponse;
string status_text = "Error: Unable to parse server response";
int item_id = 0;
try {
reader = findResponse (response);
while ((data = GetNextLine (reader)) != null) {
if (data[0] == "status") {
status = (ResultCode) int.Parse (data [1]);
} else if (data[0].StartsWith ("status_text")) {
status_text = data[1];
Log.DebugFormat ("StatusText : {0}", data[1]);
} else if (data[0].StartsWith ("auth_token")) {
AuthToken = data[1];
} else if (data[0].StartsWith ("item_name")) {
item_id = int.Parse (data [1]);
} else {
Log.DebugFormat ("Unparsed Line in ParseAddItem(): {0}={1}", data[0], data[1]);
}
}
//Console.WriteLine ("Found: {0} cookies", response.Cookies.Count);
if (status != ResultCode.Success) {
Log.Debug (status_text);
throw new GalleryCommandException (status_text, status);
}
return item_id;
} finally {
if (reader != null)
reader.Close ();
response.Close ();
}
}
public bool ParseNewAlbum (HttpWebResponse response)
{
return ParseBasic (response);
}
public bool ParseMoveAlbum (HttpWebResponse response)
{
return ParseBasic (response);
}
/*
public Album ParseAlbumProperties (HttpWebResponse response)
{
string [] data;
StreamReader reader = null;
ResultCode status = ResultCode.UnknownResponse;
string status_text = "Error: Unable to parse server response";
try {
reader = findResponse (response);
while ((data = GetNextLine (reader)) != null) {
if (data[0] == "status") {
status = (ResultCode) int.Parse (data [1]);
} else if (data[0].StartsWith ("status_text")) {
status_text = data[1];
Log.Debug ("StatusText : {0}", data[1]);
} else if (data[0].StartsWith ("auto-resize")) {
//ignore
} else {
Log.Debug ("Unparsed Line in ParseBasic(): {0}={1}", data[0], data[1]);
}
}
//Console.WriteLine ("Found: {0} cookies", response.Cookies.Count);
if (status != ResultCode.Success) {
Log.Debug (status_text);
throw new GalleryCommandException (status_text, status);
}
return true;
} finally {
if (reader != null)
reader.Close ();
response.Close ();
}
}
*/
private bool ParseBasic (HttpWebResponse response)
{
string [] data;
StreamReader reader = null;
ResultCode status = ResultCode.UnknownResponse;
string status_text = "Error: Unable to parse server response";
try {
reader = findResponse (response);
while ((data = GetNextLine (reader)) != null) {
if (data[0] == "status") {
status = (ResultCode) int.Parse (data [1]);
} else if (data[0].StartsWith ("status_text")) {
status_text = data[1];
Log.DebugFormat ("StatusText : {0}", data[1]);
} else if (data[0].StartsWith ("auth_token")) {
AuthToken = data[1];
} else {
Log.DebugFormat ("Unparsed Line in ParseBasic(): {0}={1}", data[0], data[1]);
}
}
//Console.WriteLine ("Found: {0} cookies", response.Cookies.Count);
if (status != ResultCode.Success) {
Log.Debug (status_text + " Status: " + status);
throw new GalleryCommandException (status_text, status);
}
return true;
} finally {
if (reader != null)
reader.Close ();
response.Close ();
}
}
public Album LookupAlbum (string name)
{
Album match = null;
foreach (Album album in albums) {
if (album.Name == name) {
match = album;
break;
}
}
return match;
}
public Album LookupAlbum (int ref_num)
{
// FIXME this is really not the best way to do this
Album match = null;
foreach (Album album in albums) {
if (album.RefNum == ref_num) {
match = album;
break;
}
}
return match;
}
public static string FixUrl(string url, string end)
{
string fixedUrl = url;
if (!url.EndsWith (end)) {
if (!url.EndsWith ("/"))
fixedUrl = url + "/";
fixedUrl = fixedUrl + end;
}
return fixedUrl;
}
public void PopupException (GalleryCommandException e, Gtk.Dialog d)
{
Log.DebugFormat ("{0} : {1} ({2})", e.Message, e.ResponseText, e.Status);
HigMessageDialog md =
new HigMessageDialog (d,
Gtk.DialogFlags.Modal |
Gtk.DialogFlags.DestroyWithParent,
Gtk.MessageType.Error, Gtk.ButtonsType.Ok,
Catalog.GetString ("Error while creating new album"),
String.Format (Catalog.GetString ("The following error was encountered while attempting to perform the requested operation:\n{0} ({1})"), e.Message, e.Status));
md.Run ();
md.Destroy ();
}
}
public class Gallery1 : Gallery
{
public const string script_name = "gallery_remote2.php";
public Gallery1 (string url) : this (url, url) {}
public Gallery1 (string name, string url) : base (name)
{
this.uri = new Uri (FixUrl (url, script_name));
version = GalleryVersion.Version1;
}
public override void Login (string username, string passwd)
{
//Console.WriteLine ("Gallery1: Attempting to login");
FormClient client = new FormClient (cookies);
client.Add ("cmd", "login");
client.Add ("protocol_version", "2.3");
client.Add ("uname", username);
client.Add ("password", passwd);
ParseLogin (client.Submit (uri));
}
public override ArrayList FetchAlbums ()
{
FormClient client = new FormClient (cookies);
client.Add ("cmd", "fetch-albums");
client.Add ("protocol_version", "2.3");
return ParseFetchAlbums (client.Submit (uri));
}
public override bool MoveAlbum (Album album, string end_name)
{
FormClient client = new FormClient (cookies);
client.Add ("cmd", "move-album");
client.Add ("protocol_version", "2.7");
client.Add ("set_albumName", album.Name);
client.Add ("set_destalbumName", end_name);
return ParseMoveAlbum (client.Submit (uri));
}
public override int AddItem (Album album,
string path,
string filename,
string caption,
string description,
bool autorotate)
{
FormClient client = new FormClient (cookies);
client.Add ("cmd", "add-item");
client.Add ("protocol_version", "2.9");
client.Add ("set_albumName", album.Name);
client.Add ("caption", caption);
client.Add ("userfile_name", filename);
client.Add ("force_filename", filename);
client.Add ("auto_rotate", autorotate ? "yes" : "no");
client.Add ("userfile", new FileInfo (path));
client.Add ("extrafield.Description", description);
client.expect_continue = expect_continue;
return ParseAddItem (client.Submit (uri, Progress));
}
/*
public override Album AlbumProperties (string album)
{
FormClient client = new FormClient (cookies);
client.Add ("cmd", "album-properties");
client.Add ("protocol_version", "2.3");
client.Add ("set_albumName", album);
return ParseAlbumProperties (client.Submit (uri));
}
*/
public override bool NewAlbum (string parent_name,
string name,
string title,
string description)
{
FormClient client = new FormClient (cookies);
client.Multipart = true;
client.Add ("cmd", "new-album");
client.Add ("protocol_version", "2.8");
client.Add ("set_albumName", parent_name);
client.Add ("newAlbumName", name);
client.Add ("newAlbumTitle", title);
client.Add ("newAlbumDesc", description);
return ParseNewAlbum (client.Submit (uri));
}
public override ArrayList FetchAlbumImages (Album album, bool include_ablums)
{
FormClient client = new FormClient (cookies);
client.Add ("cmd", "fetch-album-images");
client.Add ("protocol_version","2.3");
client.Add ("set_albumName", album.Name);
client.Add ("albums_too", include_ablums ? "yes" : "no");
album.Images = ParseFetchAlbumImages (client.Submit (uri), album);
return album.Images;
}
public override ArrayList FetchAlbumsPrune ()
{
FormClient client = new FormClient (cookies);
client.Add ("cmd", "fetch-albums-prune");
client.Add ("protocol_version", "2.3");
client.Add ("check_writable", "no");
ArrayList a = ParseFetchAlbums (client.Submit (uri));
a.Sort();
return a;
}
public ArrayList ParseFetchAlbumImages (HttpWebResponse response, Album album)
{
string [] data;
StreamReader reader = null;
ResultCode status = ResultCode.UnknownResponse;
string status_text = "Error: Unable to parse server response";
try {
Image current_image = null;
reader = findResponse (response);
while ((data = GetNextLine (reader)) != null) {
if (data[0] == "status") {
status = (ResultCode) int.Parse (data [1]);
} else if (data[0].StartsWith ("status_text")) {
status_text = data[1];
Log.DebugFormat ("StatusText : {0}", data[1]);
} else if (data[0].StartsWith ("image.name")) {
current_image = new Image (album, data[1]);
album.Images.Add (current_image);
} else if (data[0].StartsWith ("image.raw_width")) {
current_image.RawWidth = int.Parse (data[1]);
} else if (data[0].StartsWith ("image.raw_height")) {
current_image.RawHeight = int.Parse (data[1]);
} else if (data[0].StartsWith ("image.raw_height")) {
current_image.RawHeight = int.Parse (data[1]);
} else if (data[0].StartsWith ("image.raw_filesize")) {
} else if (data[0].StartsWith ("image.capturedate.year")) {
} else if (data[0].StartsWith ("image.capturedate.mon")) {
} else if (data[0].StartsWith ("image.capturedate.mday")) {
} else if (data[0].StartsWith ("image.capturedate.hours")) {
} else if (data[0].StartsWith ("image.capturedate.minutes")) {
} else if (data[0].StartsWith ("image.capturedate.seconds")) {
} else if (data[0].StartsWith ("image.hidden")) {
} else if (data[0].StartsWith ("image.resizedName")) {
current_image.ResizedName = data[1];
} else if (data[0].StartsWith ("image.resized_width")) {
current_image.ResizedWidth = int.Parse (data[1]);
} else if (data[0].StartsWith ("image.resized_height")) {
current_image.ResizedHeight = int.Parse (data[1]);
} else if (data[0].StartsWith ("image.thumbName")) {
current_image.ThumbName = data[1];
} else if (data[0].StartsWith ("image.thumb_width")) {
current_image.ThumbWidth = int.Parse (data[1]);
} else if (data[0].StartsWith ("image.thumb_height")) {
current_image.ThumbHeight = int.Parse (data[1]);
} else if (data[0].StartsWith ("image.caption")) {
current_image.Caption = data[1];
} else if (data[0].StartsWith ("image.extrafield.Description")) {
current_image.Description = data[1];
} else if (data[0].StartsWith ("image.clicks")) {
try {
current_image.Clicks = int.Parse (data[1]);
} catch (System.FormatException) {
current_image.Clicks = 0;
}
} else if (data[0].StartsWith ("baseurl")) {
album.BaseURL = data[1];
} else if (data[0].StartsWith ("image_count")) {
if (album.Images.Count != int.Parse (data[1]))
Log.Warning ("Parsed image count for " + album.Name + "(" + album.Images.Count + ") does not match image_count (" + data[1] + "). Something is amiss");
} else {
Log.DebugFormat ("Unparsed Line in ParseFetchAlbumImages(): {0}={1}", data[0], data[1]);
}
}
//Console.WriteLine ("Found: {0} cookies", response.Cookies.Count);
if (status != ResultCode.Success) {
Log.Debug (status_text);
throw new GalleryCommandException (status_text, status);
}
//Set the Urls for downloading the images.
string baseUrl = album.BaseURL + "/";
foreach (Image image in album.Images) {
image.Url = baseUrl + image.Name;
}
return album.Images;
} finally {
if (reader != null)
reader.Close ();
response.Close ();
}
}
public override string GetAlbumUrl (Album album)
{
string url = Uri.ToString();
url = url.Remove (url.Length - script_name.Length, script_name.Length);
string path = album.Name;
url = url + path;
url = url.Replace (" ", "+");
return url;
}
}
public class Gallery2 : Gallery
{
public const string script_name = "main.php";
public Gallery2 (string url) : this (url, url) {}
public Gallery2 (string name, string url) : base (name)
{
this.uri = new Uri (FixUrl (url, script_name));
version = GalleryVersion.Version2;
}
public override void Login (string username, string passwd)
{
Log.Debug ("Gallery2: Attempting to login");
FormClient client = new FormClient (cookies);
client.Add ("g2_form[cmd]", "login");
client.Add ("g2_form[protocol_version]", "2.10");
client.Add ("g2_form[uname]", username);
client.Add ("g2_form[password]", passwd);
AddG2Specific (client);
ParseLogin (client.Submit (uri));
}
public override ArrayList FetchAlbums ()
{
//FetchAlbums doesn't exist for G2, we have to use FetchAlbumsPrune()
return FetchAlbumsPrune ();
}
public override bool MoveAlbum (Album album, string end_name)
{
FormClient client = new FormClient (cookies);
client.Add ("g2_form[cmd]", "move-album");
client.Add ("g2_form[protocol_version]", "2.10");
client.Add ("g2_form[set_albumName]", album.Name);
client.Add ("g2_form[set_destalbumName]", end_name);
AddG2Specific (client);
return ParseMoveAlbum (client.Submit (uri));
}
public override int AddItem (Album album,
string path,
string filename,
string caption,
string description,
bool autorotate)
{
FormClient client = new FormClient (cookies);
client.Add ("g2_form[cmd]", "add-item");
client.Add ("g2_form[protocol_version]", "2.10");
client.Add ("g2_form[set_albumName]", album.Name);
client.Add ("g2_form[caption]", caption);
client.Add ("g2_form[userfile_name]", filename);
client.Add ("g2_form[force_filename]", filename);
client.Add ("g2_form[auto_rotate]", autorotate ? "yes" : "no");
client.Add ("g2_form[extrafield.Description]", description);
client.Add ("g2_userfile", new FileInfo (path));
client.expect_continue = expect_continue;
AddG2Specific (client);
return ParseAddItem (client.Submit (uri, Progress));
}
/*
public override Album AlbumProperties (string album)
{
FormClient client = new FormClient (cookies);
client.Add ("cmd", "album-properties");
client.Add ("protocol_version", "2.3");
client.Add ("set_albumName", album);
return ParseAlbumProperties (client.Submit (uri));
}
*/
public override bool NewAlbum (string parent_name,
string name,
string title,
string description)
{
FormClient client = new FormClient (cookies);
client.Multipart = true;
client.Add ("g2_form[cmd]", "new-album");
client.Add ("g2_form[protocol_version]", "2.10");
client.Add ("g2_form[set_albumName]", parent_name);
client.Add ("g2_form[newAlbumName]", name);
client.Add ("g2_form[newAlbumTitle]", title);
client.Add ("g2_form[newAlbumDesc]", description);
AddG2Specific (client);
return ParseNewAlbum (client.Submit (uri));
}
public override ArrayList FetchAlbumImages (Album album, bool include_ablums)
{
FormClient client = new FormClient (cookies);
client.Add ("g2_form[cmd]", "fetch-album-images");
client.Add ("g2_form[protocol_version]","2.10");
client.Add ("g2_form[set_albumName]", album.Name);
client.Add ("g2_form[albums_too]", include_ablums ? "yes" : "no");
AddG2Specific (client);
album.Images = ParseFetchAlbumImages (client.Submit (uri), album);
return album.Images;
}
public override ArrayList FetchAlbumsPrune ()
{
FormClient client = new FormClient (cookies);
client.Add ("g2_form[cmd]", "fetch-albums-prune");
client.Add ("g2_form[protocol_version]", "2.10");
client.Add ("g2_form[check_writable]", "no");
AddG2Specific (client);
ArrayList a = ParseFetchAlbums (client.Submit (uri));
a.Sort();
return a;
}
private void AddG2Specific (FormClient client)
{
if (AuthToken != null && AuthToken != String.Empty)
client.Add("g2_authToken", AuthToken);
client.Add("g2_controller", "remote.GalleryRemote");
}
public ArrayList ParseFetchAlbumImages (HttpWebResponse response, Album album)
{
string [] data;
StreamReader reader = null;
ResultCode status = ResultCode.UnknownResponse;
string status_text = "Error: Unable to parse server response";
try {
Image current_image = null;
string baseUrl = Uri.ToString() + "?g2_view=core.DownloadItem&g2_itemId=";
reader = findResponse (response);
while ((data = GetNextLine (reader)) != null) {
if (data[0] == "status") {
status = (ResultCode) int.Parse (data [1]);
} else if (data[0].StartsWith ("status_text")) {
status_text = data[1];
Log.DebugFormat ("StatusText : {0}", data[1]);
} else if (data[0].StartsWith ("image.name")) {
//for G2 this is the number used to download the image.
current_image = new Image (album, "awaiting 'title'");
album.Images.Add (current_image);
current_image.Url = baseUrl + data[1];
} else if (data[0].StartsWith ("image.title")) {
//for G2 the "title" is the name"
current_image.Name = data[1];
} else if (data[0].StartsWith ("image.raw_width")) {
current_image.RawWidth = int.Parse (data[1]);
} else if (data[0].StartsWith ("image.raw_height")) {
current_image.RawHeight = int.Parse (data[1]);
} else if (data[0].StartsWith ("image.raw_height")) {
current_image.RawHeight = int.Parse (data[1]);
//ignore these for now
} else if (data[0].StartsWith ("image.raw_filesize")) {
} else if (data[0].StartsWith ("image.forceExtension")) {
} else if (data[0].StartsWith ("image.capturedate.year")) {
} else if (data[0].StartsWith ("image.capturedate.mon")) {
} else if (data[0].StartsWith ("image.capturedate.mday")) {
} else if (data[0].StartsWith ("image.capturedate.hours")) {
} else if (data[0].StartsWith ("image.capturedate.minutes")) {
} else if (data[0].StartsWith ("image.capturedate.seconds")) {
} else if (data[0].StartsWith ("image.hidden")) {
} else if (data[0].StartsWith ("image.resizedName")) {
current_image.ResizedName = data[1];
} else if (data[0].StartsWith ("image.resized_width")) {
current_image.ResizedWidth = int.Parse (data[1]);
} else if (data[0].StartsWith ("image.resized_height")) {
current_image.ResizedHeight = int.Parse (data[1]);
} else if (data[0].StartsWith ("image.thumbName")) {
current_image.ThumbName = data[1];
} else if (data[0].StartsWith ("image.thumb_width")) {
current_image.ThumbWidth = int.Parse (data[1]);
} else if (data[0].StartsWith ("image.thumb_height")) {
current_image.ThumbHeight = int.Parse (data[1]);
} else if (data[0].StartsWith ("image.caption")) {
current_image.Caption = data[1];
} else if (data[0].StartsWith ("image.extrafield.Description")) {
current_image.Description = data[1];
} else if (data[0].StartsWith ("image.clicks")) {
try {
current_image.Clicks = int.Parse (data[1]);
} catch (System.FormatException) {
current_image.Clicks = 0;
}
} else if (data[0].StartsWith ("baseurl")) {
album.BaseURL = data[1];
} else if (data[0].StartsWith ("image_count")) {
if (album.Images.Count != int.Parse (data[1]))
Log.Warning ("Parsed image count for " + album.Name + "(" + album.Images.Count + ") does not match image_count (" + data[1] + "). Something is amiss");
} else {
Log.DebugFormat ("Unparsed Line in ParseFetchAlbumImages(): {0}={1}", data[0], data[1]);
}
}
Log.DebugFormat ("Found: {0} cookies", response.Cookies.Count);
if (status != ResultCode.Success) {
Log.Debug (status_text);
throw new GalleryCommandException (status_text, status);
}
return album.Images;
} finally {
if (reader != null)
reader.Close ();
response.Close ();
}
}
public override string GetAlbumUrl (Album album)
{
return Uri.ToString() + "?g2_view=core.ShowItem&g2_itemId=" + album.Name;
}
}
public enum GalleryVersion : byte
{
VersionUnknown = 0,
Version1 = 1,
Version2 = 2
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#region Using directives
using System;
using System.Collections.Generic;
using System.Management.Automation;
using System.Management.Automation.SecurityAccountsManager;
using System.Management.Automation.SecurityAccountsManager.Extensions;
using Microsoft.PowerShell.LocalAccounts;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// The Enable-LocalUser cmdlet enables local user accounts. When a user account
/// is disabled, the user is not permitted to log on. When a user account is
/// enabled, the user is permitted to log on normally.
/// </summary>
[Cmdlet(VerbsLifecycle.Enable, "LocalUser",
SupportsShouldProcess = true,
HelpUri = "https://go.microsoft.com/fwlink/?LinkId=717985")]
[Alias("elu")]
public class EnableLocalUserCommand : Cmdlet
{
#region Constants
private const Enabling enabling = Enabling.Enable;
#endregion Constants
#region Instance Data
private Sam sam = null;
#endregion Instance Data
#region Parameter Properties
/// <summary>
/// The following is the definition of the input parameter "InputObject".
/// Specifies the of the local user accounts to enable in the local Security
/// Accounts Manager.
/// </summary>
[Parameter(Mandatory = true,
Position = 0,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = "InputObject")]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public Microsoft.PowerShell.Commands.LocalUser[] InputObject
{
get { return this.inputobject; }
set { this.inputobject = value; }
}
private Microsoft.PowerShell.Commands.LocalUser[] inputobject;
/// <summary>
/// The following is the definition of the input parameter "Name".
/// Specifies the local user accounts to enable in the local Security Accounts
/// Manager.
/// </summary>
[Parameter(Mandatory = true,
Position = 0,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = "Default")]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] Name
{
get { return this.name; }
set { this.name = value; }
}
private string[] name;
/// <summary>
/// The following is the definition of the input parameter "SID".
/// Specifies the LocalUser accounts to enable by
/// System.Security.Principal.SecurityIdentifier.
/// </summary>
[Parameter(Mandatory = true,
Position = 0,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = "SecurityIdentifier")]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public System.Security.Principal.SecurityIdentifier[] SID
{
get { return this.sid;}
set { this.sid = value; }
}
private System.Security.Principal.SecurityIdentifier[] sid;
#endregion Parameter Properties
#region Cmdlet Overrides
/// <summary>
/// BeginProcessing method.
/// </summary>
protected override void BeginProcessing()
{
sam = new Sam();
}
/// <summary>
/// ProcessRecord method.
/// </summary>
protected override void ProcessRecord()
{
try
{
ProcessUsers();
ProcessNames();
ProcessSids();
}
catch (Exception ex)
{
WriteError(ex.MakeErrorRecord());
}
}
/// <summary>
/// EndProcessing method.
/// </summary>
protected override void EndProcessing()
{
if (sam != null)
{
sam.Dispose();
sam = null;
}
}
#endregion Cmdlet Overrides
#region Private Methods
/// <summary>
/// Process users requested by -Name.
/// </summary>
/// <remarks>
/// All arguments to -Name will be treated as names,
/// even if a name looks like a SID.
/// </remarks>
private void ProcessNames()
{
if (Name != null)
{
foreach (var name in Name)
{
try
{
if (CheckShouldProcess(name))
sam.EnableLocalUser(sam.GetLocalUser(name), enabling);
}
catch (Exception ex)
{
WriteError(ex.MakeErrorRecord());
}
}
}
}
/// <summary>
/// Process users requested by -SID.
/// </summary>
private void ProcessSids()
{
if (SID != null)
{
foreach (var sid in SID)
{
try
{
if (CheckShouldProcess(sid.ToString()))
sam.EnableLocalUser(sid, enabling);
}
catch (Exception ex)
{
WriteError(ex.MakeErrorRecord());
}
}
}
}
/// <summary>
/// Process users requested by -InputObject.
/// </summary>
private void ProcessUsers()
{
if (InputObject != null)
{
foreach (var user in InputObject)
{
try
{
if (CheckShouldProcess(user.Name))
sam.EnableLocalUser(user, enabling);
}
catch (Exception ex)
{
WriteError(ex.MakeErrorRecord());
}
}
}
}
private bool CheckShouldProcess(string target)
{
return ShouldProcess(target, Strings.ActionEnableUser);
}
#endregion Private Methods
}
}
| |
// 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.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
#pragma warning disable 618 // obsolete types
namespace System.Collections.Tests
{
public class HashtableTests : RemoteExecutorTestBase
{
[Fact]
public void Ctor_Empty()
{
var hash = new ComparableHashtable();
VerifyHashtable(hash, null, null);
}
[Fact]
public void Ctor_HashCodeProvider_Comparer()
{
var hash = new ComparableHashtable(CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase);
VerifyHashtable(hash, null, hash.EqualityComparer);
Assert.Same(CaseInsensitiveHashCodeProvider.DefaultInvariant, hash.HashCodeProvider);
Assert.Same(StringComparer.OrdinalIgnoreCase, hash.Comparer);
}
[Theory]
[InlineData(false, false)]
[InlineData(false, true)]
[InlineData(true, false)]
[InlineData(true, true)]
public void Ctor_HashCodeProvider_Comparer_NullInputs(bool nullProvider, bool nullComparer)
{
var hash = new ComparableHashtable(
nullProvider ? null : CaseInsensitiveHashCodeProvider.DefaultInvariant,
nullComparer ? null : StringComparer.OrdinalIgnoreCase);
VerifyHashtable(hash, null, hash.EqualityComparer);
}
[Fact]
public void Ctor_IDictionary()
{
// No exception
var hash1 = new ComparableHashtable(new Hashtable());
Assert.Equal(0, hash1.Count);
hash1 = new ComparableHashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable())))));
Assert.Equal(0, hash1.Count);
Hashtable hash2 = Helpers.CreateIntHashtable(100);
hash1 = new ComparableHashtable(hash2);
VerifyHashtable(hash1, hash2, null);
}
[Fact]
public void Ctor_IDictionary_NullDictionary_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("d", () => new Hashtable((IDictionary)null)); // Dictionary is null
}
[Fact]
public void Ctor_IDictionary_HashCodeProvider_Comparer()
{
// No exception
var hash1 = new ComparableHashtable(new Hashtable(), CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase);
Assert.Equal(0, hash1.Count);
hash1 = new ComparableHashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable())))), CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase);
Assert.Equal(0, hash1.Count);
Hashtable hash2 = Helpers.CreateIntHashtable(100);
hash1 = new ComparableHashtable(hash2, CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase);
VerifyHashtable(hash1, hash2, hash1.EqualityComparer);
}
[Fact]
public void Ctor_IDictionary_HashCodeProvider_Comparer_NullDictionary_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("d", () => new Hashtable(null, CaseInsensitiveHashCodeProvider.Default, StringComparer.OrdinalIgnoreCase)); // Dictionary is null
}
[Fact]
public void Ctor_IEqualityComparer()
{
RemoteInvoke(() =>
{
// Null comparer
var hash = new ComparableHashtable((IEqualityComparer)null);
VerifyHashtable(hash, null, null);
// Custom comparer
IEqualityComparer comparer = StringComparer.CurrentCulture;
hash = new ComparableHashtable(comparer);
VerifyHashtable(hash, null, comparer);
return SuccessExitCode;
}).Dispose();
}
[Theory]
[InlineData(0)]
[InlineData(10)]
[InlineData(100)]
public void Ctor_Int(int capacity)
{
var hash = new ComparableHashtable(capacity);
VerifyHashtable(hash, null, null);
}
[Theory]
[InlineData(0)]
[InlineData(10)]
[InlineData(100)]
public void Ctor_Int_HashCodeProvider_Comparer(int capacity)
{
var hash = new ComparableHashtable(capacity, CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase);
VerifyHashtable(hash, null, hash.EqualityComparer);
}
[Fact]
public void Ctor_Int_Invalid()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new Hashtable(-1)); // Capacity < 0
AssertExtensions.Throws<ArgumentException>("capacity", null, () => new Hashtable(int.MaxValue)); // Capacity / load factor > int.MaxValue
}
[Fact]
public void Ctor_IDictionary_Int()
{
// No exception
var hash1 = new ComparableHashtable(new Hashtable(), 1f, CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase);
Assert.Equal(0, hash1.Count);
hash1 = new ComparableHashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(), 1f), 1f), 1f), 1f), 1f,
CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase);
Assert.Equal(0, hash1.Count);
Hashtable hash2 = Helpers.CreateIntHashtable(100);
hash1 = new ComparableHashtable(hash2, 1f, CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase);
VerifyHashtable(hash1, hash2, hash1.EqualityComparer);
}
[Fact]
public void Ctor_IDictionary_Int_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("d", () => new Hashtable(null, 1f)); // Dictionary is null
AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), 0.09f)); // Load factor < 0.1f
AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), 1.01f)); // Load factor > 1f
AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), float.NaN)); // Load factor is NaN
AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), float.PositiveInfinity)); // Load factor is infinity
AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), float.NegativeInfinity)); // Load factor is infinity
}
[Fact]
public void Ctor_IDictionary_Int_HashCodeProvider_Comparer()
{
// No exception
var hash1 = new ComparableHashtable(new Hashtable(), 1f);
Assert.Equal(0, hash1.Count);
hash1 = new ComparableHashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(), 1f), 1f), 1f), 1f), 1f);
Assert.Equal(0, hash1.Count);
Hashtable hash2 = Helpers.CreateIntHashtable(100);
hash1 = new ComparableHashtable(hash2, 1f);
VerifyHashtable(hash1, hash2, null);
}
[Fact]
public void Ctor_IDictionary_IEqualityComparer()
{
RemoteInvoke(() =>
{
// No exception
var hash1 = new ComparableHashtable(new Hashtable(), null);
Assert.Equal(0, hash1.Count);
hash1 = new ComparableHashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(), null), null), null), null), null);
Assert.Equal(0, hash1.Count);
// Null comparer
Hashtable hash2 = Helpers.CreateIntHashtable(100);
hash1 = new ComparableHashtable(hash2, null);
VerifyHashtable(hash1, hash2, null);
// Custom comparer
hash2 = Helpers.CreateIntHashtable(100);
IEqualityComparer comparer = StringComparer.CurrentCulture;
hash1 = new ComparableHashtable(hash2, comparer);
VerifyHashtable(hash1, hash2, comparer);
return SuccessExitCode;
}).Dispose();
}
[Fact]
public void Ctor_IDictionary_IEqualityComparer_NullDictionary_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("d", () => new Hashtable((IDictionary)null, null)); // Dictionary is null
}
[Theory]
[InlineData(0, 0.1)]
[InlineData(10, 0.2)]
[InlineData(100, 0.3)]
[InlineData(1000, 1)]
public void Ctor_Int_Int(int capacity, float loadFactor)
{
var hash = new ComparableHashtable(capacity, loadFactor);
VerifyHashtable(hash, null, null);
}
[Theory]
[InlineData(0, 0.1)]
[InlineData(10, 0.2)]
[InlineData(100, 0.3)]
[InlineData(1000, 1)]
public void Ctor_Int_Int_HashCodeProvider_Comparer(int capacity, float loadFactor)
{
var hash = new ComparableHashtable(capacity, loadFactor, CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase);
VerifyHashtable(hash, null, hash.EqualityComparer);
}
[Fact]
public void Ctor_Int_Int_GenerateNewPrime()
{
// The ctor for Hashtable performs the following calculation:
// rawSize = capacity / (loadFactor * 0.72)
// If rawSize is > 3, then it calls HashHelpers.GetPrime(rawSize) to generate a prime.
// Then, if the rawSize > 7,199,369 (the largest number in a list of known primes), we have to generate a prime programatically
// This test makes sure this works.
int capacity = 8000000;
float loadFactor = 0.1f / 0.72f;
try
{
var hash = new ComparableHashtable(capacity, loadFactor);
}
catch (OutOfMemoryException)
{
// On memory constrained devices, we can get an OutOfMemoryException, which we can safely ignore.
}
}
[Fact]
public void Ctor_Int_Int_Invalid()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new Hashtable(-1, 1f)); // Capacity < 0
AssertExtensions.Throws<ArgumentException>("capacity", null, () => new Hashtable(int.MaxValue, 0.1f)); // Capacity / load factor > int.MaxValue
AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, 0.09f)); // Load factor < 0.1f
AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, 1.01f)); // Load factor > 1f
AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, float.NaN)); // Load factor is NaN
AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, float.PositiveInfinity)); // Load factor is infinity
AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, float.NegativeInfinity)); // Load factor is infinity
}
[Theory]
[InlineData(0)]
[InlineData(10)]
[InlineData(100)]
[InlineData(1000)]
public void Ctor_Int_IEqualityComparer(int capacity)
{
RemoteInvoke((rcapacity) =>
{
int.TryParse(rcapacity, out int capacityint);
// Null comparer
var hash = new ComparableHashtable(capacityint, null);
VerifyHashtable(hash, null, null);
// Custom comparer
IEqualityComparer comparer = StringComparer.CurrentCulture;
hash = new ComparableHashtable(capacityint, comparer);
VerifyHashtable(hash, null, comparer);
return SuccessExitCode;
}, capacity.ToString()).Dispose();
}
[Fact]
public void Ctor_Int_IEqualityComparer_Invalid()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new Hashtable(-1, null)); // Capacity < 0
AssertExtensions.Throws<ArgumentException>("capacity", null, () => new Hashtable(int.MaxValue, null)); // Capacity / load factor > int.MaxValue
}
[Fact]
public void Ctor_IDictionary_Int_IEqualityComparer()
{
RemoteInvoke(() => {
// No exception
var hash1 = new ComparableHashtable(new Hashtable(), 1f, null);
Assert.Equal(0, hash1.Count);
hash1 = new ComparableHashtable(new Hashtable(new Hashtable(
new Hashtable(new Hashtable(new Hashtable(), 1f, null), 1f, null), 1f, null), 1f, null), 1f, null);
Assert.Equal(0, hash1.Count);
// Null comparer
Hashtable hash2 = Helpers.CreateIntHashtable(100);
hash1 = new ComparableHashtable(hash2, 1f, null);
VerifyHashtable(hash1, hash2, null);
hash2 = Helpers.CreateIntHashtable(100);
// Custom comparer
IEqualityComparer comparer = StringComparer.CurrentCulture;
hash1 = new ComparableHashtable(hash2, 1f, comparer);
VerifyHashtable(hash1, hash2, comparer);
return SuccessExitCode;
}).Dispose();
}
[Fact]
public void Ctor_IDictionary_LoadFactor_IEqualityComparer_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("d", () => new Hashtable(null, 1f, null)); // Dictionary is null
AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), 0.09f, null)); // Load factor < 0.1f
AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), 1.01f, null)); // Load factor > 1f
AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), float.NaN, null)); // Load factor is NaN
AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), float.PositiveInfinity, null)); // Load factor is infinity
AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), float.NegativeInfinity, null)); // Load factor is infinity
}
[Theory]
[InlineData(0, 0.1)]
[InlineData(10, 0.2)]
[InlineData(100, 0.3)]
[InlineData(1000, 1)]
public void Ctor_Int_Int_IEqualityComparer(int capacity, float loadFactor)
{
RemoteInvoke((rcapacity, rloadFactor) =>
{
int.TryParse(rcapacity, out int capacityint);
float.TryParse(rloadFactor, out float loadFactorFloat);
// Null comparer
var hash = new ComparableHashtable(capacityint, loadFactorFloat, null);
VerifyHashtable(hash, null, null);
Assert.Null(hash.EqualityComparer);
// Custom compare
IEqualityComparer comparer = StringComparer.CurrentCulture;
hash = new ComparableHashtable(capacityint, loadFactorFloat, comparer);
VerifyHashtable(hash, null, comparer);
return SuccessExitCode;
}, capacity.ToString(), loadFactor.ToString()).Dispose();
}
[Fact]
public void Ctor_Capacity_LoadFactor_IEqualityComparer_Invalid()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new Hashtable(-1, 1f, null)); // Capacity < 0
AssertExtensions.Throws<ArgumentException>("capacity", null, () => new Hashtable(int.MaxValue, 0.1f, null)); // Capacity / load factor > int.MaxValue
AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, 0.09f, null)); // Load factor < 0.1f
AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, 1.01f, null)); // Load factor > 1f
AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, float.NaN, null)); // Load factor is NaN
AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, float.PositiveInfinity, null)); // Load factor is infinity
AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, float.NegativeInfinity, null)); // Load factor is infinity
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")]
public void DebuggerAttribute()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(new Hashtable());
var hash = new Hashtable() { { "a", 1 }, { "b", 2 } };
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(hash);
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(Hashtable), Hashtable.Synchronized(hash));
bool threwNull = false;
try
{
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(Hashtable), null);
}
catch (TargetInvocationException ex)
{
threwNull = ex.InnerException is ArgumentNullException;
}
Assert.True(threwNull);
}
[Fact]
public void Add_ReferenceType()
{
var hash1 = new Hashtable();
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
// Value is a reference
var foo = new Foo();
hash2.Add("Key", foo);
Assert.Equal("Hello World", ((Foo)hash2["Key"]).StringValue);
// Changing original object should change the object stored in the Hashtable
foo.StringValue = "Goodbye";
Assert.Equal("Goodbye", ((Foo)hash2["Key"]).StringValue);
});
}
[Fact]
public void Add_ClearRepeatedly()
{
const int Iterations = 2;
const int Count = 2;
var hash = new Hashtable();
for (int i = 0; i < Iterations; i++)
{
for (int j = 0; j < Count; j++)
{
string key = "Key: i=" + i + ", j=" + j;
string value = "Value: i=" + i + ", j=" + j;
hash.Add(key, value);
}
Assert.Equal(Count, hash.Count);
hash.Clear();
}
}
[Fact]
[OuterLoop]
public void AddRemove_LargeAmountNumbers()
{
// Generate a random 100,000 array of ints as test data
var inputData = new int[100000];
var random = new Random(341553);
for (int i = 0; i < inputData.Length; i++)
{
inputData[i] = random.Next(7500000, int.MaxValue);
}
var hash = new Hashtable();
int count = 0;
foreach (long number in inputData)
{
hash.Add(number, count++);
}
count = 0;
foreach (long number in inputData)
{
Assert.Equal(hash[number], count);
Assert.True(hash.ContainsKey(number));
count++;
}
foreach (long number in inputData)
{
hash.Remove(number);
}
Assert.Equal(0, hash.Count);
}
[Fact]
public void DuplicatedKeysWithInitialCapacity()
{
// Make rehash get called because to many items with duplicated keys have been added to the hashtable
var hash = new Hashtable(200);
const int Iterations = 1600;
for (int i = 0; i < Iterations; i += 2)
{
hash.Add(new BadHashCode(i), i.ToString());
hash.Add(new BadHashCode(i + 1), (i + 1).ToString());
hash.Remove(new BadHashCode(i));
hash.Remove(new BadHashCode(i + 1));
}
for (int i = 0; i < Iterations; i++)
{
hash.Add(i.ToString(), i);
}
for (int i = 0; i < Iterations; i++)
{
Assert.Equal(i, hash[i.ToString()]);
}
}
[Fact]
public void DuplicatedKeysWithDefaultCapacity()
{
// Make rehash get called because to many items with duplicated keys have been added to the hashtable
var hash = new Hashtable();
const int Iterations = 1600;
for (int i = 0; i < Iterations; i += 2)
{
hash.Add(new BadHashCode(i), i.ToString());
hash.Add(new BadHashCode(i + 1), (i + 1).ToString());
hash.Remove(new BadHashCode(i));
hash.Remove(new BadHashCode(i + 1));
}
for (int i = 0; i < Iterations; i++)
{
hash.Add(i.ToString(), i);
}
for (int i = 0; i < Iterations; i++)
{
Assert.Equal(i, hash[i.ToString()]);
}
}
[Theory]
[InlineData(0)]
[InlineData(100)]
public void Clone(int count)
{
Hashtable hash1 = Helpers.CreateStringHashtable(count);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
Hashtable clone = (Hashtable)hash2.Clone();
Assert.Equal(hash2.Count, clone.Count);
Assert.Equal(hash2.IsSynchronized, clone.IsSynchronized);
Assert.Equal(hash2.IsFixedSize, clone.IsFixedSize);
Assert.Equal(hash2.IsReadOnly, clone.IsReadOnly);
for (int i = 0; i < clone.Count; i++)
{
string key = "Key_" + i;
string value = "Value_" + i;
Assert.True(clone.ContainsKey(key));
Assert.True(clone.ContainsValue(value));
Assert.Equal(value, clone[key]);
}
});
}
[Fact]
public void Clone_IsShallowCopy()
{
var hash = new Hashtable();
for (int i = 0; i < 10; i++)
{
hash.Add(i, new Foo());
}
Hashtable clone = (Hashtable)hash.Clone();
for (int i = 0; i < clone.Count; i++)
{
Assert.Equal("Hello World", ((Foo)clone[i]).StringValue);
Assert.Same(hash[i], clone[i]);
}
// Change object in original hashtable
((Foo)hash[1]).StringValue = "Goodbye";
Assert.Equal("Goodbye", ((Foo)clone[1]).StringValue);
// Removing an object from the original hashtable doesn't change the clone
hash.Remove(0);
Assert.True(clone.Contains(0));
}
[Fact]
public void Clone_HashtableCastedToInterfaces()
{
// Try to cast the returned object from Clone() to different types
Hashtable hash = Helpers.CreateIntHashtable(100);
ICollection collection = (ICollection)hash.Clone();
Assert.Equal(hash.Count, collection.Count);
IDictionary dictionary = (IDictionary)hash.Clone();
Assert.Equal(hash.Count, dictionary.Count);
}
[Fact]
public void ContainsKey()
{
Hashtable hash1 = Helpers.CreateStringHashtable(100);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
for (int i = 0; i < hash2.Count; i++)
{
string key = "Key_" + i;
Assert.True(hash2.ContainsKey(key));
Assert.True(hash2.Contains(key));
}
Assert.False(hash2.ContainsKey("Non Existent Key"));
Assert.False(hash2.Contains("Non Existent Key"));
Assert.False(hash2.ContainsKey(101));
Assert.False(hash2.Contains("Non Existent Key"));
string removedKey = "Key_1";
hash2.Remove(removedKey);
Assert.False(hash2.ContainsKey(removedKey));
Assert.False(hash2.Contains(removedKey));
});
}
[Fact]
public void ContainsKey_EqualObjects()
{
var hash1 = new Hashtable();
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
var foo1 = new Foo() { StringValue = "Goodbye" };
var foo2 = new Foo() { StringValue = "Goodbye" };
hash2.Add(foo1, 101);
Assert.True(hash2.ContainsKey(foo2));
Assert.True(hash2.Contains(foo2));
int i1 = 0x10;
int i2 = 0x100;
long l1 = (((long)i1) << 32) + i2; // Create two longs with same hashcode
long l2 = (((long)i2) << 32) + i1;
hash2.Add(l1, 101);
hash2.Add(l2, 101); // This will cause collision bit of the first entry to be set
Assert.True(hash2.ContainsKey(l1));
Assert.True(hash2.Contains(l1));
hash2.Remove(l1); // Remove the first item
Assert.False(hash2.ContainsKey(l1));
Assert.False(hash2.Contains(l1));
Assert.True(hash2.ContainsKey(l2));
Assert.True(hash2.Contains(l2));
});
}
[Fact]
public void ContainsKey_NullKey_ThrowsArgumentNullException()
{
var hash1 = new Hashtable();
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
AssertExtensions.Throws<ArgumentNullException>("key", () => hash2.ContainsKey(null)); // Key is null
AssertExtensions.Throws<ArgumentNullException>("key", () => hash2.Contains(null)); // Key is null
});
}
[Fact]
public void ContainsValue()
{
Hashtable hash1 = Helpers.CreateStringHashtable(100);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
for (int i = 0; i < hash2.Count; i++)
{
string value = "Value_" + i;
Assert.True(hash2.ContainsValue(value));
}
Assert.False(hash2.ContainsValue("Non Existent Value"));
Assert.False(hash2.ContainsValue(101));
Assert.False(hash2.ContainsValue(null));
hash2.Add("Key_101", null);
Assert.True(hash2.ContainsValue(null));
string removedKey = "Key_1";
string removedValue = "Value_1";
hash2.Remove(removedKey);
Assert.False(hash2.ContainsValue(removedValue));
});
}
[Fact]
public void ContainsValue_EqualObjects()
{
var hash1 = new Hashtable();
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
var foo1 = new Foo() { StringValue = "Goodbye" };
var foo2 = new Foo() { StringValue = "Goodbye" };
hash2.Add(101, foo1);
Assert.True(hash2.ContainsValue(foo2));
});
}
[Fact]
public void Keys_ModifyingHashtable_ModifiesCollection()
{
Hashtable hash = Helpers.CreateStringHashtable(100);
ICollection keys = hash.Keys;
// Removing a key from the hashtable should update the Keys ICollection.
// This means that the Keys ICollection no longer contains the key.
hash.Remove("Key_0");
IEnumerator enumerator = keys.GetEnumerator();
while (enumerator.MoveNext())
{
Assert.NotEqual("Key_0", enumerator.Current);
}
}
[Fact]
public void Remove_SameHashcode()
{
// We want to add and delete items (with the same hashcode) to the hashtable in such a way that the hashtable
// does not expand but have to tread through collision bit set positions to insert the new elements. We do this
// by creating a default hashtable of size 11 (with the default load factor of 0.72), this should mean that
// the hashtable does not expand as long as we have at most 7 elements at any given time?
var hash = new Hashtable();
var arrList = new ArrayList();
for (int i = 0; i < 7; i++)
{
var hashConfuse = new BadHashCode(i);
arrList.Add(hashConfuse);
hash.Add(hashConfuse, i);
}
var rand = new Random(-55);
int iCount = 7;
for (int i = 0; i < 100; i++)
{
for (int j = 0; j < 7; j++)
{
Assert.Equal(hash[arrList[j]], ((BadHashCode)arrList[j]).Value);
}
// Delete 3 elements from the hashtable
for (int j = 0; j < 3; j++)
{
int iElement = rand.Next(6);
hash.Remove(arrList[iElement]);
Assert.False(hash.ContainsValue(null));
arrList.RemoveAt(iElement);
int testInt = iCount++;
var hashConfuse = new BadHashCode(testInt);
arrList.Add(hashConfuse);
hash.Add(hashConfuse, testInt);
}
}
}
[Fact]
public void SynchronizedProperties()
{
// Ensure Synchronized correctly reflects a wrapped hashtable
var hash1 = Helpers.CreateStringHashtable(100);
var hash2 = Hashtable.Synchronized(hash1);
Assert.Equal(hash1.Count, hash2.Count);
Assert.Equal(hash1.IsReadOnly, hash2.IsReadOnly);
Assert.Equal(hash1.IsFixedSize, hash2.IsFixedSize);
Assert.True(hash2.IsSynchronized);
Assert.Equal(hash1.SyncRoot, hash2.SyncRoot);
for (int i = 0; i < hash2.Count; i++)
{
Assert.Equal("Value_" + i, hash2["Key_" + i]);
}
}
[Fact]
public void Synchronized_NullTable_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("table", () => Hashtable.Synchronized(null)); // Table is null
}
[Fact]
public void Values_ModifyingHashtable_ModifiesCollection()
{
Hashtable hash = Helpers.CreateStringHashtable(100);
ICollection values = hash.Values;
// Removing a value from the hashtable should update the Values ICollection.
// This means that the Values ICollection no longer contains the value.
hash.Remove("Key_0");
IEnumerator enumerator = values.GetEnumerator();
while (enumerator.MoveNext())
{
Assert.NotEqual("Value_0", enumerator.Current);
}
}
[Fact]
public void HashCodeProvider_Set_ImpactsSearch()
{
var hash = new ComparableHashtable(CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase);
hash.Add("test", "test");
// Should be able to find with the same and different casing
Assert.True(hash.ContainsKey("test"));
Assert.True(hash.ContainsKey("TEST"));
// Changing the hash code provider, we shouldn't be able to find either
hash.HashCodeProvider = new FixedHashCodeProvider
{
FixedHashCode = CaseInsensitiveHashCodeProvider.DefaultInvariant.GetHashCode("test") + 1
};
Assert.False(hash.ContainsKey("test"));
Assert.False(hash.ContainsKey("TEST"));
// Changing it back, should be able to find both again
hash.HashCodeProvider = CaseInsensitiveHashCodeProvider.DefaultInvariant;
Assert.True(hash.ContainsKey("test"));
Assert.True(hash.ContainsKey("TEST"));
}
[Fact]
public void HashCodeProvider_Comparer_CompatibleGetSet_Success()
{
var hash = new ComparableHashtable();
Assert.Null(hash.HashCodeProvider);
Assert.Null(hash.Comparer);
hash = new ComparableHashtable();
hash.HashCodeProvider = null;
hash.Comparer = null;
hash = new ComparableHashtable();
hash.Comparer = null;
hash.HashCodeProvider = null;
hash.HashCodeProvider = CaseInsensitiveHashCodeProvider.DefaultInvariant;
hash.Comparer = StringComparer.OrdinalIgnoreCase;
}
[Fact]
public void HashCodeProvider_Comparer_IncompatibleGetSet_Throws()
{
var hash = new ComparableHashtable(StringComparer.CurrentCulture);
AssertExtensions.Throws<ArgumentException>(null, () => hash.HashCodeProvider);
AssertExtensions.Throws<ArgumentException>(null, () => hash.Comparer);
AssertExtensions.Throws<ArgumentException>(null, () => hash.HashCodeProvider = CaseInsensitiveHashCodeProvider.DefaultInvariant);
AssertExtensions.Throws<ArgumentException>(null, () => hash.Comparer = StringComparer.OrdinalIgnoreCase);
}
[Fact]
public void Comparer_Set_ImpactsSearch()
{
var hash = new ComparableHashtable(CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase);
hash.Add("test", "test");
// Should be able to find with the same and different casing
Assert.True(hash.ContainsKey("test"));
Assert.True(hash.ContainsKey("TEST"));
// Changing the comparer, should only be able to find the matching case
hash.Comparer = StringComparer.Ordinal;
Assert.True(hash.ContainsKey("test"));
Assert.False(hash.ContainsKey("TEST"));
// Changing it back, should be able to find both again
hash.Comparer = StringComparer.OrdinalIgnoreCase;
Assert.True(hash.ContainsKey("test"));
Assert.True(hash.ContainsKey("TEST"));
}
private class FixedHashCodeProvider : IHashCodeProvider
{
public int FixedHashCode;
public int GetHashCode(object obj) => FixedHashCode;
}
private static void VerifyHashtable(ComparableHashtable hash1, Hashtable hash2, IEqualityComparer ikc)
{
if (hash2 == null)
{
Assert.Equal(0, hash1.Count);
}
else
{
// Make sure that construtor imports all keys and values
Assert.Equal(hash2.Count, hash1.Count);
for (int i = 0; i < 100; i++)
{
Assert.True(hash1.ContainsKey(i));
Assert.True(hash1.ContainsValue(i));
}
// Make sure the new and old hashtables are not linked
hash2.Clear();
for (int i = 0; i < 100; i++)
{
Assert.True(hash1.ContainsKey(i));
Assert.True(hash1.ContainsValue(i));
}
}
Assert.Equal(ikc, hash1.EqualityComparer);
Assert.False(hash1.IsFixedSize);
Assert.False(hash1.IsReadOnly);
Assert.False(hash1.IsSynchronized);
// Make sure we can add to the hashtable
int count = hash1.Count;
for (int i = count; i < count + 100; i++)
{
hash1.Add(i, i);
Assert.True(hash1.ContainsKey(i));
Assert.True(hash1.ContainsValue(i));
}
}
private class ComparableHashtable : Hashtable
{
public ComparableHashtable() : base() { }
public ComparableHashtable(int capacity) : base(capacity) { }
public ComparableHashtable(int capacity, float loadFactor) : base(capacity, loadFactor) { }
public ComparableHashtable(int capacity, IHashCodeProvider hcp, IComparer comparer) : base(capacity, hcp, comparer) { }
public ComparableHashtable(int capacity, IEqualityComparer ikc) : base(capacity, ikc) { }
public ComparableHashtable(IHashCodeProvider hcp, IComparer comparer) : base(hcp, comparer) { }
public ComparableHashtable(IEqualityComparer ikc) : base(ikc) { }
public ComparableHashtable(IDictionary d) : base(d) { }
public ComparableHashtable(IDictionary d, float loadFactor) : base(d, loadFactor) { }
public ComparableHashtable(IDictionary d, IHashCodeProvider hcp, IComparer comparer) : base(d, hcp, comparer) { }
public ComparableHashtable(IDictionary d, IEqualityComparer ikc) : base(d, ikc) { }
public ComparableHashtable(IDictionary d, float loadFactor, IHashCodeProvider hcp, IComparer comparer) : base(d, loadFactor, hcp, comparer) { }
public ComparableHashtable(IDictionary d, float loadFactor, IEqualityComparer ikc) : base(d, loadFactor, ikc) { }
public ComparableHashtable(int capacity, float loadFactor, IHashCodeProvider hcp, IComparer comparer) : base(capacity, loadFactor, hcp, comparer) { }
public ComparableHashtable(int capacity, float loadFactor, IEqualityComparer ikc) : base(capacity, loadFactor, ikc) { }
public new IEqualityComparer EqualityComparer => base.EqualityComparer;
public IHashCodeProvider HashCodeProvider { get { return hcp; } set { hcp = value; } }
public IComparer Comparer { get { return comparer; } set { comparer = value; } }
}
private class BadHashCode
{
public BadHashCode(int value)
{
Value = value;
}
public int Value { get; private set; }
public override bool Equals(object o)
{
BadHashCode rhValue = o as BadHashCode;
if (rhValue != null)
{
return Value.Equals(rhValue.Value);
}
else
{
throw new ArgumentException("is not BadHashCode type actual " + o.GetType(), nameof(o));
}
}
// Return 0 for everything to force hash collisions.
public override int GetHashCode() => 0;
public override string ToString() => Value.ToString();
}
private class Foo
{
public string StringValue { get; set; } = "Hello World";
public override bool Equals(object obj)
{
Foo foo = obj as Foo;
return foo != null && StringValue == foo.StringValue;
}
public override int GetHashCode() => StringValue.GetHashCode();
}
}
/// <summary>
/// A hashtable can have a race condition:
/// A read operation on hashtable has three steps:
/// (1) calculate the hash and find the slot number.
/// (2) compare the hashcode, if equal, go to step 3. Otherwise end.
/// (3) compare the key, if equal, go to step 4. Otherwise end.
/// (4) return the value contained in the bucket.
/// The problem is that after step 3 and before step 4. A writer can kick in a remove the old item and add a new one
/// in the same bucket. In order to make this happen easily, I created two long with same hashcode.
/// </summary>
public class Hashtable_ItemThreadSafetyTests
{
private object _key1;
private object _key2;
private object _value1 = "value1";
private object _value2 = "value2";
private Hashtable _hash;
private bool _errorOccurred = false;
private bool _timeExpired = false;
private const int MAX_TEST_TIME_MS = 10000; // 10 seconds
[Fact]
[OuterLoop]
public void GetItem_ThreadSafety()
{
int i1 = 0x10;
int i2 = 0x100;
// Setup key1 and key2 so they are different values but have the same hashcode
// To produce a hashcode long XOR's the first 32bits with the last 32 bits
long l1 = (((long)i1) << 32) + i2;
long l2 = (((long)i2) << 32) + i1;
_key1 = l1;
_key2 = l2;
_hash = new Hashtable(3); // Just one item will be in the hashtable at a time
int taskCount = 3;
var readers1 = new Task[taskCount];
var readers2 = new Task[taskCount];
Stopwatch stopwatch = Stopwatch.StartNew();
for (int i = 0; i < readers1.Length; i++)
{
readers1[i] = Task.Run(new Action(ReaderFunction1));
}
for (int i = 0; i < readers2.Length; i++)
{
readers2[i] = Task.Run(new Action(ReaderFunction2));
}
Task writer = Task.Run(new Action(WriterFunction));
var spin = new SpinWait();
while (!_errorOccurred && !_timeExpired)
{
if (MAX_TEST_TIME_MS < stopwatch.ElapsedMilliseconds)
{
_timeExpired = true;
}
spin.SpinOnce();
}
Task.WaitAll(readers1);
Task.WaitAll(readers2);
writer.Wait();
Assert.False(_errorOccurred);
}
private void ReaderFunction1()
{
while (!_timeExpired)
{
object value = _hash[_key1];
if (value != null)
{
Assert.NotEqual(value, _value2);
}
}
}
private void ReaderFunction2()
{
while (!_errorOccurred && !_timeExpired)
{
object value = _hash[_key2];
if (value != null)
{
Assert.NotEqual(value, _value1);
}
}
}
private void WriterFunction()
{
while (!_errorOccurred && !_timeExpired)
{
_hash.Add(_key1, _value1);
_hash.Remove(_key1);
_hash.Add(_key2, _value2);
_hash.Remove(_key2);
}
}
}
public class Hashtable_SynchronizedTests
{
private Hashtable _hash2;
private int _iNumberOfElements = 20;
[Fact]
[OuterLoop]
public void SynchronizedThreadSafety()
{
const int NumberOfWorkers = 3;
// Synchronized returns a hashtable that is thread safe
// We will try to test this by getting a number of threads to write some items
// to a synchronized IList
var hash1 = new Hashtable();
_hash2 = Hashtable.Synchronized(hash1);
var workers = new Task[NumberOfWorkers];
for (int i = 0; i < workers.Length; i++)
{
var name = "Thread worker " + i;
var task = new Action(() => AddElements(name));
workers[i] = Task.Run(task);
}
Task.WaitAll(workers);
// Check time
Assert.Equal(_hash2.Count, _iNumberOfElements * NumberOfWorkers);
for (int i = 0; i < NumberOfWorkers; i++)
{
for (int j = 0; j < _iNumberOfElements; j++)
{
string strValue = "Thread worker " + i + "_" + j;
Assert.True(_hash2.Contains(strValue));
}
}
// We cannot can make an assumption on the order of these items but
// now we are going to remove all of these
workers = new Task[NumberOfWorkers];
for (int i = 0; i < workers.Length; i++)
{
string name = "Thread worker " + i;
var task = new Action(() => RemoveElements(name));
workers[i] = Task.Run(task);
}
Task.WaitAll(workers);
Assert.Equal(_hash2.Count, 0);
}
private void AddElements(string strName)
{
for (int i = 0; i < _iNumberOfElements; i++)
{
_hash2.Add(strName + "_" + i, "string_" + i);
}
}
private void RemoveElements(string strName)
{
for (int i = 0; i < _iNumberOfElements; i++)
{
_hash2.Remove(strName + "_" + i);
}
}
}
public class Hashtable_SyncRootTests
{
private Hashtable _hashDaughter;
private Hashtable _hashGrandDaughter;
private const int NumberOfElements = 100;
[Fact]
public void SyncRoot()
{
// Different hashtables have different SyncRoots
var hash1 = new Hashtable();
var hash2 = new Hashtable();
Assert.NotEqual(hash1.SyncRoot, hash2.SyncRoot);
Assert.Equal(hash1.SyncRoot.GetType(), typeof(object));
// Cloned hashtables have different SyncRoots
hash1 = new Hashtable();
hash2 = Hashtable.Synchronized(hash1);
Hashtable hash3 = (Hashtable)hash2.Clone();
Assert.NotEqual(hash2.SyncRoot, hash3.SyncRoot);
Assert.NotEqual(hash1.SyncRoot, hash3.SyncRoot);
// Testing SyncRoot is not as simple as its implementation looks like. This is the working
// scenario we have in mind.
// 1) Create your Down to earth mother Hashtable
// 2) Get a synchronized wrapper from it
// 3) Get a Synchronized wrapper from 2)
// 4) Get a synchronized wrapper of the mother from 1)
// 5) all of these should SyncRoot to the mother earth
var hashMother = new Hashtable();
for (int i = 0; i < NumberOfElements; i++)
{
hashMother.Add("Key_" + i, "Value_" + i);
}
Hashtable hashSon = Hashtable.Synchronized(hashMother);
_hashGrandDaughter = Hashtable.Synchronized(hashSon);
_hashDaughter = Hashtable.Synchronized(hashMother);
Assert.Equal(hashSon.SyncRoot, hashMother.SyncRoot);
Assert.Equal(hashSon.SyncRoot, hashMother.SyncRoot);
Assert.Equal(_hashGrandDaughter.SyncRoot, hashMother.SyncRoot);
Assert.Equal(_hashDaughter.SyncRoot, hashMother.SyncRoot);
Assert.Equal(hashSon.SyncRoot, hashMother.SyncRoot);
// We are going to rumble with the Hashtables with some threads
int iNumberOfWorkers = 30;
var workers = new Task[iNumberOfWorkers];
var ts2 = new Action(RemoveElements);
for (int iThreads = 0; iThreads < iNumberOfWorkers; iThreads += 2)
{
var name = "Thread_worker_" + iThreads;
var ts1 = new Action(() => AddMoreElements(name));
workers[iThreads] = Task.Run(ts1);
workers[iThreads + 1] = Task.Run(ts2);
}
Task.WaitAll(workers);
// Check:
// Either there should be some elements (the new ones we added and/or the original ones) or none
var hshPossibleValues = new Hashtable();
for (int i = 0; i < NumberOfElements; i++)
{
hshPossibleValues.Add("Key_" + i, "Value_" + i);
}
for (int i = 0; i < iNumberOfWorkers; i++)
{
hshPossibleValues.Add("Key_Thread_worker_" + i, "Thread_worker_" + i);
}
IDictionaryEnumerator idic = hashMother.GetEnumerator();
while (idic.MoveNext())
{
Assert.True(hshPossibleValues.ContainsKey(idic.Key));
Assert.True(hshPossibleValues.ContainsValue(idic.Value));
}
}
private void AddMoreElements(string threadName)
{
_hashGrandDaughter.Add("Key_" + threadName, threadName);
}
private void RemoveElements()
{
_hashDaughter.Clear();
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="DataRowComparer.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">spather</owner>
//------------------------------------------------------------------------------
using System;
using System.Data;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Data.DataSetExtensions;
namespace System.Data
{
/// <summary>
/// This class implements IEqualityComparer using value based semantics
/// when comparing DataRows.
/// </summary>
public static class DataRowComparer
{
/// <summary>
/// Gets the singleton instance of the data row comparer.
/// </summary>
public static DataRowComparer<DataRow> Default { get { return DataRowComparer<DataRow>.Default; } }
internal static bool AreEqual(object a, object b)
{
if (Object.ReferenceEquals(a, b))
{ // same reference or (null, null) or (DBNull.Value, DBNull.Value)
return true;
}
if (Object.ReferenceEquals(a, null) || Object.ReferenceEquals(a, DBNull.Value) ||
Object.ReferenceEquals(b, null) || Object.ReferenceEquals(b, DBNull.Value))
{ // (null, non-null) or (null, DBNull.Value) or vice versa
return false;
}
return (a.Equals(b) || (a.GetType().IsArray && CompareArray((Array)a, b as Array)));
}
private static bool AreElementEqual(object a, object b)
{
if (Object.ReferenceEquals(a, b))
{ // same reference or (null, null) or (DBNull.Value, DBNull.Value)
return true;
}
if (Object.ReferenceEquals(a, null) || Object.ReferenceEquals(a, DBNull.Value) ||
Object.ReferenceEquals(b, null) || Object.ReferenceEquals(b, DBNull.Value))
{ // (null, non-null) or (null, DBNull.Value) or vice versa
return false;
}
return a.Equals(b);
}
private static bool CompareArray(Array a, Array b)
{
if ((null == b) ||
(1 != a.Rank) ||
(1 != b.Rank) ||
(a.Length != b.Length))
{ // automatically consider array's with Rank>1 not-equal
return false;
}
int index1 = a.GetLowerBound(0);
int index2 = b.GetLowerBound(0);
if (a.GetType() == b.GetType() && (0 == index1) && (0 == index2))
{
switch (Type.GetTypeCode(a.GetType().GetElementType()))
{
case TypeCode.Byte:
return DataRowComparer.CompareEquatableArray<Byte>((Byte[])a, (Byte[])b);
case TypeCode.Int16:
return DataRowComparer.CompareEquatableArray<Int16>((Int16[])a, (Int16[])b);
case TypeCode.Int32:
return DataRowComparer.CompareEquatableArray<Int32>((Int32[])a, (Int32[])b);
case TypeCode.Int64:
return DataRowComparer.CompareEquatableArray<Int64>((Int64[])a, (Int64[])b);
case TypeCode.String:
return DataRowComparer.CompareEquatableArray<String>((String[])a, (String[])b);
}
}
//Compare every element. But don't recurse if we have Array of array.
int length = index1 + a.Length;
for (; index1 < length; ++index1, ++index2)
{
if (!AreElementEqual(a.GetValue(index1), b.GetValue(index2)))
{
return false;
}
}
return true;
}
private static bool CompareEquatableArray<TElem>(TElem[] a, TElem[] b) where TElem : IEquatable<TElem>
{
if (Object.ReferenceEquals(a, b))
{
return true;
}
if (Object.ReferenceEquals(a, null) ||
Object.ReferenceEquals(b, null))
{
return false;
}
if (a.Length != b.Length)
{
return false;
}
for (int i = 0; i < a.Length; ++i)
{
if (!a[i].Equals(b[i]))
{
return false;
}
}
return true;
}
}
/// <summary>
/// This class implements IEqualityComparer using value based semantics
/// when comparing DataRows.
/// </summary>
public sealed class DataRowComparer<TRow> : IEqualityComparer<TRow> where TRow : DataRow
{
/// <summary>
/// Private constructor to prevent initialization outside of Default singleton instance.
/// </summary>
private DataRowComparer() { }
private static DataRowComparer<TRow> _instance = new DataRowComparer<TRow>();
/// <summary>
/// Gets the singleton instance of the data row comparer.
/// </summary>
public static DataRowComparer<TRow> Default { get { return _instance; } }
/// <summary>
/// This method compares to DataRows by doing a column by column value based
/// comparision.
/// </summary>
/// <param name="leftRow">
/// The first input DataRow
/// </param>
/// <param name="rightRow">
/// The second input DataRow
/// </param>
/// <returns>
/// True if rows are equal, false if not.
/// </returns>
public bool Equals(TRow leftRow, TRow rightRow)
{
if (Object.ReferenceEquals(leftRow, rightRow))
{
return true;
}
if (Object.ReferenceEquals(leftRow, null) ||
Object.ReferenceEquals(rightRow, null))
{
return false;
}
if (leftRow.RowState == DataRowState.Deleted || rightRow.RowState == DataRowState.Deleted)
{
throw DataSetUtil.InvalidOperation(Strings.DataSetLinq_CannotCompareDeletedRow);
}
int count = leftRow.Table.Columns.Count;
if (count != rightRow.Table.Columns.Count)
{
return false;
}
for (int i = 0; i < count; ++i)
{
if (!DataRowComparer.AreEqual(leftRow[i], rightRow[i]))
{
return false;
}
}
return true;
}
/// <summary>
/// This mtheod retrieves a hash code for the source row.
/// </summary>
/// <param name="row">
/// The source DataRow
/// </param>
/// <returns>
/// HashCode for row based on values in the row.
/// </returns>
public int GetHashCode(TRow row)
{
DataSetUtil.CheckArgumentNull(row, "row");
if (row.RowState == DataRowState.Deleted)
{
throw DataSetUtil.InvalidOperation(Strings.DataSetLinq_CannotCompareDeletedRow);
}
int hash = 0;
Debug.Assert(row.Table != null);
if (row.Table.Columns.Count > 0)
{
// if the row has at least one column, then use the first column value
object value = row[0];
Type valueType = value.GetType();
if (valueType.IsArray)
{
Array array = value as Array;
if (array.Rank > 1)
{
hash = value.GetHashCode();
}
else if (array.Length > 0)
{
hash = array.GetValue(array.GetLowerBound(0)).GetHashCode();
}
}
else
{
System.ValueType vt = value as System.ValueType;
// have to unbox value types.
if (vt != null)
{
hash = vt.GetHashCode();
}
else
{
hash = value.GetHashCode();
}
}
}
// if table has no columns, the hash code is 0
return hash;
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Diagnostics;
using System.Globalization;
using System.Threading;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.CoreServices.Settings;
using OpenLiveWriter.Interop.Windows;
namespace OpenLiveWriter.ApplicationFramework.Preferences
{
/// <summary>
/// Preferences base class.
/// </summary>
public abstract class Preferences
{
#region Static & Constant Declarations
#endregion Static & Constant Declarations
#region Private Member Variables
/// <summary>
/// The settings persister helper.
/// </summary>
private SettingsPersisterHelper settingsPersisterHelper;
/// <summary>
/// A value that indicates that the Preferences object has been modified since being
/// loaded.
/// </summary>
private bool modified;
/// <summary>
/// Handle to underlying registry key used by these prefs (we need this in order
/// to register for change notifications)
/// </summary>
private UIntPtr hPrefsKey = UIntPtr.Zero;
/// <summary>
/// Win32 event that is signalled whenever our prefs key is changed
/// </summary>
private ManualResetEvent settingsChangedEvent = null;
/// <summary>
/// State variable that indicates we have disabled change monitoring
/// (normally because a very unexpected error has occurred during change
/// monitoring initialization)
/// </summary>
private bool changeMonitoringDisabled = false;
#endregion Private Member Variables
#region Public Events
/// <summary>
/// Occurs when one or more preferences in the Preferences class have been modified.
/// </summary>
public event EventHandler PreferencesModified;
/// <summary>
/// Occurs when one or more preferences in the Preferences class have changed.
/// </summary>
public event EventHandler PreferencesChanged;
#endregion
#region Class Initialization & Termination
/// <summary>
/// Initialize preferences
/// </summary>
/// <param name="subKey">sub key name</param>
public Preferences(string subKey) : this(subKey, false)
{
}
/// <summary>
/// Initializes a new instance of the Preferences class (optionally enable change monitoring)
/// </summary>
/// <param name="subKey">sub-key name</param>
/// <param name="monitorChanges">specifies whether the creator intendes to monitor
/// this prefs object for changes by calling the CheckForChanges method</param>
public Preferences(string subKey, bool monitorChanges)
{
// Instantiate the settings persister helper object.
settingsPersisterHelper = ApplicationEnvironment.PreferencesSettingsRoot.GetSubSettings(subKey);
// Load preferences
LoadPreferences() ;
// Monitor changes, if requested.
if (monitorChanges)
ConfigureChangeMonitoring(subKey);
}
#endregion Class Initialization & Termination
#region Public Methods
/// <summary>
/// Check for changes to the preferences
/// </summary>
/// <returns>true if there were changes; otherwise, false.</returns>
public bool CheckForChanges()
{
return ReloadPreferencesIfNecessary();
}
/// <summary>
/// Returns a value that indicates that the Preferences object has been modified since
/// being loaded.
/// </summary>
public bool IsModified()
{
return modified;
}
/// <summary>
/// Saves preferences.
/// </summary>
public void Save()
{
if (modified)
{
SavePreferences();
modified = false;
}
}
#endregion Public Methods
#region Protected Methods
/// <summary>
/// Loads preferences. This method is overridden in derived classes to load the
/// preferences of the class.
/// </summary>
protected abstract void LoadPreferences();
/// <summary>
/// Saves preferences. This method is overridden in derived classes to save the
/// preferences of the class.
/// </summary>
protected abstract void SavePreferences();
/// <summary>
/// Sets a value that indicates that the Preferences object has been modified since being
/// loaded.
/// </summary>
protected void Modified()
{
modified = true;
OnPreferencesModified(EventArgs.Empty);
}
#endregion Protected Methods
#region Protected Properties
/// <summary>
/// Gets the SettingsPersisterHelper for this Preferences object.
/// </summary>
protected SettingsPersisterHelper SettingsPersisterHelper
{
get
{
return settingsPersisterHelper;
}
}
#endregion Protected Properties
#region Protected Events
/// <summary>
/// Raises the PreferencesModified event.
/// </summary>
/// <param name="e">An EventArgs that contains the event data.</param>
protected virtual void OnPreferencesModified(EventArgs e)
{
if (PreferencesModified != null)
PreferencesModified(this, e);
}
/// <summary>
/// Raises the Changed event.
/// </summary>
/// <param name="e">An EventArgs that contains the event data.</param>
protected virtual void OnPreferencesChanged(EventArgs e)
{
if (PreferencesChanged != null)
PreferencesChanged(this, e);
}
#endregion Protected Events
#region Private Methods
/// <summary>
/// Configure change monitoring for this prefs object
/// </summary>
/// <param name="subKey"></param>
private void ConfigureChangeMonitoring(string subKey)
{
// assert preconditions
Debug.Assert( hPrefsKey == UIntPtr.Zero ) ;
Debug.Assert( settingsChangedEvent == null ) ;
try
{
// open handle to registry key
int result = Advapi32.RegOpenKeyEx(
HKEY.CURRENT_USER,
String.Format( CultureInfo.InvariantCulture, @"{0}\{1}\{2}", ApplicationEnvironment.SettingsRootKeyName, ApplicationConstants.PREFERENCES_SUB_KEY, subKey),
0, KEY.READ, out hPrefsKey ) ;
if ( result != ERROR.SUCCESS )
{
Trace.Fail("Failed to open registry key") ;
changeMonitoringDisabled = true ;
return ;
}
// create settings changed event
settingsChangedEvent = new ManualResetEvent(false) ;
// start monitoring changes
MonitorChanges() ;
}
catch( Exception e )
{
// Just being super-paranoid here because this code is likely be called during
// application initialization -- if ANY type of error occurs then we disable
// change monitoring for the life of this object
Trace.WriteLine( "Unexpected error occurred during change monitor configuration: " + e.Message + "\r\n" + e.StackTrace ) ;
changeMonitoringDisabled = true ;
}
}
/// <summary>
/// Monitor changes in the registry key for this prefs object
/// </summary>
private void MonitorChanges()
{
// reset the settings changed event so it will not be signaled until
// a change is made to the specified key
settingsChangedEvent.Reset();
// request that the event be signaled when the registry key changes
int result = Advapi32.RegNotifyChangeKeyValue( hPrefsKey, false, REG_NOTIFY_CHANGE.LAST_SET, settingsChangedEvent.SafeWaitHandle, true);
if (result != ERROR.SUCCESS)
{
Trace.WriteLine("Unexpeced failure to monitor reg key (Error code: " + result.ToString(CultureInfo.InvariantCulture));
changeMonitoringDisabled = true;
}
}
/// <summary>
/// Load changes to preferences if they have changed since our last check
/// </summary>
/// <returns>true if preferences were reloaded; otherwise, false.</returns>
private bool ReloadPreferencesIfNecessary()
{
// If change monitoring is disabled, then just return.
if (changeMonitoringDisabled)
return false;
// Verify this instance is configured to monitor changes.
if (settingsChangedEvent == null)
{
Debug.Fail("Must initialize preferences object with monitorChanges flag set to true in order to call CheckForChanges");
return false;
}
// check to see whether any changes have occurred
try
{
// if the settings changed event is signaled then reload preferences
if (settingsChangedEvent.WaitOne(0, false))
{
// Reload.
LoadPreferences();
// Monitor subsequent changes.
MonitorChanges();
// Raise the PreferencesChanged event.
OnPreferencesChanged(EventArgs.Empty);
// Changes were loaded.
return true;
}
}
catch (Exception e)
{
// Just being super-paranoid here because this code is called from a timer
// in the UI thread -- if ANY type of error occurs during change monitoring
// then we disable change monitoring for the life of this object
Trace.WriteLine("Unexpected error occurred during check for changes: "+e.Message+"\r\n"+e.StackTrace);
changeMonitoringDisabled = true;
return false;
}
// Not loaded!
return false;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using Swift.Net.WebAPI.Areas.HelpPage.ModelDescriptions;
using Swift.Net.WebAPI.Areas.HelpPage.Models;
namespace Swift.Net.WebAPI.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Windows.Forms;
using Bloom.Collection;
using Bloom.CollectionCreating;
using Bloom.Properties;
//using Chorus.UI.Clone;
using SIL.Windows.Forms.Extensions;
using SIL.i18n;
using System.Linq;
using Bloom.Workspace;
using SIL.IO;
namespace Bloom.CollectionChoosing
{
public partial class OpenCreateCloneControl : UserControl
{
private MostRecentPathsList _mruList;
private Func<string> _createNewLibraryAndReturnPath;
private string _filterString;
public event EventHandler DoneChoosingOrCreatingLibrary;
public string SelectedPath { get; private set; }
public OpenCreateCloneControl()
{
Font = SystemFonts.MessageBoxFont; //use the default OS UI font
InitializeComponent();
SetupUiLanguageMenu();
}
private void SetupUiLanguageMenu()
{
_toolStrip1.Renderer = new Workspace.NoBorderToolStripRenderer();
WorkspaceView.SetupUiLanguageMenuCommon(_uiLanguageMenu);
}
public void Init(MostRecentPathsList mruList,
string filterString,
Func<string> createNewLibraryAndReturnPath)
{
_filterString = filterString;
_createNewLibraryAndReturnPath = createNewLibraryAndReturnPath;
_mruList = mruList;
}
/// <summary>
/// Client should use this, at least, to set the icon (the image) for mru items
/// </summary>
public Button TemplateButton
{
get { return _templateButton; }
}
private void OnLoad(object sender, EventArgs e)
{
if (this.DesignModeAtAll())
{
return;
}
_templateButton.Parent.Controls.Remove(_templateButton);
const int maxMruItems = 3;
var collectionsToShow = _mruList.Paths.Take(maxMruItems).ToList();
if (collectionsToShow.Count() < maxMruItems && Directory.Exists(NewCollectionWizard.DefaultParentDirectoryForCollections))
{
collectionsToShow.AddRange(Directory.GetDirectories(NewCollectionWizard.DefaultParentDirectoryForCollections)
.Select(d => Path.Combine(d, Path.ChangeExtension(Path.GetFileName(d),"bloomCollection")))
.Where(c => RobustFile.Exists(c) && !collectionsToShow.Contains(c))
.OrderBy(c => Directory.GetLastWriteTime(Path.GetDirectoryName(c)))
.Reverse()
.Take(maxMruItems - collectionsToShow.Count()));
}
var count = 0;
foreach (var path in collectionsToShow)
{
AddFileChoice(path, count);
++count;
if (count > maxMruItems)
break;
}
foreach (Control control in tableLayoutPanel2.Controls)
{
if (control.Tag != null && control.Tag.ToString() == "sendreceive")
control.Visible = Settings.Default.ShowSendReceive;
}
// We've pulled _sendReceiveInstructionsLabel out into _topRightPanel; set visibility in the same way
_sendReceiveInstructionsLabel.Visible = Settings.Default.ShowSendReceive;
}
private void AddFileChoice(string path, int index)
{
const int kRowOffsetForMRUChoices = 1;
var button = AddChoice(Path.GetFileNameWithoutExtension(path), path, true, OnOpenRecentCollection,
index + kRowOffsetForMRUChoices);
button.Tag = path;
}
private Button AddChoice(string localizedLabel, string localizedTooltip, bool enabled, EventHandler clickHandler,
int row)
{
var button = new Button();
button.Anchor = AnchorStyles.Top | AnchorStyles.Left;
button.Width = _templateButton.Width;
button.Height = _templateButton.Height;
button.Font = new Font(StringCatalog.LabelFont.FontFamily, _templateButton.Font.Size,
_templateButton.Font.Style);
button.Image = _templateButton.Image;
button.ImageAlign = ContentAlignment.MiddleLeft;
button.Click += clickHandler;
button.Text = " " + localizedLabel;
button.FlatAppearance.BorderSize = _templateButton.FlatAppearance.BorderSize;
button.ForeColor = _templateButton.ForeColor;
button.FlatStyle = _templateButton.FlatStyle;
button.ImageAlign = _templateButton.ImageAlign;
button.TextImageRelation = _templateButton.TextImageRelation;
button.UseVisualStyleBackColor = _templateButton.UseVisualStyleBackColor;
button.Enabled = enabled;
toolTip1.SetToolTip(button, localizedTooltip);
tableLayoutPanel2.Controls.Add(button);
tableLayoutPanel2.SetRow(button, row);
tableLayoutPanel2.SetColumn(button, 0);
return button;
}
#if Chorus
private void OnGetFromInternet(object sender, EventArgs e)
{
using (var dlg = new Chorus.UI.Clone.GetCloneFromInternetDialog(NewCollectionWizard.DefaultParentDirectoryForCollections))
{
SelectAndCloneProject(dlg);
}
}
private void OnGetFromUsb(object sender, EventArgs e)
{
using (var dlg = new Chorus.UI.Clone.GetCloneFromUsbDialog(NewCollectionWizard.DefaultParentDirectoryForCollections))
{
SelectAndCloneProject(dlg);
}
}
private void OnGetFromChorusHub(object sender, EventArgs e)
{
using (var dlg = new Chorus.UI.Clone.GetCloneFromChorusHubDialog(new GetCloneFromChorusHubModel(NewCollectionWizard.DefaultParentDirectoryForCollections)))
{
SelectAndCloneProject(dlg);
}
}
private void SelectAndCloneProject(ICloneSourceDialog dlg)
{
try
{
if (!Directory.Exists(NewCollectionWizard.DefaultParentDirectoryForCollections))
{
Directory.CreateDirectory(NewCollectionWizard.DefaultParentDirectoryForCollections);
}
dlg.SetFilePatternWhichMustBeFoundInHgDataFolder("*.bloom_collection.i");
if (DialogResult.Cancel == ((Form)dlg).ShowDialog())
return;
SelectCollectionAndClose(CollectionSettings.FindSettingsFileInFolder(dlg.PathToNewlyClonedFolder));
}
catch (Exception error)
{
SIL.Reporting.ErrorReport.NotifyUserOfProblem(error, "Bloom ran into a problem:\r\n{0}",
error.Message);
}
}
#endif
private void OnOpenRecentCollection(object sender, EventArgs e)
{
SelectCollectionAndClose(((Button) sender).Tag as string);
}
private void OnBrowseForExistingLibraryClick(object sender, EventArgs e)
{
if (!Directory.Exists(NewCollectionWizard.DefaultParentDirectoryForCollections))
{
Directory.CreateDirectory(NewCollectionWizard.DefaultParentDirectoryForCollections);
}
using (var dlg = new OpenFileDialog())
{
dlg.Title = "Open Collection";
dlg.Filter = _filterString;
dlg.InitialDirectory = NewCollectionWizard.DefaultParentDirectoryForCollections;
dlg.CheckFileExists = true;
dlg.CheckPathExists = true;
if (dlg.ShowDialog(this) == DialogResult.Cancel)
return;
SelectCollectionAndClose(dlg.FileName);
}
}
private void CreateNewLibrary_LinkClicked(object sender, EventArgs e)
{
var desiredOrExistingSettingsFilePath = _createNewLibraryAndReturnPath();
if (desiredOrExistingSettingsFilePath == null)
return;
var settings = new CollectionSettings(desiredOrExistingSettingsFilePath);
SelectCollectionAndClose(settings.SettingsFilePath);
}
public void SelectCollectionAndClose(string path)
{
SelectedPath = path;
if (!string.IsNullOrEmpty(path))
{
if (ReportIfInvalidCollectionToEdit(path)) return;
//CheckForBeingInDropboxFolder(path);
_mruList.AddNewPath(path);
Invoke(DoneChoosingOrCreatingLibrary);
}
}
public static bool ReportIfInvalidCollectionToEdit(string path)
{
if (IsInvalidCollectionToEdit(path))
{
var msg = L10NSharp.LocalizationManager.GetString("OpenCreateCloneControl.InSourceCollectionMessage",
"This collection is part of your 'Sources for new books' which you can see in the bottom left of the Collections tab. It cannot be opened for editing.");
MessageBox.Show(msg);
return true;
}
return false;
}
public static bool IsInvalidCollectionToEdit(string path)
{
return path.StartsWith(ProjectContext.GetInstalledCollectionsDirectory())
|| path.StartsWith(BloomFileLocator.FactoryTemplateBookDirectory);
}
#if NotOkToBeInDropbox
/// <summary>
/// Path(s) to the user's Dropbox folder(s). It is static because we only want to look these up once.
/// </summary>
private static List<string> _dropboxFolders;
/// <summary>
/// This method checks 'path' for being in a Dropbox folder. If so, it displays a warning message.
/// </summary>
public static void CheckForBeingInDropboxFolder(string path)
{
if (string.IsNullOrEmpty(path)) return;
try
{
if (_dropboxFolders == null)
{
_dropboxFolders = new List<string>();
string dropboxInfoFile;
// On Windows, Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) returns
// the path of the user's AppData/Roaming subdirectory. I know the name looks like it should
// return the AppData directory itself, but it returns the Roaming subdirectory (although
// there seems to be some confusion about this on stackoverflow.) MSDN has this to say to
// describe this enumeration value:
// The directory that serves as a common repository for application-specific data for the
// current roaming user.
// My tests on Windows 7/.Net 4.0 empirically show the return value looks something like
// C:\Users\username\AppData\Roaming
// On Linux/Mono 3, the return value looks something like
// /home/username/.config
// but Dropbox places its .dropbox folder in the user's home directory so we need to strip
// one directory level from that return value.
var baseFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
if (SIL.PlatformUtilities.Platform.IsWindows)
dropboxInfoFile = Path.Combine(baseFolder, @"Dropbox\info.json");
else
dropboxInfoFile = Path.Combine(Path.GetDirectoryName(baseFolder), @".dropbox/info.json");
//on my windows 10 box, the file we want is in AppData\Local\Dropbox
if (!RobustFile.Exists(dropboxInfoFile))
{
baseFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
if (SIL.PlatformUtilities.Platform.IsWindows)
dropboxInfoFile = Path.Combine(baseFolder, @"Dropbox\info.json");
else
dropboxInfoFile = Path.Combine(Path.GetDirectoryName(baseFolder), @".dropbox/info.json");
if (!RobustFile.Exists(dropboxInfoFile))
return; // User appears to not have Dropbox installed
}
var info = RobustFile.ReadAllText(dropboxInfoFile);
var matches = Regex.Matches(info, @"{""path"": ""([^""]+)"",");
foreach (Match match in matches)
{
var folder = match.Groups[1].Value;
if (SIL.PlatformUtilities.Platform.IsWindows)
{
folder = folder.Replace("\\\\", "\\");
folder = folder.ToLowerInvariant();
}
_dropboxFolders.Add(folder + Path.DirectorySeparatorChar);
}
}
if (_dropboxFolders.Count == 0)
return; // User appears to not have Dropbox installed
if (SIL.PlatformUtilities.Platform.IsWindows)
path = path.ToLowerInvariant(); // We do a case-insensitive compare on Windows.
foreach (var folder in _dropboxFolders)
{
if (path.StartsWith(folder))
{
var msg = L10NSharp.LocalizationManager.GetString("OpenCreateCloneControl.InDropboxMessage",
"Bloom detected that this collection is located in your Dropbox folder. This can cause problems as Dropbox sometimes locks Bloom out of its own files. If you have problems, we recommend that you move your collection somewhere else or disable Dropbox while using Bloom.",
"");
SIL.Reporting.ErrorReport.NotifyUserOfProblem(msg);
return;
}
}
}
catch (Exception e)
{
// To help fix BL-1246, we enable this:
SIL.Reporting.ErrorReport.NotifyUserOfProblem(e,
"For some reason Bloom could not check your Dropbox settings. This should not cause you any problems, but please report it so we can fix it.");
SIL.Reporting.Logger.WriteEvent("*** In CheckForBeingInDropboxFolder(), got "+e.Message+Environment.NewLine+e.StackTrace);
Debug.Fail(e.Message);
}
}
#endif
private void _readMoreLabel_Click(object sender, LinkLabelLinkClickedEventArgs e)
{
HelpLauncher.Show(null, "Chorus_Help.chm", "Chorus/Chorus_overview.htm");
}
public void UpdateUiLanguageMenuSelection()
{
foreach (ToolStripDropDownItem item in _uiLanguageMenu.DropDownItems)
{
CultureInfo cultureInfo = (CultureInfo) item.Tag;
if (cultureInfo.IetfLanguageTag == Settings.Default.UserInterfaceLanguage)
{
item.Select();
WorkspaceView.UpdateMenuTextToShorterNameOfSelection(_uiLanguageMenu, cultureInfo);
return;
}
}
}
}
}
| |
using UnityEngine;
using System;
using System.Collections.Generic;
using PixelCrushers.DialogueSystem.UnityGUI;
namespace PixelCrushers.DialogueSystem {
/// <summary>
/// This component implements a proximity-based selector that allows the player to move into
/// range and use a usable object.
///
/// To mark an object usable, add the Usable component and a collider to it. The object's
/// layer should be in the layer mask specified on the Selector component.
///
/// The proximity selector tracks the most recent usable object whose trigger the player has
/// entered. It displays a targeting reticle and information about the object. If the target
/// is in range, the inRange reticle texture is displayed; otherwise the outOfRange texture is
/// displayed.
///
/// If the player presses the use button (which defaults to spacebar and Fire2), the targeted
/// object will receive an "OnUse" message.
///
/// You can hook into SelectedUsableObject and DeselectedUsableObject to get notifications
/// when the current target has changed.
/// </summary>
[AddComponentMenu("Dialogue System/Actor/Player/Proximity Selector")]
public class ProximitySelector : MonoBehaviour {
/// <summary>
/// This class defines the textures and size of the targeting reticle.
/// </summary>
[System.Serializable]
public class Reticle {
public Texture2D inRange;
public Texture2D outOfRange;
public float width = 64f;
public float height = 64f;
}
/// <summary>
/// If <c>true</c>, uses a default OnGUI to display a selection message and
/// targeting reticle.
/// </summary>
public bool useDefaultGUI = true;
/// <summary>
/// The GUI skin to use for the target's information (name and use message).
/// </summary>
public GUISkin guiSkin;
/// <summary>
/// The name of the GUI style in the skin.
/// </summary>
public string guiStyleName = "label";
/// <summary>
/// The text alignment.
/// </summary>
public TextAnchor alignment = TextAnchor.UpperCenter;
/// <summary>
/// The color of the information labels when the target is in range.
/// </summary>
public Color color = Color.yellow;
/// <summary>
/// The text style for the text.
/// </summary>
public TextStyle textStyle = TextStyle.Shadow;
/// <summary>
/// The color of the text style's outline or shadow.
/// </summary>
public Color textStyleColor = Color.black;
/// <summary>
/// The default use message. This can be overridden in the target's Usable component.
/// </summary>
public string defaultUseMessage = "(spacebar to interact)";
/// <summary>
/// The key that sends an OnUse message.
/// </summary>
public KeyCode useKey = KeyCode.Space;
/// <summary>
/// The button that sends an OnUse message.
/// </summary>
public string useButton = "Fire2";
/// <summary>
/// Tick to enable touch triggering.
/// </summary>
public bool enableTouch = false;
/// <summary>
/// If touch triggering is enabled and there's a touch in this area,
/// the selector triggers.
/// </summary>
public ScaledRect touchArea = new ScaledRect(ScaledRect.empty);
/// <summary>
/// If ticked, the OnUse message is broadcast to the usable object's children.
/// </summary>
public bool broadcastToChildren = true;
/// <summary>
/// The actor transform to send with OnUse. Defaults to this transform.
/// </summary>
public Transform actorTransform = null;
/// <summary>
/// Occurs when the selector has targeted a usable object.
/// </summary>
public event SelectedUsableObjectDelegate SelectedUsableObject = null;
/// <summary>
/// Occurs when the selector has untargeted a usable object.
/// </summary>
public event DeselectedUsableObjectDelegate DeselectedUsableObject = null;
/// <summary>
/// Gets the current usable.
/// </summary>
/// <value>The usable.</value>
public Usable CurrentUsable { get { return currentUsable; } }
/// <summary>
/// Gets the GUI style.
/// </summary>
/// <value>The GUI style.</value>
public GUIStyle GuiStyle { get { SetGuiStyle(); return guiStyle; } }
/// <summary>
/// Keeps track of which usable objects' triggers the selector is currently inside.
/// </summary>
private List<Usable> usablesInRange = new List<Usable>();
/// <summary>
/// The current usable that will receive an OnUse message if the player hits the use button.
/// </summary>
private Usable currentUsable = null;
private string currentHeading = string.Empty;
private string currentUseMessage = string.Empty;
/// <summary>
/// Caches the GUI style to use when displaying the selection message in OnGUI.
/// </summary>
private GUIStyle guiStyle = null;
private const float MinTimeBetweenUseButton = 0.5f;
private float timeToEnableUseButton = 0;
public void OnConversationEnd(Transform actor) {
timeToEnableUseButton = Time.time + MinTimeBetweenUseButton;
}
/// <summary>
/// Sends an OnUse message to the current selection if the player presses the use button.
/// </summary>
void Update() {
// Exit if disabled or paused:
if (!enabled || (Time.timeScale <= 0)) return;
if (DialogueManager.IsConversationActive) timeToEnableUseButton = Time.time + MinTimeBetweenUseButton;
// If the player presses the use key/button, send the OnUse message:
if (IsUseButtonDown() && (currentUsable != null) && (Time.time >= timeToEnableUseButton)) {
var fromTransform = (actorTransform != null) ? actorTransform : this.transform;
if (broadcastToChildren) {
currentUsable.gameObject.BroadcastMessage("OnUse", fromTransform, SendMessageOptions.DontRequireReceiver);
} else {
currentUsable.gameObject.SendMessage("OnUse", fromTransform, SendMessageOptions.DontRequireReceiver);
}
}
}
/// <summary>
/// Checks whether the player has just pressed the use button.
/// </summary>
/// <returns>
/// <c>true</c> if the use button/key is down; otherwise, <c>false</c>.
/// </returns>
private bool IsUseButtonDown() {
if (enableTouch && IsTouchDown()) return true;
return ((useKey != KeyCode.None) && Input.GetKeyDown(useKey))
|| (!string.IsNullOrEmpty(useButton) && Input.GetButtonUp(useButton));
}
private bool IsTouchDown() {
if (Input.touchCount >= 1){
foreach (Touch touch in Input.touches) {
Vector2 screenPosition = new Vector2(touch.position.x, Screen.height - touch.position.y);
if (touchArea.GetPixelRect().Contains(screenPosition)) return true;
}
}
return false;
}
/// <summary>
/// If we entered a trigger, check if it's a usable object. If so, update the selection
/// and raise the SelectedUsableObject event.
/// </summary>
/// <param name='other'>
/// The trigger collider.
/// </param>
void OnTriggerEnter(Collider other) {
CheckTriggerEnter(other.gameObject);
}
/// <summary>
/// If we entered a 2D trigger, check if it's a usable object. If so, update the selection
/// and raise the SelectedUsableObject event.
/// </summary>
/// <param name='other'>
/// The 2D trigger collider.
/// </param>
void OnTriggerEnter2D(Collider2D other) {
CheckTriggerEnter(other.gameObject);
}
/// <summary>
/// If we just left a trigger, check if it's the current selection. If so, clear the
/// selection and raise the DeselectedUsableObject event. If we're still in range of
/// any other usables, select one of them.
/// </summary>
/// <param name='other'>
/// The trigger collider.
/// </param>
void OnTriggerExit(Collider other) {
CheckTriggerExit(other.gameObject);
}
/// <summary>
/// If we just left a 2D trigger, check if it's the current selection. If so, clear the
/// selection and raise the DeselectedUsableObject event. If we're still in range of
/// any other usables, select one of them.
/// </summary>
/// <param name='other'>
/// The 2D trigger collider.
/// </param>
void OnTriggerExit2D(Collider2D other) {
CheckTriggerExit(other.gameObject);
}
private void CheckTriggerEnter(GameObject other) {
Usable usable = other.GetComponent<Usable>();
if (usable != null) {
SetCurrentUsable(usable);
if (!usablesInRange.Contains(usable)) usablesInRange.Add(usable);
if (SelectedUsableObject != null) SelectedUsableObject(usable);
}
}
private void CheckTriggerExit(GameObject other) {
Usable usable = other.GetComponent<Usable>();
if (usable != null) {
if (usablesInRange.Contains(usable)) usablesInRange.Remove(usable);
if (currentUsable == usable) {
if (DeselectedUsableObject != null) DeselectedUsableObject(usable);
Usable newUsable = null;
if (usablesInRange.Count > 0) {
newUsable = usablesInRange[0];
if (SelectedUsableObject != null) SelectedUsableObject(newUsable);
}
SetCurrentUsable(newUsable);
}
}
}
private void SetCurrentUsable(Usable usable) {
currentUsable = usable;
if (usable != null) {
currentHeading = currentUsable.GetName();
currentUseMessage = string.IsNullOrEmpty(currentUsable.overrideUseMessage) ? defaultUseMessage : currentUsable.overrideUseMessage;
} else {
currentHeading = string.Empty;
currentUseMessage = string.Empty;
}
}
/// <summary>
/// If useDefaultGUI is <c>true</c> and a usable object has been targeted, this method
/// draws a selection message and targeting reticle.
/// </summary>
public virtual void OnGUI() {
if (useDefaultGUI) {
SetGuiStyle();
Rect screenRect = new Rect(0, 0, Screen.width, Screen.height);
if (currentUsable != null) {
UnityGUITools.DrawText(screenRect, currentHeading, guiStyle, textStyle, textStyleColor);
UnityGUITools.DrawText(new Rect(0, guiStyle.CalcSize(new GUIContent("Ay")).y, Screen.width, Screen.height), currentUseMessage, guiStyle, textStyle, textStyleColor);
}
}
}
protected void SetGuiStyle() {
GUI.skin = UnityGUITools.GetValidGUISkin(guiSkin);
if (guiStyle == null) {
guiStyle = new GUIStyle(GUI.skin.FindStyle(guiStyleName) ?? GUI.skin.label);
guiStyle.alignment = alignment;
guiStyle.normal.textColor = color;
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.