context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void HorizontalAddInt16()
{
var test = new HorizontalBinaryOpTest__HorizontalAddInt16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse2.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 (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse2.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 (Sse2.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 (Sse2.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 (Sse2.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 HorizontalBinaryOpTest__HorizontalAddInt16
{
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(Int16[] inArray1, Int16[] inArray2, Int16[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>();
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<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, 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 Vector128<Int16> _fld1;
public Vector128<Int16> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
return testStruct;
}
public void RunStructFldScenario(HorizontalBinaryOpTest__HorizontalAddInt16 testClass)
{
var result = Ssse3.HorizontalAdd(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(HorizontalBinaryOpTest__HorizontalAddInt16 testClass)
{
fixed (Vector128<Int16>* pFld1 = &_fld1)
fixed (Vector128<Int16>* pFld2 = &_fld2)
{
var result = Ssse3.HorizontalAdd(
Sse2.LoadVector128((Int16*)(pFld1)),
Sse2.LoadVector128((Int16*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static Int16[] _data2 = new Int16[Op2ElementCount];
private static Vector128<Int16> _clsVar1;
private static Vector128<Int16> _clsVar2;
private Vector128<Int16> _fld1;
private Vector128<Int16> _fld2;
private DataTable _dataTable;
static HorizontalBinaryOpTest__HorizontalAddInt16()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
}
public HorizontalBinaryOpTest__HorizontalAddInt16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
_dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Ssse3.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Ssse3.HorizontalAdd(
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int16>>(_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 = Ssse3.HorizontalAdd(
Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int16*)(_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 = Ssse3.HorizontalAdd(
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int16*)(_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(Ssse3).GetMethod(nameof(Ssse3.HorizontalAdd), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Ssse3).GetMethod(nameof(Ssse3.HorizontalAdd), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Ssse3).GetMethod(nameof(Ssse3.HorizontalAdd), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Ssse3.HorizontalAdd(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Int16>* pClsVar1 = &_clsVar1)
fixed (Vector128<Int16>* pClsVar2 = &_clsVar2)
{
var result = Ssse3.HorizontalAdd(
Sse2.LoadVector128((Int16*)(pClsVar1)),
Sse2.LoadVector128((Int16*)(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<Vector128<Int16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr);
var result = Ssse3.HorizontalAdd(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr));
var result = Ssse3.HorizontalAdd(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr));
var result = Ssse3.HorizontalAdd(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new HorizontalBinaryOpTest__HorizontalAddInt16();
var result = Ssse3.HorizontalAdd(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 HorizontalBinaryOpTest__HorizontalAddInt16();
fixed (Vector128<Int16>* pFld1 = &test._fld1)
fixed (Vector128<Int16>* pFld2 = &test._fld2)
{
var result = Ssse3.HorizontalAdd(
Sse2.LoadVector128((Int16*)(pFld1)),
Sse2.LoadVector128((Int16*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Ssse3.HorizontalAdd(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Int16>* pFld1 = &_fld1)
fixed (Vector128<Int16>* pFld2 = &_fld2)
{
var result = Ssse3.HorizontalAdd(
Sse2.LoadVector128((Int16*)(pFld1)),
Sse2.LoadVector128((Int16*)(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 = Ssse3.HorizontalAdd(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 = Ssse3.HorizontalAdd(
Sse2.LoadVector128((Int16*)(&test._fld1)),
Sse2.LoadVector128((Int16*)(&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(Vector128<Int16> op1, Vector128<Int16> op2, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var outer = 0; outer < (LargestVectorSize / 16); outer++)
{
for (var inner = 0; inner < (8 / sizeof(Int16)); inner++)
{
var i1 = (outer * (16 / sizeof(Int16))) + inner;
var i2 = i1 + (8 / sizeof(Int16));
var i3 = (outer * (16 / sizeof(Int16))) + (inner * 2);
if (result[i1] != (short)(left[i3] + left[i3 + 1]))
{
succeeded = false;
break;
}
if (result[i2] != (short)(right[i3] + right[i3 + 1]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Ssse3)}.{nameof(Ssse3.HorizontalAdd)}<Int16>(Vector128<Int16>, Vector128<Int16>): {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;
}
}
}
}
| |
using System;
using Microsoft.AspNetCore.Mvc;
using Smidge.CompositeFiles;
using Smidge.Models;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;
using Smidge.FileProcessors;
using Smidge.Cache;
using Microsoft.AspNetCore.Authorization;
namespace Smidge.Controllers
{
/// <summary>
/// Controller for handling minified/combined responses
/// </summary>
[AddCompressionHeader(Order = 0)]
[AddExpiryHeaders(Order = 1)]
[CheckNotModified(Order = 2)]
[CompositeFileCacheFilter(Order = 3)]
[AllowAnonymous]
public class SmidgeController : Controller
{
private readonly ISmidgeFileSystem _fileSystem;
private readonly IBundleManager _bundleManager;
private readonly IBundleFileSetGenerator _fileSetGenerator;
private readonly PreProcessPipelineFactory _processorFactory;
private readonly IPreProcessManager _preProcessManager;
private readonly ILogger _logger;
/// <summary>
/// Constructor
/// </summary>
/// <param name="fileSystemHelper"></param>
/// <param name="bundleManager"></param>
/// <param name="fileSetGenerator"></param>
/// <param name="processorFactory"></param>
/// <param name="preProcessManager"></param>
/// <param name="logger"></param>
public SmidgeController(
ISmidgeFileSystem fileSystemHelper,
IBundleManager bundleManager,
IBundleFileSetGenerator fileSetGenerator,
PreProcessPipelineFactory processorFactory,
IPreProcessManager preProcessManager,
ILogger<SmidgeController> logger)
{
_fileSystem = fileSystemHelper ?? throw new ArgumentNullException(nameof(fileSystemHelper));
_bundleManager = bundleManager ?? throw new ArgumentNullException(nameof(bundleManager));
_fileSetGenerator = fileSetGenerator ?? throw new ArgumentNullException(nameof(fileSetGenerator));
_processorFactory = processorFactory ?? throw new ArgumentNullException(nameof(processorFactory));
_preProcessManager = preProcessManager ?? throw new ArgumentNullException(nameof(preProcessManager));
_logger = logger;
}
/// <summary>
/// Handles requests for named bundles
/// </summary>
/// <param name="bundleModel">The bundle model</param>
/// <returns></returns>
public async Task<IActionResult> Bundle(
[FromServices] BundleRequestModel bundleModel)
{
if (!_bundleManager.TryGetValue(bundleModel.FileKey, out Bundle foundBundle))
{
return NotFound();
}
var bundleOptions = foundBundle.GetBundleOptions(_bundleManager, bundleModel.Debug);
var cacheBusterValue = bundleModel.ParsedPath.CacheBusterValue;
//now we need to determine if this bundle has already been created
var cacheFile = _fileSystem.CacheFileSystem.GetCachedCompositeFile(cacheBusterValue, bundleModel.Compression, bundleModel.FileKey, out var cacheFilePath);
if (cacheFile.Exists)
{
_logger.LogDebug($"Returning bundle '{bundleModel.FileKey}' from cache");
if (!string.IsNullOrWhiteSpace(cacheFile.PhysicalPath))
{
//if physical path is available then it's the physical file system, in which case we'll deliver the file with the PhysicalFileResult
//FilePathResult uses IHttpSendFileFeature which is a native host option for sending static files
return PhysicalFile(cacheFile.PhysicalPath, bundleModel.Mime);
}
else
{
return File(cacheFile.CreateReadStream(), bundleModel.Mime);
}
}
//the bundle doesn't exist so we'll go get the files, process them and create the bundle
//TODO: We should probably lock here right?! we don't want multiple threads trying to do this at the same time, we'll need a dictionary of locks to do this effectively
//get the files for the bundle
var files = _fileSetGenerator.GetOrderedFileSet(foundBundle,
_processorFactory.CreateDefault(
//the file type in the bundle will always be the same
foundBundle.Files[0].DependencyType))
.ToArray();
if (files.Length == 0)
{
return NotFound();
}
using (var bundleContext = new BundleContext(cacheBusterValue, bundleModel, cacheFilePath))
{
var watch = new Stopwatch();
watch.Start();
_logger.LogDebug($"Processing bundle '{bundleModel.FileKey}', debug? {bundleModel.Debug} ...");
//we need to do the minify on the original files
foreach (var file in files)
{
await _preProcessManager.ProcessAndCacheFileAsync(file, bundleOptions, bundleContext);
}
//Get each file path to it's hashed location since that is what the pre-processed file will be saved as
var fileInfos = files.Select(x => _fileSystem.CacheFileSystem.GetCacheFile(
x,
() => _fileSystem.GetRequiredFileInfo(x),
bundleOptions.FileWatchOptions.Enabled,
Path.GetExtension(x.FilePath),
cacheBusterValue,
out _));
using (var resultStream = await GetCombinedStreamAsync(fileInfos, bundleContext))
{
//compress the response (if enabled)
var compressedStream = await Compressor.CompressAsync(
//do not compress anything if it's not enabled in the bundle options
bundleOptions.CompressResult ? bundleModel.Compression : CompressionType.None,
resultStream);
//save the resulting compressed file, if compression is not enabled it will just save the non compressed format
// this persisted file will be used in the CheckNotModifiedAttribute which will short circuit the request and return
// the raw file if it exists for further requests to this path
await CacheCompositeFileAsync(_fileSystem.CacheFileSystem, cacheFilePath, compressedStream);
_logger.LogDebug($"Processed bundle '{bundleModel.FileKey}' in {watch.ElapsedMilliseconds}ms");
//return the stream
return File(compressedStream, bundleModel.Mime);
}
}
}
/// <summary>
/// Handles requests for composite files (non-named bundles)
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public async Task<IActionResult> Composite(
[FromServices] CompositeFileModel file)
{
if (!file.ParsedPath.Names.Any())
{
return NotFound();
}
var defaultBundleOptions = _bundleManager.GetDefaultBundleOptions(false);
var cacheBusterValue = file.ParsedPath.CacheBusterValue;
var cacheFile = _fileSystem.CacheFileSystem.GetCachedCompositeFile(cacheBusterValue, file.Compression, file.FileKey, out var cacheFilePath);
if (cacheFile.Exists)
{
//this is already processed, return it
if (!string.IsNullOrWhiteSpace(cacheFile.PhysicalPath))
{
//if physical path is available then it's the physical file system, in which case we'll deliver the file with the PhysicalFileResult
//FilePathResult uses IHttpSendFileFeature which is a native host option for sending static files
return PhysicalFile(cacheFile.PhysicalPath, file.Mime);
}
else
{
return File(cacheFile.CreateReadStream(), file.Mime);
}
}
using (var bundleContext = new BundleContext(cacheBusterValue, file, cacheFilePath))
{
var files = file.ParsedPath.Names.Select(filePath =>
_fileSystem.CacheFileSystem.GetRequiredFileInfo(
$"{file.ParsedPath.CacheBusterValue}/{filePath + file.Extension}"));
using (var resultStream = await GetCombinedStreamAsync(files, bundleContext))
{
var compressedStream = await Compressor.CompressAsync(file.Compression, resultStream);
await CacheCompositeFileAsync(_fileSystem.CacheFileSystem, cacheFilePath, compressedStream);
return File(compressedStream, file.Mime);
}
}
}
private static async Task CacheCompositeFileAsync(ICacheFileSystem cacheProvider, string filePath, Stream compositeStream)
{
await cacheProvider.WriteFileAsync(filePath, compositeStream);
if (compositeStream.CanSeek)
compositeStream.Position = 0;
}
/// <summary>
/// Combines files into a single stream
/// </summary>
/// <param name="files"></param>
/// <param name="bundleContext"></param>
/// <returns></returns>
private async Task<Stream> GetCombinedStreamAsync(IEnumerable<IFileInfo> files, BundleContext bundleContext)
{
//TODO: Here we need to be able to prepend/append based on a "BundleContext" (or similar)
List<Stream> inputs = null;
try
{
inputs = files.Where(x => x.Exists)
.Select(x => x.CreateReadStream())
.ToList();
var delimeter = bundleContext.BundleRequest.Extension == ".js" ? ";\n" : "\n";
var combined = await bundleContext.GetCombinedStreamAsync(inputs, delimeter);
return combined;
}
finally
{
if (inputs != null)
{
foreach (var input in inputs)
{
input.Dispose();
}
}
}
}
}
}
| |
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Localization;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.Extensions.DependencyInjection;
using OrchardCore.DisplayManagement.Razor;
using OrchardCore.DisplayManagement.Shapes;
using OrchardCore.DisplayManagement.Title;
using OrchardCore.Settings;
namespace OrchardCore.DisplayManagement.RazorPages
{
public abstract class Page : Microsoft.AspNetCore.Mvc.RazorPages.Page
{
private dynamic _displayHelper;
private IShapeFactory _shapeFactory;
private IOrchardDisplayHelper _orchardHelper;
private ISite _site;
public override ViewContext ViewContext
{
get => base.ViewContext;
set
{
// We make the ViewContext available to other sub-systems that need it.
var viewContextAccessor = value.HttpContext.RequestServices.GetService<ViewContextAccessor>();
base.ViewContext = viewContextAccessor.ViewContext = value;
}
}
private void EnsureDisplayHelper()
{
if (_displayHelper == null)
{
_displayHelper = HttpContext.RequestServices.GetService<IDisplayHelper>();
}
}
private void EnsureShapeFactory()
{
if (_shapeFactory == null)
{
_shapeFactory = HttpContext.RequestServices.GetService<IShapeFactory>();
}
}
/// <summary>
/// Gets a dynamic shape factory to create new shapes.
/// </summary>
/// <example>
/// Usage:
/// <code>
/// await New.MyShape()
/// await New.MyShape(A: 1, B: "Some text")
/// (await New.MyShape()).A(1).B("Some text")
/// </code>
/// </example>
public dynamic New => Factory;
/// <summary>
/// Gets an <see cref="IShapeFactory"/> to create new shapes.
/// </summary>
public IShapeFactory Factory
{
get
{
EnsureShapeFactory();
return _shapeFactory;
}
}
/// <summary>
/// Renders a shape.
/// </summary>
/// <param name="shape">The shape.</param>
public Task<IHtmlContent> DisplayAsync(dynamic shape)
{
EnsureDisplayHelper();
return (Task<IHtmlContent>)_displayHelper(shape);
}
public IOrchardDisplayHelper Orchard
{
get
{
if (_orchardHelper == null)
{
EnsureDisplayHelper();
_orchardHelper = new OrchardDisplayHelper(HttpContext, _displayHelper);
}
return _orchardHelper;
}
}
private dynamic _themeLayout;
public dynamic ThemeLayout
{
get
{
if (_themeLayout == null)
{
_themeLayout = HttpContext.Features.Get<RazorViewFeature>()?.ThemeLayout;
}
return _themeLayout;
}
set
{
_themeLayout = value;
}
}
public string ViewLayout
{
get
{
if (ThemeLayout is IShape layout)
{
if (layout.Metadata.Alternates.Count > 0)
{
return layout.Metadata.Alternates.Last;
}
return layout.Metadata.Type;
}
return String.Empty;
}
set
{
if (ThemeLayout is IShape layout)
{
if (layout.Metadata.Alternates.Contains(value))
{
if (layout.Metadata.Alternates.Last == value)
{
return;
}
layout.Metadata.Alternates.Remove(value);
}
layout.Metadata.Alternates.Add(value);
}
}
}
private IPageTitleBuilder _pageTitleBuilder;
public IPageTitleBuilder Title
{
get
{
if (_pageTitleBuilder == null)
{
_pageTitleBuilder = HttpContext.RequestServices.GetRequiredService<IPageTitleBuilder>();
}
return _pageTitleBuilder;
}
}
private IViewLocalizer _t;
/// <summary>
/// The <see cref="IViewLocalizer"/> instance for the current view.
/// </summary>
public IViewLocalizer T
{
get
{
if (_t == null)
{
_t = HttpContext.RequestServices.GetRequiredService<IViewLocalizer>();
((IViewContextAware)_t).Contextualize(ViewContext);
}
return _t;
}
}
/// <summary>
/// Adds a segment to the title and returns all segments.
/// </summary>
/// <param name="segment">The segment to add to the title.</param>
/// <param name="position">Optional. The position of the segment in the title.</param>
/// <param name="separator">The html string that should separate all segments.</param>
/// <returns>And <see cref="IHtmlContent"/> instance representing the full title.</returns>
public IHtmlContent RenderTitleSegments(IHtmlContent segment, string position = "0", IHtmlContent separator = null)
{
Title.AddSegment(segment, position);
return Title.GenerateTitle(separator);
}
/// <summary>
/// Adds a segment to the title and returns all segments.
/// </summary>
/// <param name="segment">The segment to add to the title.</param>
/// <param name="position">Optional. The position of the segment in the title.</param>
/// <param name="separator">The html string that should separate all segments.</param>
/// <returns>And <see cref="IHtmlContent"/> instance representing the full title.</returns>
public IHtmlContent RenderTitleSegments(string segment, string position = "0", IHtmlContent separator = null)
{
Title.AddSegment(new StringHtmlContent(segment), position);
return Title.GenerateTitle(separator);
}
/// <summary>
/// Creates a <see cref="TagBuilder"/> to render a shape.
/// </summary>
/// <param name="shape">The shape.</param>
/// <returns>A new <see cref="TagBuilder"/>.</returns>
public TagBuilder Tag(dynamic shape)
{
return Shape.GetTagBuilder(shape);
}
public TagBuilder Tag(dynamic shape, string tag)
{
return Shape.GetTagBuilder(shape, tag);
}
/// <summary>
/// Check if a zone is defined in the layout or it has items.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public bool IsSectionDefined(string name)
{
// We can replace the base implementation as it can't be called on a view that is not an actual MVC Layout.
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
var zone = ThemeLayout[name];
return zone != null;
}
/// <summary>
/// Renders a zone from the RazorPages.
/// </summary>
/// <param name="name">The name of the zone to render.</param>
public Task<IHtmlContent> RenderSectionAsync(string name)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
return RenderSectionAsync(name, required: true);
}
/// <summary>
/// Renders a zone from the RazorPages.
/// </summary>
/// <param name="name">The name of the zone to render.</param>
/// <param name="required">Whether the zone is required or not.</param>
public Task<IHtmlContent> RenderSectionAsync(string name, bool required)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
var zone = ThemeLayout[name];
if (required && zone != null && zone is Shape && zone.Items.Count == 0)
{
throw new InvalidOperationException("Zone not found: " + name);
}
return DisplayAsync(zone);
}
public object OrDefault(object text, object other)
{
if (text == null || Convert.ToString(text) == "")
{
return other;
}
return text;
}
/// <summary>
/// Returns the full escaped path of the current request.
/// </summary>
public string FullRequestPath => HttpContext.Request.PathBase + HttpContext.Request.Path + HttpContext.Request.QueryString;
/// <summary>
/// Gets the <see cref="ISite"/> instance.
/// </summary>
public ISite Site
{
get
{
if (_site == null)
{
_site = HttpContext.Features.Get<RazorViewFeature>()?.Site;
}
return _site;
}
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.IO;
using System.Collections.Generic;
using Type = System.Type;
using UnityEngine.Assertions;
#if UNITY_EDITOR
using System.Linq;
#endif
/// <summary>
/// Cache for ComponentDependencyAttribute so GetAttributes doesn't need to be called on each type
/// at runtime (potential GC Alloc and performance spikes)
/// </summary>
public class ComponentDependencyCache : ResourceSingleton<ComponentDependencyCache>
, ISerializationCallbackReceiver
{
[System.Serializable]
public struct SerializedDependency
{
public string requiredTypeName;
public string defaultTypeName;
}
[System.Serializable]
public struct SerializedItem
{
public string typeName;
public SerializedDependency[] dependencies;
}
/// <summary>
/// Serialized version of dependency table to be loaded at runtime.
/// </summary>
[SerializeField] List<SerializedItem> m_serializedItems = new List<SerializedItem>();
public struct Dependency
{
public Type requiredType;
public Type defaultType;
}
/// <summary>
/// Dependencies table for all types using ComponentDepenencyAttribute
/// </summary>
Dictionary<Type, Dependency[]> m_dependencies = new Dictionary<Type, Dependency[]>();
static Dependency[] GetDependencies(Type forType)
{
Dependency[] output = null;
if(instance.m_dependencies.TryGetValue(forType, out output))
{
return output;
}
return new Dependency[0];
}
public static void CreateDependencies_Runtime(Component forComponent)
{
if(forComponent==null) return;
var gameObject = forComponent.gameObject;
var type = forComponent.GetType();
var dependencies = ComponentDependencyCache.GetDependencies(type);
for(int i=0;i<dependencies.Length;++i)
{
var dep = dependencies[i];
if(gameObject.GetComponent(dep.requiredType)) continue;
gameObject.AddComponent(dep.defaultType);
}
}
#if UNITY_EDITOR
public static void CreateDependencies_Editor(Component forComponent)
{
if(forComponent==null) return;
var gameObject = forComponent.gameObject;
var type = forComponent.GetType();
var depenencyAttributes = (ComponentDependencyAttribute[])type.GetCustomAttributes(typeof(ComponentDependencyAttribute), true);
for(int i=0; i<depenencyAttributes.Length; ++i)
{
var attrib = depenencyAttributes[i];
var deps = attrib.GetComponentDependencies();
for(int j=0; j<deps.Length; ++j)
{
var dep = deps[j];
if(typeof(Component).IsAssignableFrom(dep.requiredType))
{
var component = gameObject.GetComponent(dep.requiredType);
if(!component)
{
Debug.Log("ComponentDependencyAttribute: Creating default component type "+dep.defaultType.Name);
gameObject.AddComponent(dep.defaultType);
}
}
}
}
}
#endif
#if UNITY_EDITOR
/*
public class Builder : UnityEditor.AssetPostprocessor
{
static void OnPostprocessAllAssets (string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
{
if(importedAssets
.Concat(movedAssets)
.Concat(deletedAssets)
.Any(x=> x.EndsWith(".cs") || x.EndsWith(".js")))
{
ComponentDependencyCache.ProcessDependencies();
}
}
}*/
/*
[UnityEditor.InitializeOnLoadMethod]
static void InitializeOnLoad()
{
if (UnityEditor.BuildPipeline.isBuildingPlayer || UnityEditor.EditorApplication.isPlayingOrWillChangePlaymode)
{
ProcessDependencies();
}
else
{
UnityEditor.EditorApplication.delayCall += ProcessDependencies;
}
}
*/
/*
[UnityEditor.Callbacks.PostProcessScene]
static void PostProcessScene()
{
if (!Application.isPlaying && UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene().buildIndex <= 0)
{
ProcessDependencies();
}
}*/
[UnityEditor.Callbacks.DidReloadScripts]
private static void ProcessDependencies()
{
ResourceSingletonBuilder.BuildResourceSingletonsIfDirty();
var types = new string[] { ".cs", ".js" };
var allScriptPaths = Directory.GetFiles("Assets", "*.*", SearchOption.AllDirectories)
.Where(s => types.Any(x => s.EndsWith(x, System.StringComparison.CurrentCultureIgnoreCase)))
.ToArray();
for (int i = 0; i < allScriptPaths.Length; ++i)
{
UnityEditor.MonoScript script = UnityEditor.AssetDatabase.LoadAssetAtPath(allScriptPaths[i], typeof(UnityEditor.MonoScript)) as UnityEditor.MonoScript;
if (!script || script.GetClass() == null) continue;
if (!typeof(Component).IsAssignableFrom(script.GetClass())) continue;
var type = script.GetClass();
var attributes = (ComponentDependencyAttribute[])type.GetCustomAttributes(typeof(ComponentDependencyAttribute), true);
if (attributes.Length == 0) continue;
var dependencies = attributes
.Where(x => x != null)
.SelectMany(x => x.GetComponentDependencies())
.ToArray();
ProcessAll_SetDependencies(type, dependencies);
}
}
static void ProcessAll_SetDependencies(Type type, Dependency[] dependencies)
{
var items = instance.m_serializedItems;
if(dependencies == null)
{
dependencies = new Dependency[0];
}
items.RemoveAll(x=>x.typeName==type.Name);
if(dependencies.Length>0)
{
var seralisedDeps = new List<SerializedDependency>();
foreach(var dependency in dependencies)
{
Assert.IsNotNull(dependency.requiredType);
Assert.IsNotNull(dependency.defaultType);
seralisedDeps.Add(new SerializedDependency(){
requiredTypeName = dependency.requiredType.FullName,
defaultTypeName = dependency.defaultType.FullName,
});
}
items.Add(new SerializedItem(){
typeName = type.FullName,
dependencies = seralisedDeps.ToArray()
});
}
instance.hideFlags = HideFlags.NotEditable;
UnityEditor.EditorUtility.SetDirty(instance);
var so = new UnityEditor.SerializedObject(instance);
so.Update();
UnityEditor.AssetDatabase.SaveAssets();
}
#endif
#region ISerializationCallbackReceiver implementation
void ISerializationCallbackReceiver.OnBeforeSerialize()
{
}
void ISerializationCallbackReceiver.OnAfterDeserialize()
{
m_dependencies.Clear();
for(int i=0;i<m_serializedItems.Count;++i)
{
var item = m_serializedItems[i];
if(string.IsNullOrEmpty(item.typeName)) continue;
var forType = GetType(item.typeName);
if(forType==null)
{
continue;
}
List<Dependency> list = new List<Dependency>();
for(int j=0;j<item.dependencies.Length;++j)
{
var dependency = new Dependency();
var dep = item.dependencies[j];
if(!string.IsNullOrEmpty(dep.requiredTypeName))
{
dependency.requiredType = GetType(dep.requiredTypeName);
}
if(dependency.requiredType==null)
{
#if DEBUG_LOG
Debug.Log("ComponentDependencyCache: Skipping missing type "+dep.requiredTypeName);
#endif
continue;
}
if(!string.IsNullOrEmpty(dep.defaultTypeName))
{
dependency.defaultType = GetType(dep.defaultTypeName);
}
if(dependency.defaultType==null)
{
Debug.LogError("ComponentDependencyCache: Could not find type "+dep.defaultTypeName);
continue;
}
list.Add(dependency);
}
m_dependencies[forType] = list.ToArray();
}
}
#endregion
static System.Type GetType(string name)
{
System.Type type = null;
var assemblies = System.AppDomain.CurrentDomain.GetAssemblies();
for (int i = 0; i < assemblies.Length; i++)
{
type = assemblies[i].GetType(name);
if (type != null) break;
}
return type;
}
}
| |
// 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.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Tests
{
public partial class StreamWriterTests
{
[Fact]
public void Write_EmptySpan_WritesNothing()
{
using (var s = new MemoryStream())
using (var writer = new StreamWriter(s))
{
writer.Write(ReadOnlySpan<char>.Empty);
writer.Flush();
Assert.Equal(0, s.Position);
}
}
[Fact]
public void WriteLine_EmptySpan_WritesNewLine()
{
using (var s = new MemoryStream())
using (var writer = new StreamWriter(s))
{
writer.WriteLine(ReadOnlySpan<char>.Empty);
writer.Flush();
Assert.Equal(Environment.NewLine.Length, s.Position);
}
}
[Fact]
public async Task WriteAsync_EmptyMemory_WritesNothing()
{
using (var s = new MemoryStream())
using (var writer = new StreamWriter(s))
{
await writer.WriteAsync(ReadOnlyMemory<char>.Empty);
await writer.FlushAsync();
Assert.Equal(0, s.Position);
}
}
[Fact]
public async Task WriteLineAsync_EmptyMemory_WritesNothing()
{
using (var s = new MemoryStream())
using (var writer = new StreamWriter(s))
{
await writer.WriteLineAsync(ReadOnlyMemory<char>.Empty);
await writer.FlushAsync();
Assert.Equal(Environment.NewLine.Length, s.Position);
}
}
[Theory]
[InlineData(1, 1, 1, false)]
[InlineData(100, 1, 100, false)]
[InlineData(100, 10, 3, false)]
[InlineData(1, 1, 1, true)]
[InlineData(100, 1, 100, true)]
[InlineData(100, 10, 3, true)]
public void Write_Span_WritesExpectedData(int length, int writeSize, int writerBufferSize, bool autoFlush)
{
using (var s = new MemoryStream())
using (var writer = new StreamWriter(s, Encoding.ASCII, writerBufferSize) { AutoFlush = autoFlush })
{
var data = new char[length];
var rand = new Random(42);
for (int i = 0; i < data.Length; i++)
{
data[i] = (char)(rand.Next(0, 26) + 'a');
}
Span<char> source = data;
while (source.Length > 0)
{
int n = Math.Min(source.Length, writeSize);
writer.Write(source.Slice(0, n));
source = source.Slice(n);
}
writer.Flush();
Assert.Equal(data, s.ToArray().Select(b => (char)b));
}
}
[Theory]
[InlineData(1, 1, 1, false)]
[InlineData(100, 1, 100, false)]
[InlineData(100, 10, 3, false)]
[InlineData(1, 1, 1, true)]
[InlineData(100, 1, 100, true)]
[InlineData(100, 10, 3, true)]
public async Task Write_Memory_WritesExpectedData(int length, int writeSize, int writerBufferSize, bool autoFlush)
{
using (var s = new MemoryStream())
using (var writer = new StreamWriter(s, Encoding.ASCII, writerBufferSize) { AutoFlush = autoFlush })
{
var data = new char[length];
var rand = new Random(42);
for (int i = 0; i < data.Length; i++)
{
data[i] = (char)(rand.Next(0, 26) + 'a');
}
ReadOnlyMemory<char> source = data;
while (source.Length > 0)
{
int n = Math.Min(source.Length, writeSize);
await writer.WriteAsync(source.Slice(0, n));
source = source.Slice(n);
}
await writer.FlushAsync();
Assert.Equal(data, s.ToArray().Select(b => (char)b));
}
}
[Theory]
[InlineData(1, 1, 1, false)]
[InlineData(100, 1, 100, false)]
[InlineData(100, 10, 3, false)]
[InlineData(1, 1, 1, true)]
[InlineData(100, 1, 100, true)]
[InlineData(100, 10, 3, true)]
public void WriteLine_Span_WritesExpectedData(int length, int writeSize, int writerBufferSize, bool autoFlush)
{
using (var s = new MemoryStream())
using (var writer = new StreamWriter(s, Encoding.ASCII, writerBufferSize) { AutoFlush = autoFlush })
{
var data = new char[length];
var rand = new Random(42);
for (int i = 0; i < data.Length; i++)
{
data[i] = (char)(rand.Next(0, 26) + 'a');
}
Span<char> source = data;
while (source.Length > 0)
{
int n = Math.Min(source.Length, writeSize);
writer.WriteLine(source.Slice(0, n));
source = source.Slice(n);
}
writer.Flush();
Assert.Equal(length + (Environment.NewLine.Length * (length / writeSize)), s.Length);
}
}
[Theory]
[InlineData(1, 1, 1, false)]
[InlineData(100, 1, 100, false)]
[InlineData(100, 10, 3, false)]
[InlineData(1, 1, 1, true)]
[InlineData(100, 1, 100, true)]
[InlineData(100, 10, 3, true)]
public async Task WriteLineAsync_Memory_WritesExpectedData(int length, int writeSize, int writerBufferSize, bool autoFlush)
{
using (var s = new MemoryStream())
using (var writer = new StreamWriter(s, Encoding.ASCII, writerBufferSize) { AutoFlush = autoFlush })
{
var data = new char[length];
var rand = new Random(42);
for (int i = 0; i < data.Length; i++)
{
data[i] = (char)(rand.Next(0, 26) + 'a');
}
ReadOnlyMemory<char> source = data;
while (source.Length > 0)
{
int n = Math.Min(source.Length, writeSize);
await writer.WriteLineAsync(source.Slice(0, n));
source = source.Slice(n);
}
await writer.FlushAsync();
Assert.Equal(length + (Environment.NewLine.Length * (length / writeSize)), s.Length);
}
}
[Fact]
public async Task WriteAsync_Precanceled_ThrowsCancellationException()
{
using (var writer = new StreamWriter(Stream.Null))
{
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => writer.WriteAsync(ReadOnlyMemory<char>.Empty, new CancellationToken(true)));
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => writer.WriteLineAsync(ReadOnlyMemory<char>.Empty, new CancellationToken(true)));
}
}
[Fact]
public void StreamWriter_WithOptionalArguments_NoExceptions()
{
Encoding UTF8NoBOM = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
// check enabled leaveOpen and default encoding
using (var tempStream = new MemoryStream())
{
using (var sw = new StreamWriter(tempStream, leaveOpen: true))
{
Assert.Equal(UTF8NoBOM, sw.Encoding);
}
Assert.True(tempStream.CanRead);
}
// check null encoding, default encoding, default leaveOpen
using (var tempStream = new MemoryStream())
{
using (var sw = new StreamWriter(tempStream, encoding: null))
{
Assert.Equal(UTF8NoBOM, sw.Encoding);
}
Assert.False(tempStream.CanRead);
}
// check bufferSize, default BOM, default leaveOpen
using (var tempStream = new MemoryStream())
{
using (var sw = new StreamWriter(tempStream, bufferSize: -1))
{
Assert.Equal(UTF8NoBOM, sw.Encoding);
}
Assert.False(tempStream.CanRead);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using NuGet.Frameworks;
using NuGet.Packaging;
using NuGet.Packaging.Core;
using NuGet.Versioning;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Microsoft.DotNet.Build.Tasks.Packaging
{
public class CreateTrimDependencyGroups : PackagingTask
{
private const string PlaceHolderDependency = "_._";
[Required]
public ITaskItem[] Dependencies
{
get;
set;
}
[Required]
public ITaskItem[] Files
{
get;
set;
}
/// <summary>
/// Package index files used to define stable package list.
/// </summary>
[Required]
public ITaskItem[] PackageIndexes
{
get;
set;
}
[Output]
public ITaskItem[] TrimmedDependencies
{
get;
set;
}
/* Given a set of available frameworks ("InboxOnTargetFrameworks"), and a list of desired frameworks,
reduce the set of frameworks to the minimum set of frameworks which is compatible (preferring inbox frameworks. */
public override bool Execute()
{
if (null == Dependencies)
{
Log.LogError("Dependencies argument must be specified");
return false;
}
if (PackageIndexes == null && PackageIndexes.Length == 0)
{
Log.LogError("PackageIndexes argument must be specified");
return false;
}
var index = PackageIndex.Load(PackageIndexes.Select(pi => pi.GetMetadata("FullPath")));
// Retrieve the list of dependency group TFM's
var dependencyGroups = Dependencies
.Select(dependencyItem => new TaskItemPackageDependency(dependencyItem))
.GroupBy(dependency => dependency.TargetFramework)
.Select(dependencyGrouping => new TaskItemPackageDependencyGroup(dependencyGrouping.Key, dependencyGrouping))
.ToArray();
// Prepare a resolver for evaluating if candidate frameworks are actually supported by the package
PackageItem[] packageItems = Files.Select(f => new PackageItem(f)).ToArray();
var packagePaths = packageItems.Select(pi => pi.TargetPath);
NuGetAssetResolver resolver = new NuGetAssetResolver(null, packagePaths);
// Determine all inbox frameworks which are supported by this package
var supportedInboxFrameworks = index.GetAlllInboxFrameworks().Where(fx => IsSupported(fx, resolver));
var newDependencyGroups = new Queue<TaskItemPackageDependencyGroup>();
// For each inbox framework determine its best compatible dependency group and create an explictit group, trimming out any inbox dependencies
foreach(var supportedInboxFramework in supportedInboxFrameworks)
{
var nearestDependencyGroup = dependencyGroups.GetNearest(supportedInboxFramework);
// We found a compatible dependency group that is not the same as this framework
if (nearestDependencyGroup != null && nearestDependencyGroup.TargetFramework != supportedInboxFramework)
{
// remove all dependencies which are inbox on supportedInboxFramework
var filteredDependencies = nearestDependencyGroup.Packages.Where(d => !index.IsInbox(d.Id, supportedInboxFramework, d.AssemblyVersion)).ToArray();
newDependencyGroups.Enqueue(new TaskItemPackageDependencyGroup(supportedInboxFramework, filteredDependencies));
}
}
// Remove any redundant groups from the added set (EG: net45 and net46 with the same set of dependencies)
int groupsToCheck = newDependencyGroups.Count;
for(int i = 0; i < groupsToCheck; i++)
{
// to determine if this is a redundant group, we dequeue so that it won't be considered in the following check for nearest group.
var group = newDependencyGroups.Dequeue();
// of the remaining groups, find the most compatible one
var nearestGroup = newDependencyGroups.Concat(dependencyGroups).GetNearest(group.TargetFramework);
// either we found no compatible group,
// or the closest compatible group has different dependencies,
// or the closest compatible group is portable and this is not (Portable profiles have different framework precedence, https://github.com/NuGet/Home/issues/6483),
// keep it in the set of additions
if (nearestGroup == null ||
!group.Packages.SetEquals(nearestGroup.Packages) ||
FrameworkUtilities.IsPortableMoniker(group.TargetFramework) != FrameworkUtilities.IsPortableMoniker(nearestGroup.TargetFramework))
{
// not redundant, keep it in the queue
newDependencyGroups.Enqueue(group);
}
}
// Build the items representing added dependency groups.
List<ITaskItem> trimmedDependencies = new List<ITaskItem>();
foreach (var newDependencyGroup in newDependencyGroups)
{
if (newDependencyGroup.Packages.Count == 0)
{
// no dependencies (all inbox), use a placeholder dependency.
var item = new TaskItem(PlaceHolderDependency);
item.SetMetadata("TargetFramework", newDependencyGroup.TargetFramework.GetShortFolderName());
trimmedDependencies.Add(item);
}
else
{
foreach(var dependency in newDependencyGroup.Packages)
{
var item = new TaskItem(dependency.Item);
// emit CopiedFromTargetFramework to aide in debugging.
item.SetMetadata("CopiedFromTargetFramework", item.GetMetadata("TargetFramework"));
item.SetMetadata("TargetFramework", newDependencyGroup.TargetFramework.GetShortFolderName());
trimmedDependencies.Add(item);
}
}
}
TrimmedDependencies = trimmedDependencies.ToArray();
return !Log.HasLoggedErrors;
}
private bool IsSupported(NuGetFramework inboxFx, NuGetAssetResolver resolver)
{
var compileAssets = resolver.ResolveCompileAssets(inboxFx);
// We assume that packages will only support inbox frameworks with lib/tfm assets and not runtime specific assets.
// This effectively means we'll never reduce dependencies if a package happens to support an inbox framework with
// a RID asset, but that is OK because RID assets can only be used by nuget3 + project.json
// and we don't care about reducing dependencies for project.json because indirect dependencies are hidden.
var runtimeAssets = resolver.ResolveRuntimeAssets(inboxFx, null);
foreach (var compileAsset in compileAssets.Where(c => !NuGetAssetResolver.IsPlaceholder(c)))
{
string fileName = Path.GetFileName(compileAsset);
if (!runtimeAssets.Any(r => Path.GetFileName(r).Equals(fileName, StringComparison.OrdinalIgnoreCase)))
{
// ref with no matching lib
return false;
}
}
// Either all compile assets had matching runtime assets, or all were placeholders, make sure we have at
// least one runtime asset to cover the placeholder case
return runtimeAssets.Any();
}
/// <summary>
/// Similar to NuGet.Packaging.Core.PackageDependency but also allows for flowing the original ITaskItem.
/// </summary>
class TaskItemPackageDependency : PackageDependency
{
public TaskItemPackageDependency(ITaskItem item) : base(item.ItemSpec, TryParseVersionRange(item.GetMetadata("Version")))
{
Item = item;
TargetFramework = NuGetFramework.Parse(item.GetMetadata(nameof(TargetFramework)));
AssemblyVersion = GetAssemblyVersion(item);
}
private static VersionRange TryParseVersionRange(string versionString)
{
VersionRange value;
return VersionRange.TryParse(versionString, out value) ? value : null;
}
private static Version GetAssemblyVersion(ITaskItem dependency)
{
// If we don't have the AssemblyVersion metadata (4 part version string), fall back and use Version (3 part version string)
string versionString = dependency.GetMetadata("AssemblyVersion");
if (string.IsNullOrEmpty(versionString))
{
versionString = dependency.GetMetadata("Version");
int prereleaseIndex = versionString.IndexOf('-');
if (prereleaseIndex != -1)
{
versionString = versionString.Substring(0, prereleaseIndex);
}
}
Version assemblyVersion = FrameworkUtilities.Ensure4PartVersion(
String.IsNullOrEmpty(versionString) ?
new Version(0, 0, 0, 0) :
new Version(versionString));
return assemblyVersion;
}
public ITaskItem Item { get; }
public NuGetFramework TargetFramework { get; }
public Version AssemblyVersion { get; }
}
/// <summary>
/// An IFrameworkSpecific type that can be used with FrameworkUtilties.GetNearest.
/// This differs from NuGet.Packaging.PackageDependencyGroup in that it exposes the package dependencies as an ISet which can
/// undergo an unordered comparison with another ISet.
/// </summary>
class TaskItemPackageDependencyGroup : IFrameworkSpecific
{
public TaskItemPackageDependencyGroup(NuGetFramework targetFramework, IEnumerable<TaskItemPackageDependency> packages)
{
TargetFramework = targetFramework;
Packages = new HashSet<TaskItemPackageDependency>(packages.Where(d => d.Id != PlaceHolderDependency));
}
public NuGetFramework TargetFramework { get; }
public ISet<TaskItemPackageDependency> Packages { get; }
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Compute.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedZoneOperationsClientTest
{
[xunit::FactAttribute]
public void DeleteRequestObject()
{
moq::Mock<ZoneOperations.ZoneOperationsClient> mockGrpcClient = new moq::Mock<ZoneOperations.ZoneOperationsClient>(moq::MockBehavior.Strict);
DeleteZoneOperationRequest request = new DeleteZoneOperationRequest
{
Zone = "zone255f4ea8",
Operation = "operation615a23f7",
Project = "projectaa6ff846",
};
DeleteZoneOperationResponse expectedResponse = new DeleteZoneOperationResponse { };
mockGrpcClient.Setup(x => x.Delete(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ZoneOperationsClient client = new ZoneOperationsClientImpl(mockGrpcClient.Object, null);
DeleteZoneOperationResponse response = client.Delete(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteRequestObjectAsync()
{
moq::Mock<ZoneOperations.ZoneOperationsClient> mockGrpcClient = new moq::Mock<ZoneOperations.ZoneOperationsClient>(moq::MockBehavior.Strict);
DeleteZoneOperationRequest request = new DeleteZoneOperationRequest
{
Zone = "zone255f4ea8",
Operation = "operation615a23f7",
Project = "projectaa6ff846",
};
DeleteZoneOperationResponse expectedResponse = new DeleteZoneOperationResponse { };
mockGrpcClient.Setup(x => x.DeleteAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<DeleteZoneOperationResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ZoneOperationsClient client = new ZoneOperationsClientImpl(mockGrpcClient.Object, null);
DeleteZoneOperationResponse responseCallSettings = await client.DeleteAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
DeleteZoneOperationResponse responseCancellationToken = await client.DeleteAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void Delete()
{
moq::Mock<ZoneOperations.ZoneOperationsClient> mockGrpcClient = new moq::Mock<ZoneOperations.ZoneOperationsClient>(moq::MockBehavior.Strict);
DeleteZoneOperationRequest request = new DeleteZoneOperationRequest
{
Zone = "zone255f4ea8",
Operation = "operation615a23f7",
Project = "projectaa6ff846",
};
DeleteZoneOperationResponse expectedResponse = new DeleteZoneOperationResponse { };
mockGrpcClient.Setup(x => x.Delete(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ZoneOperationsClient client = new ZoneOperationsClientImpl(mockGrpcClient.Object, null);
DeleteZoneOperationResponse response = client.Delete(request.Project, request.Zone, request.Operation);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteAsync()
{
moq::Mock<ZoneOperations.ZoneOperationsClient> mockGrpcClient = new moq::Mock<ZoneOperations.ZoneOperationsClient>(moq::MockBehavior.Strict);
DeleteZoneOperationRequest request = new DeleteZoneOperationRequest
{
Zone = "zone255f4ea8",
Operation = "operation615a23f7",
Project = "projectaa6ff846",
};
DeleteZoneOperationResponse expectedResponse = new DeleteZoneOperationResponse { };
mockGrpcClient.Setup(x => x.DeleteAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<DeleteZoneOperationResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ZoneOperationsClient client = new ZoneOperationsClientImpl(mockGrpcClient.Object, null);
DeleteZoneOperationResponse responseCallSettings = await client.DeleteAsync(request.Project, request.Zone, request.Operation, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
DeleteZoneOperationResponse responseCancellationToken = await client.DeleteAsync(request.Project, request.Zone, request.Operation, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetRequestObject()
{
moq::Mock<ZoneOperations.ZoneOperationsClient> mockGrpcClient = new moq::Mock<ZoneOperations.ZoneOperationsClient>(moq::MockBehavior.Strict);
GetZoneOperationRequest request = new GetZoneOperationRequest
{
Zone = "zone255f4ea8",
Operation = "operation615a23f7",
Project = "projectaa6ff846",
};
Operation expectedResponse = new Operation
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
User = "userb1cb11ee",
Zone = "zone255f4ea8",
CreationTimestamp = "creation_timestamp235e59a1",
StartTime = "start_timebd8dd9c4",
OperationGroupId = "operation_group_idd2040cf0",
TargetLink = "target_link9b435dc0",
Progress = 278622268,
Error = new Error(),
EndTime = "end_time89285d30",
Region = "regionedb20d96",
OperationType = "operation_typeece9e153",
Status = Operation.Types.Status.Pending,
HttpErrorMessage = "http_error_messageb5ef3c7f",
TargetId = 6263187990225347157UL,
ClientOperationId = "client_operation_id4e51b631",
StatusMessage = "status_message2c618f86",
HttpErrorStatusCode = 1766362655,
Description = "description2cf9da67",
InsertTime = "insert_time7467185a",
SelfLink = "self_link7e87f12d",
Warnings = { new Warnings(), },
};
mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ZoneOperationsClient client = new ZoneOperationsClientImpl(mockGrpcClient.Object, null);
Operation response = client.Get(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetRequestObjectAsync()
{
moq::Mock<ZoneOperations.ZoneOperationsClient> mockGrpcClient = new moq::Mock<ZoneOperations.ZoneOperationsClient>(moq::MockBehavior.Strict);
GetZoneOperationRequest request = new GetZoneOperationRequest
{
Zone = "zone255f4ea8",
Operation = "operation615a23f7",
Project = "projectaa6ff846",
};
Operation expectedResponse = new Operation
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
User = "userb1cb11ee",
Zone = "zone255f4ea8",
CreationTimestamp = "creation_timestamp235e59a1",
StartTime = "start_timebd8dd9c4",
OperationGroupId = "operation_group_idd2040cf0",
TargetLink = "target_link9b435dc0",
Progress = 278622268,
Error = new Error(),
EndTime = "end_time89285d30",
Region = "regionedb20d96",
OperationType = "operation_typeece9e153",
Status = Operation.Types.Status.Pending,
HttpErrorMessage = "http_error_messageb5ef3c7f",
TargetId = 6263187990225347157UL,
ClientOperationId = "client_operation_id4e51b631",
StatusMessage = "status_message2c618f86",
HttpErrorStatusCode = 1766362655,
Description = "description2cf9da67",
InsertTime = "insert_time7467185a",
SelfLink = "self_link7e87f12d",
Warnings = { new Warnings(), },
};
mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Operation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ZoneOperationsClient client = new ZoneOperationsClientImpl(mockGrpcClient.Object, null);
Operation responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Operation responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void Get()
{
moq::Mock<ZoneOperations.ZoneOperationsClient> mockGrpcClient = new moq::Mock<ZoneOperations.ZoneOperationsClient>(moq::MockBehavior.Strict);
GetZoneOperationRequest request = new GetZoneOperationRequest
{
Zone = "zone255f4ea8",
Operation = "operation615a23f7",
Project = "projectaa6ff846",
};
Operation expectedResponse = new Operation
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
User = "userb1cb11ee",
Zone = "zone255f4ea8",
CreationTimestamp = "creation_timestamp235e59a1",
StartTime = "start_timebd8dd9c4",
OperationGroupId = "operation_group_idd2040cf0",
TargetLink = "target_link9b435dc0",
Progress = 278622268,
Error = new Error(),
EndTime = "end_time89285d30",
Region = "regionedb20d96",
OperationType = "operation_typeece9e153",
Status = Operation.Types.Status.Pending,
HttpErrorMessage = "http_error_messageb5ef3c7f",
TargetId = 6263187990225347157UL,
ClientOperationId = "client_operation_id4e51b631",
StatusMessage = "status_message2c618f86",
HttpErrorStatusCode = 1766362655,
Description = "description2cf9da67",
InsertTime = "insert_time7467185a",
SelfLink = "self_link7e87f12d",
Warnings = { new Warnings(), },
};
mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ZoneOperationsClient client = new ZoneOperationsClientImpl(mockGrpcClient.Object, null);
Operation response = client.Get(request.Project, request.Zone, request.Operation);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetAsync()
{
moq::Mock<ZoneOperations.ZoneOperationsClient> mockGrpcClient = new moq::Mock<ZoneOperations.ZoneOperationsClient>(moq::MockBehavior.Strict);
GetZoneOperationRequest request = new GetZoneOperationRequest
{
Zone = "zone255f4ea8",
Operation = "operation615a23f7",
Project = "projectaa6ff846",
};
Operation expectedResponse = new Operation
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
User = "userb1cb11ee",
Zone = "zone255f4ea8",
CreationTimestamp = "creation_timestamp235e59a1",
StartTime = "start_timebd8dd9c4",
OperationGroupId = "operation_group_idd2040cf0",
TargetLink = "target_link9b435dc0",
Progress = 278622268,
Error = new Error(),
EndTime = "end_time89285d30",
Region = "regionedb20d96",
OperationType = "operation_typeece9e153",
Status = Operation.Types.Status.Pending,
HttpErrorMessage = "http_error_messageb5ef3c7f",
TargetId = 6263187990225347157UL,
ClientOperationId = "client_operation_id4e51b631",
StatusMessage = "status_message2c618f86",
HttpErrorStatusCode = 1766362655,
Description = "description2cf9da67",
InsertTime = "insert_time7467185a",
SelfLink = "self_link7e87f12d",
Warnings = { new Warnings(), },
};
mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Operation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ZoneOperationsClient client = new ZoneOperationsClientImpl(mockGrpcClient.Object, null);
Operation responseCallSettings = await client.GetAsync(request.Project, request.Zone, request.Operation, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Operation responseCancellationToken = await client.GetAsync(request.Project, request.Zone, request.Operation, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void WaitRequestObject()
{
moq::Mock<ZoneOperations.ZoneOperationsClient> mockGrpcClient = new moq::Mock<ZoneOperations.ZoneOperationsClient>(moq::MockBehavior.Strict);
WaitZoneOperationRequest request = new WaitZoneOperationRequest
{
Zone = "zone255f4ea8",
Operation = "operation615a23f7",
Project = "projectaa6ff846",
};
Operation expectedResponse = new Operation
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
User = "userb1cb11ee",
Zone = "zone255f4ea8",
CreationTimestamp = "creation_timestamp235e59a1",
StartTime = "start_timebd8dd9c4",
OperationGroupId = "operation_group_idd2040cf0",
TargetLink = "target_link9b435dc0",
Progress = 278622268,
Error = new Error(),
EndTime = "end_time89285d30",
Region = "regionedb20d96",
OperationType = "operation_typeece9e153",
Status = Operation.Types.Status.Pending,
HttpErrorMessage = "http_error_messageb5ef3c7f",
TargetId = 6263187990225347157UL,
ClientOperationId = "client_operation_id4e51b631",
StatusMessage = "status_message2c618f86",
HttpErrorStatusCode = 1766362655,
Description = "description2cf9da67",
InsertTime = "insert_time7467185a",
SelfLink = "self_link7e87f12d",
Warnings = { new Warnings(), },
};
mockGrpcClient.Setup(x => x.Wait(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ZoneOperationsClient client = new ZoneOperationsClientImpl(mockGrpcClient.Object, null);
Operation response = client.Wait(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task WaitRequestObjectAsync()
{
moq::Mock<ZoneOperations.ZoneOperationsClient> mockGrpcClient = new moq::Mock<ZoneOperations.ZoneOperationsClient>(moq::MockBehavior.Strict);
WaitZoneOperationRequest request = new WaitZoneOperationRequest
{
Zone = "zone255f4ea8",
Operation = "operation615a23f7",
Project = "projectaa6ff846",
};
Operation expectedResponse = new Operation
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
User = "userb1cb11ee",
Zone = "zone255f4ea8",
CreationTimestamp = "creation_timestamp235e59a1",
StartTime = "start_timebd8dd9c4",
OperationGroupId = "operation_group_idd2040cf0",
TargetLink = "target_link9b435dc0",
Progress = 278622268,
Error = new Error(),
EndTime = "end_time89285d30",
Region = "regionedb20d96",
OperationType = "operation_typeece9e153",
Status = Operation.Types.Status.Pending,
HttpErrorMessage = "http_error_messageb5ef3c7f",
TargetId = 6263187990225347157UL,
ClientOperationId = "client_operation_id4e51b631",
StatusMessage = "status_message2c618f86",
HttpErrorStatusCode = 1766362655,
Description = "description2cf9da67",
InsertTime = "insert_time7467185a",
SelfLink = "self_link7e87f12d",
Warnings = { new Warnings(), },
};
mockGrpcClient.Setup(x => x.WaitAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Operation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ZoneOperationsClient client = new ZoneOperationsClientImpl(mockGrpcClient.Object, null);
Operation responseCallSettings = await client.WaitAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Operation responseCancellationToken = await client.WaitAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void Wait()
{
moq::Mock<ZoneOperations.ZoneOperationsClient> mockGrpcClient = new moq::Mock<ZoneOperations.ZoneOperationsClient>(moq::MockBehavior.Strict);
WaitZoneOperationRequest request = new WaitZoneOperationRequest
{
Zone = "zone255f4ea8",
Operation = "operation615a23f7",
Project = "projectaa6ff846",
};
Operation expectedResponse = new Operation
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
User = "userb1cb11ee",
Zone = "zone255f4ea8",
CreationTimestamp = "creation_timestamp235e59a1",
StartTime = "start_timebd8dd9c4",
OperationGroupId = "operation_group_idd2040cf0",
TargetLink = "target_link9b435dc0",
Progress = 278622268,
Error = new Error(),
EndTime = "end_time89285d30",
Region = "regionedb20d96",
OperationType = "operation_typeece9e153",
Status = Operation.Types.Status.Pending,
HttpErrorMessage = "http_error_messageb5ef3c7f",
TargetId = 6263187990225347157UL,
ClientOperationId = "client_operation_id4e51b631",
StatusMessage = "status_message2c618f86",
HttpErrorStatusCode = 1766362655,
Description = "description2cf9da67",
InsertTime = "insert_time7467185a",
SelfLink = "self_link7e87f12d",
Warnings = { new Warnings(), },
};
mockGrpcClient.Setup(x => x.Wait(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ZoneOperationsClient client = new ZoneOperationsClientImpl(mockGrpcClient.Object, null);
Operation response = client.Wait(request.Project, request.Zone, request.Operation);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task WaitAsync()
{
moq::Mock<ZoneOperations.ZoneOperationsClient> mockGrpcClient = new moq::Mock<ZoneOperations.ZoneOperationsClient>(moq::MockBehavior.Strict);
WaitZoneOperationRequest request = new WaitZoneOperationRequest
{
Zone = "zone255f4ea8",
Operation = "operation615a23f7",
Project = "projectaa6ff846",
};
Operation expectedResponse = new Operation
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
User = "userb1cb11ee",
Zone = "zone255f4ea8",
CreationTimestamp = "creation_timestamp235e59a1",
StartTime = "start_timebd8dd9c4",
OperationGroupId = "operation_group_idd2040cf0",
TargetLink = "target_link9b435dc0",
Progress = 278622268,
Error = new Error(),
EndTime = "end_time89285d30",
Region = "regionedb20d96",
OperationType = "operation_typeece9e153",
Status = Operation.Types.Status.Pending,
HttpErrorMessage = "http_error_messageb5ef3c7f",
TargetId = 6263187990225347157UL,
ClientOperationId = "client_operation_id4e51b631",
StatusMessage = "status_message2c618f86",
HttpErrorStatusCode = 1766362655,
Description = "description2cf9da67",
InsertTime = "insert_time7467185a",
SelfLink = "self_link7e87f12d",
Warnings = { new Warnings(), },
};
mockGrpcClient.Setup(x => x.WaitAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Operation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ZoneOperationsClient client = new ZoneOperationsClientImpl(mockGrpcClient.Object, null);
Operation responseCallSettings = await client.WaitAsync(request.Project, request.Zone, request.Operation, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Operation responseCancellationToken = await client.WaitAsync(request.Project, request.Zone, request.Operation, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// Sundry Debtor Fee Groups Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class SDGDataSet : EduHubDataSet<SDG>
{
/// <inheritdoc />
public override string Name { get { return "SDG"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal SDGDataSet(EduHubContext Context)
: base(Context)
{
Index_SDGKEY = new Lazy<Dictionary<string, SDG>>(() => this.ToDictionary(i => i.SDGKEY));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="SDG" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="SDG" /> fields for each CSV column header</returns>
internal override Action<SDG, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<SDG, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "SDGKEY":
mapper[i] = (e, v) => e.SDGKEY = v;
break;
case "DESCRIPTION":
mapper[i] = (e, v) => e.DESCRIPTION = v;
break;
case "MEMBER_TYPE":
mapper[i] = (e, v) => e.MEMBER_TYPE = v;
break;
case "SDG_MEMO":
mapper[i] = (e, v) => e.SDG_MEMO = v;
break;
case "LW_DATE":
mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_TIME":
mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "LW_USER":
mapper[i] = (e, v) => e.LW_USER = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="SDG" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="SDG" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="SDG" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{SDG}"/> of entities</returns>
internal override IEnumerable<SDG> ApplyDeltaEntities(IEnumerable<SDG> Entities, List<SDG> DeltaEntities)
{
HashSet<string> Index_SDGKEY = new HashSet<string>(DeltaEntities.Select(i => i.SDGKEY));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.SDGKEY;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_SDGKEY.Remove(entity.SDGKEY);
if (entity.SDGKEY.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<Dictionary<string, SDG>> Index_SDGKEY;
#endregion
#region Index Methods
/// <summary>
/// Find SDG by SDGKEY field
/// </summary>
/// <param name="SDGKEY">SDGKEY value used to find SDG</param>
/// <returns>Related SDG entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public SDG FindBySDGKEY(string SDGKEY)
{
return Index_SDGKEY.Value[SDGKEY];
}
/// <summary>
/// Attempt to find SDG by SDGKEY field
/// </summary>
/// <param name="SDGKEY">SDGKEY value used to find SDG</param>
/// <param name="Value">Related SDG entity</param>
/// <returns>True if the related SDG entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindBySDGKEY(string SDGKEY, out SDG Value)
{
return Index_SDGKEY.Value.TryGetValue(SDGKEY, out Value);
}
/// <summary>
/// Attempt to find SDG by SDGKEY field
/// </summary>
/// <param name="SDGKEY">SDGKEY value used to find SDG</param>
/// <returns>Related SDG entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public SDG TryFindBySDGKEY(string SDGKEY)
{
SDG value;
if (Index_SDGKEY.Value.TryGetValue(SDGKEY, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a SDG table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[SDG]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[SDG](
[SDGKEY] varchar(12) NOT NULL,
[DESCRIPTION] varchar(30) NULL,
[MEMBER_TYPE] varchar(1) NULL,
[SDG_MEMO] varchar(MAX) NULL,
[LW_DATE] datetime NULL,
[LW_TIME] smallint NULL,
[LW_USER] varchar(128) NULL,
CONSTRAINT [SDG_Index_SDGKEY] PRIMARY KEY CLUSTERED (
[SDGKEY] ASC
)
);
END");
}
/// <summary>
/// Returns null as <see cref="SDGDataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns null as <see cref="SDGDataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="SDG"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="SDG"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<SDG> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<string> Index_SDGKEY = new List<string>();
foreach (var entity in Entities)
{
Index_SDGKEY.Add(entity.SDGKEY);
}
builder.AppendLine("DELETE [dbo].[SDG] WHERE");
// Index_SDGKEY
builder.Append("[SDGKEY] IN (");
for (int index = 0; index < Index_SDGKEY.Count; index++)
{
if (index != 0)
builder.Append(", ");
// SDGKEY
var parameterSDGKEY = $"@p{parameterIndex++}";
builder.Append(parameterSDGKEY);
command.Parameters.Add(parameterSDGKEY, SqlDbType.VarChar, 12).Value = Index_SDGKEY[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the SDG data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the SDG data set</returns>
public override EduHubDataSetDataReader<SDG> GetDataSetDataReader()
{
return new SDGDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the SDG data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the SDG data set</returns>
public override EduHubDataSetDataReader<SDG> GetDataSetDataReader(List<SDG> Entities)
{
return new SDGDataReader(new EduHubDataSetLoadedReader<SDG>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class SDGDataReader : EduHubDataSetDataReader<SDG>
{
public SDGDataReader(IEduHubDataSetReader<SDG> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 7; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // SDGKEY
return Current.SDGKEY;
case 1: // DESCRIPTION
return Current.DESCRIPTION;
case 2: // MEMBER_TYPE
return Current.MEMBER_TYPE;
case 3: // SDG_MEMO
return Current.SDG_MEMO;
case 4: // LW_DATE
return Current.LW_DATE;
case 5: // LW_TIME
return Current.LW_TIME;
case 6: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 1: // DESCRIPTION
return Current.DESCRIPTION == null;
case 2: // MEMBER_TYPE
return Current.MEMBER_TYPE == null;
case 3: // SDG_MEMO
return Current.SDG_MEMO == null;
case 4: // LW_DATE
return Current.LW_DATE == null;
case 5: // LW_TIME
return Current.LW_TIME == null;
case 6: // LW_USER
return Current.LW_USER == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // SDGKEY
return "SDGKEY";
case 1: // DESCRIPTION
return "DESCRIPTION";
case 2: // MEMBER_TYPE
return "MEMBER_TYPE";
case 3: // SDG_MEMO
return "SDG_MEMO";
case 4: // LW_DATE
return "LW_DATE";
case 5: // LW_TIME
return "LW_TIME";
case 6: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "SDGKEY":
return 0;
case "DESCRIPTION":
return 1;
case "MEMBER_TYPE":
return 2;
case "SDG_MEMO":
return 3;
case "LW_DATE":
return 4;
case "LW_TIME":
return 5;
case "LW_USER":
return 6;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#if FEATURE_XML_SCHEMA_VALIDATION
using System;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Threading;
using System.Xml;
using Microsoft.Build.CommandLine;
using Microsoft.Build.Framework;
using Microsoft.Build.Shared;
using Xunit;
namespace Microsoft.Build.UnitTests
{
public class ProjectSchemaValidationHandlerTest
{
/***********************************************************************
*
* Test: ProjectSchemaValidationHandlerTest.VerifyProjectSchema
*
* This calls VerifyProjectSchema to validate a project file passed, where
* the project contents are invalid
*
**********************************************************************/
[Fact]
public void VerifyInvalidProjectSchema
(
)
{
string[] msbuildTempXsdFilenames = new string[] { };
string projectFilename = null;
string oldValueForMSBuildOldOM = null;
try
{
oldValueForMSBuildOldOM = Environment.GetEnvironmentVariable("MSBuildOldOM");
Environment.SetEnvironmentVariable("MSBuildOldOM", "");
// Create schema files in the temp folder
msbuildTempXsdFilenames = PrepareSchemaFiles();
projectFilename = CreateTempFileOnDisk(@"
<Project xmlns=`msbuildnamespace`>
<PropertyGroup>
<MyInvalidProperty/>
</PropertyGroup>
<Target Name=`Build` />
</Project>
");
string quotedProjectFilename = "\"" + projectFilename + "\"";
Assert.Equal(MSBuildApp.ExitType.InitializationError, MSBuildApp.Execute(@"c:\foo\msbuild.exe " + quotedProjectFilename + " /validate:\"" + msbuildTempXsdFilenames[0] + "\""));
}
finally
{
if (projectFilename != null) File.Delete(projectFilename);
CleanupSchemaFiles(msbuildTempXsdFilenames);
Environment.SetEnvironmentVariable("MSBuildOldOM", oldValueForMSBuildOldOM);
}
}
/// <summary>
/// Checks that an exception is thrown when the schema being validated
/// against is itself invalid
/// </summary>
[Fact]
public void VerifyInvalidSchemaItself1
(
)
{
string invalidSchemaFile = null;
string projectFilename = null;
string oldValueForMSBuildOldOM = null;
try
{
oldValueForMSBuildOldOM = Environment.GetEnvironmentVariable("MSBuildOldOM");
Environment.SetEnvironmentVariable("MSBuildOldOM", "");
// Create schema files in the temp folder
invalidSchemaFile = FileUtilities.GetTemporaryFile();
File.WriteAllText(invalidSchemaFile, "<this_is_invalid_schema_content/>");
projectFilename = CreateTempFileOnDisk(@"
<Project xmlns=`msbuildnamespace`>
<Target Name=`Build` />
</Project>
");
string quotedProjectFile = "\"" + projectFilename + "\"";
Assert.Equal(MSBuildApp.ExitType.InitializationError, MSBuildApp.Execute(@"c:\foo\msbuild.exe " + quotedProjectFile + " /validate:\"" + invalidSchemaFile + "\""));
}
finally
{
if (projectFilename != null) File.Delete(projectFilename);
if (invalidSchemaFile != null) File.Delete(invalidSchemaFile);
Environment.SetEnvironmentVariable("MSBuildOldOM", oldValueForMSBuildOldOM);
}
}
/// <summary>
/// Checks that an exception is thrown when the schema being validated
/// against is itself invalid
/// </summary>
[Fact]
public void VerifyInvalidSchemaItself2
(
)
{
string invalidSchemaFile = null;
string projectFilename = null;
string oldValueForMSBuildOldOM = null;
try
{
oldValueForMSBuildOldOM = Environment.GetEnvironmentVariable("MSBuildOldOM");
Environment.SetEnvironmentVariable("MSBuildOldOM", "");
// Create schema files in the temp folder
invalidSchemaFile = FileUtilities.GetTemporaryFile();
File.WriteAllText(invalidSchemaFile, @"<?xml version=""1.0"" encoding=""UTF-8""?>
<xs:schema targetNamespace=""http://schemas.microsoft.com/developer/msbuild/2003"" xmlns:msb=""http://schemas.microsoft.com/developer/msbuild/2003"" xmlns:xs=""http://www.w3.org/2001/XMLSchema"" elementFormDefault=""qualified"">
<xs:element name=""Project"">
<xs:complexType>
<xs:sequence>
<xs:group ref=""x"" minOccurs=""0"" maxOccurs=""unbounded""/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
");
projectFilename = CreateTempFileOnDisk(@"
<Project xmlns=`msbuildnamespace`>
<Target Name=`Build` />
</Project>
");
string quotedProjectFile = "\"" + projectFilename + "\"";
Assert.Equal(MSBuildApp.ExitType.InitializationError, MSBuildApp.Execute(@"c:\foo\msbuild.exe " + quotedProjectFile + " /validate:\"" + invalidSchemaFile + "\""));
}
finally
{
if (invalidSchemaFile != null) File.Delete(invalidSchemaFile);
if (projectFilename != null) File.Delete(projectFilename);
Environment.SetEnvironmentVariable("MSBuildOldOM", oldValueForMSBuildOldOM);
}
}
/***********************************************************************
*
* Test: ProjectSchemaValidationHandlerTest.VerifyProjectSchema
*
* This calls VerifyProjectSchema to validate a project XML
* specified in a string, where the project passed is valid
*
**********************************************************************/
[Fact]
public void VerifyValidProjectSchema
(
)
{
string[] msbuildTempXsdFilenames = new string[] { };
string projectFilename = CreateTempFileOnDisk(@"
<Project xmlns=`msbuildnamespace`>
<Target Name=`Build` />
</Project>
");
string oldValueForMSBuildOldOM = null;
try
{
oldValueForMSBuildOldOM = Environment.GetEnvironmentVariable("MSBuildOldOM");
Environment.SetEnvironmentVariable("MSBuildOldOM", "");
// Create schema files in the temp folder
msbuildTempXsdFilenames = PrepareSchemaFiles();
string quotedProjectFile = "\"" + projectFilename + "\"";
Assert.Equal(MSBuildApp.ExitType.Success, MSBuildApp.Execute(@"c:\foo\msbuild.exe " + quotedProjectFile + " /validate:\"" + msbuildTempXsdFilenames[0] + "\""));
//ProjectSchemaValidationHandler.VerifyProjectSchema
// (
// projectFilename,
// msbuildTempXsdFilenames[0],
// @"c:\"
// );
}
finally
{
File.Delete(projectFilename);
CleanupSchemaFiles(msbuildTempXsdFilenames);
Environment.SetEnvironmentVariable("MSBuildOldOM", oldValueForMSBuildOldOM);
}
}
/// <summary>
/// The test has a valid project file, importing an invalid project file.
/// We should not validate imported files against the schema in V1, so this
/// should not be caught by the schema
/// </summary>
[Fact]
public void VerifyInvalidImportNotCaughtBySchema
(
)
{
string[] msbuildTempXsdFilenames = new string[] { };
string importedProjectFilename = CreateTempFileOnDisk(@"
<Project xmlns=`msbuildnamespace`>
<PropertyGroup><UnknownProperty/></PropertyGroup>
<Target Name=`Build` />
</Project>
");
string projectFilename = CreateTempFileOnDisk(@"
<Project xmlns=`msbuildnamespace`>
<Import Project=`{0}` />
</Project>
", importedProjectFilename);
string oldValueForMSBuildOldOM = null;
try
{
oldValueForMSBuildOldOM = Environment.GetEnvironmentVariable("MSBuildOldOM");
Environment.SetEnvironmentVariable("MSBuildOldOM", "");
// Create schema files in the temp folder
msbuildTempXsdFilenames = PrepareSchemaFiles();
string quotedProjectFile = "\"" + projectFilename + "\"";
Assert.Equal(MSBuildApp.ExitType.Success, MSBuildApp.Execute(@"c:\foo\msbuild.exe " + quotedProjectFile + " /validate:\"" + msbuildTempXsdFilenames[0] + "\""));
//ProjectSchemaValidationHandler.VerifyProjectSchema
// (
// projectFilename,
// msbuildTempXsdFilenames[0],
// @"c:\"
// );
}
finally
{
CleanupSchemaFiles(msbuildTempXsdFilenames);
File.Delete(projectFilename);
File.Delete(importedProjectFilename);
Environment.SetEnvironmentVariable("MSBuildOldOM", oldValueForMSBuildOldOM);
}
}
#region Helper Functions
/// <summary>
/// MSBuild schemas are embedded as a resource into Microsoft.Build.Engine.UnitTests.dll.
/// Extract the stream from the resource and write the XSDs out to a temporary file,
/// so that our schema validator can access it.
/// </summary>
private string[] PrepareSchemaFiles()
{
string msbuildXsdRootDirectory = Path.GetTempPath();
Directory.CreateDirectory(msbuildXsdRootDirectory);
Stream msbuildXsdStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Microsoft.Build.CommandLine.UnitTests.Microsoft.Build.xsd");
StreamReader msbuildXsdStreamReader = new StreamReader(msbuildXsdStream);
string msbuildXsdContents = msbuildXsdStreamReader.ReadToEnd();
string msbuildTempXsdFilename = Path.Combine(msbuildXsdRootDirectory, "Microsoft.Build.xsd");
File.WriteAllText(msbuildTempXsdFilename, msbuildXsdContents);
string msbuildXsdSubDirectory = Path.Combine(msbuildXsdRootDirectory, "MSBuild");
Directory.CreateDirectory(msbuildXsdSubDirectory);
msbuildXsdStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Microsoft.Build.CommandLine.UnitTests.Microsoft.Build.Core.xsd");
msbuildXsdStreamReader = new StreamReader(msbuildXsdStream);
msbuildXsdContents = msbuildXsdStreamReader.ReadToEnd();
string msbuildTempXsdFilename2 = Path.Combine(msbuildXsdSubDirectory, "Microsoft.Build.Core.xsd");
File.WriteAllText(msbuildTempXsdFilename2, msbuildXsdContents);
msbuildXsdStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Microsoft.Build.CommandLine.UnitTests.Microsoft.Build.CommonTypes.xsd");
msbuildXsdStreamReader = new StreamReader(msbuildXsdStream);
msbuildXsdContents = msbuildXsdStreamReader.ReadToEnd();
string msbuildTempXsdFilename3 = Path.Combine(msbuildXsdSubDirectory, "Microsoft.Build.CommonTypes.xsd");
File.WriteAllText(msbuildTempXsdFilename3, msbuildXsdContents);
return new string[] { msbuildTempXsdFilename, msbuildTempXsdFilename2, msbuildTempXsdFilename3 };
}
/// <summary>
/// Gets rid of the temporary files created to hold the schemas for the duration
/// of these unit tests.
/// </summary>
private void CleanupSchemaFiles(string[] msbuildTempXsdFilenames)
{
foreach (string file in msbuildTempXsdFilenames)
{
if (File.Exists(file))
{
File.Delete(file);
}
}
string msbuildXsdSubDirectory = Path.Combine(Path.GetTempPath(), "MSBuild");
if (Directory.Exists(msbuildXsdSubDirectory))
{
for (int i = 0; i < 5; i++)
{
try
{
FileUtilities.DeleteWithoutTrailingBackslash(msbuildXsdSubDirectory, true /* recursive */);
break;
}
catch (Exception)
{
Thread.Sleep(1000);
// Eat exceptions from the delete
}
}
}
}
/// <summary>
/// Create an MSBuild project file on disk and return the full path to it.
/// </summary>
/// <remarks>Stolen from ObjectModelHelpers because we use relatively little
/// of the ObjectModelHelpers functionality, so as to avoid having to include in
/// this project everything that ObjectModelHelpers depends on</remarks>
static internal string CreateTempFileOnDisk(string fileContents, params object[] args)
{
return CreateTempFileOnDiskNoFormat(String.Format(fileContents, args));
}
/// <summary>
/// Create an MSBuild project file on disk and return the full path to it.
/// </summary>
/// <remarks>Stolen from ObjectModelHelpers because we use relatively little
/// of the ObjectModelHelpers functionality, so as to avoid having to include in
/// this project everything that ObjectModelHelpers depends on</remarks>
static internal string CreateTempFileOnDiskNoFormat(string fileContents)
{
string projectFilePath = FileUtilities.GetTemporaryFile();
File.WriteAllText(projectFilePath, CleanupFileContents(fileContents));
return projectFilePath;
}
/// <summary>
/// Does certain replacements in a string representing the project file contents.
/// This makes it easier to write unit tests because the author doesn't have
/// to worry about escaping double-quotes, etc.
/// </summary>
/// <remarks>Stolen from ObjectModelHelpers because we use relatively little
/// of the ObjectModelHelpers functionality, so as to avoid having to include in
/// this project everything that ObjectModelHelpers depends on</remarks>
static private string CleanupFileContents(string projectFileContents)
{
// Replace reverse-single-quotes with double-quotes.
projectFileContents = projectFileContents.Replace("`", "\"");
// Place the correct MSBuild namespace into the <Project> tag.
projectFileContents = projectFileContents.Replace("msbuildnamespace", msbuildNamespace);
projectFileContents = projectFileContents.Replace("msbuilddefaulttoolsversion", msbuildDefaultToolsVersion);
return projectFileContents;
}
private const string msbuildNamespace = "http://schemas.microsoft.com/developer/msbuild/2003";
private const string msbuildDefaultToolsVersion = "4.0";
#endregion // Helper Functions
}
}
#endif
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
namespace System.ServiceModel.Description
{
[DebuggerDisplay("Name={_name}, IsInitiating={_isInitiating}, IsTerminating={_isTerminating}")]
public class OperationDescription
{
internal const string SessionOpenedAction = Channels.WebSocketTransportSettings.ConnectionOpenedAction;
private XmlName _name;
private bool _isInitiating;
private bool _isTerminating;
private bool _isSessionOpenNotificationEnabled;
private ContractDescription _declaringContract;
private FaultDescriptionCollection _faults;
private MessageDescriptionCollection _messages;
private KeyedByTypeCollection<IOperationBehavior> _behaviors;
private Collection<Type> _knownTypes;
private MethodInfo _beginMethod;
private MethodInfo _endMethod;
private MethodInfo _syncMethod;
private MethodInfo _taskMethod;
private bool _validateRpcWrapperName = true;
private bool _hasNoDisposableParameters;
public OperationDescription(string name, ContractDescription declaringContract)
{
if (name == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("name");
}
if (name.Length == 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentOutOfRangeException("name", SR.SFxOperationDescriptionNameCannotBeEmpty));
}
_name = new XmlName(name, true /*isEncoded*/);
if (declaringContract == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("declaringContract");
}
_declaringContract = declaringContract;
_isInitiating = true;
_isTerminating = false;
_faults = new FaultDescriptionCollection();
_messages = new MessageDescriptionCollection();
_behaviors = new KeyedByTypeCollection<IOperationBehavior>();
_knownTypes = new Collection<Type>();
}
internal OperationDescription(string name, ContractDescription declaringContract, bool validateRpcWrapperName)
: this(name, declaringContract)
{
_validateRpcWrapperName = validateRpcWrapperName;
}
public KeyedCollection<Type, IOperationBehavior> OperationBehaviors
{
get { return this.Behaviors; }
}
[EditorBrowsable(EditorBrowsableState.Never)]
public KeyedByTypeCollection<IOperationBehavior> Behaviors
{
get { return _behaviors; }
}
// Not serializable on purpose, metadata import/export cannot
// produce it, only available when binding to runtime
public MethodInfo TaskMethod
{
get { return _taskMethod; }
set { _taskMethod = value; }
}
// Not serializable on purpose, metadata import/export cannot
// produce it, only available when binding to runtime
public MethodInfo SyncMethod
{
get { return _syncMethod; }
set { _syncMethod = value; }
}
// Not serializable on purpose, metadata import/export cannot
// produce it, only available when binding to runtime
public MethodInfo BeginMethod
{
get { return _beginMethod; }
set { _beginMethod = value; }
}
internal MethodInfo OperationMethod
{
get
{
if (this.SyncMethod == null)
{
return this.TaskMethod ?? this.BeginMethod;
}
else
{
return this.SyncMethod;
}
}
}
internal bool HasNoDisposableParameters
{
get { return _hasNoDisposableParameters; }
set { _hasNoDisposableParameters = value; }
}
// Not serializable on purpose, metadata import/export cannot
// produce it, only available when binding to runtime
public MethodInfo EndMethod
{
get { return _endMethod; }
set { _endMethod = value; }
}
public ContractDescription DeclaringContract
{
get { return _declaringContract; }
set
{
if (value == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("DeclaringContract");
}
else
{
_declaringContract = value;
}
}
}
public FaultDescriptionCollection Faults
{
get { return _faults; }
}
public bool IsOneWay
{
get { return this.Messages.Count == 1; }
}
public bool IsInitiating
{
get { return _isInitiating; }
set { _isInitiating = value; }
}
internal bool IsServerInitiated()
{
EnsureInvariants();
return Messages[0].Direction == MessageDirection.Output;
}
public bool IsTerminating
{
get { return _isTerminating; }
set { _isTerminating = value; }
}
public Collection<Type> KnownTypes
{
get { return _knownTypes; }
}
// Messages[0] is the 'request' (first of MEP), and for non-oneway MEPs, Messages[1] is the 'response' (second of MEP)
public MessageDescriptionCollection Messages
{
get { return _messages; }
}
internal XmlName XmlName
{
get { return _name; }
}
internal string CodeName
{
get { return _name.DecodedName; }
}
public string Name
{
get { return _name.EncodedName; }
}
internal bool IsValidateRpcWrapperName { get { return _validateRpcWrapperName; } }
//This property is set during contract inference in a hosted workflow scenario. This is required to handle correct
//transactional invocation from the dispatcher in regards to scenarios involving the TransactedReceiveScope activity
internal bool IsInsideTransactedReceiveScope
{
get;
set;
}
//This property is set during contract inference in a hosted workflow scenario. This is required to handle correct
//transactional invocation from the dispatcher in regards to scenarios involving the TransactedReceiveScope activity
internal bool IsFirstReceiveOfTransactedReceiveScopeTree
{
get;
set;
}
internal Type TaskTResult
{
get;
set;
}
internal bool HasOutputParameters
{
get
{
// For non-oneway operations, Messages[1] is the 'response'
return (this.Messages.Count > 1) &&
(this.Messages[1].Body.Parts.Count > 0);
}
}
internal bool IsSessionOpenNotificationEnabled
{
get { return _isSessionOpenNotificationEnabled; }
set { _isSessionOpenNotificationEnabled = value; }
}
internal void EnsureInvariants()
{
if (this.Messages.Count != 1 && this.Messages.Count != 2)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new System.InvalidOperationException(SR.Format(SR.SFxOperationMustHaveOneOrTwoMessages, this.Name)));
}
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace Microsoft.Build.Tasks.Xaml
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime;
using System.Threading;
using System.Xaml;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Microsoft.VisualStudio.Activities;
[Fx.Tag.XamlVisible(true)]
public class PartialClassGenerationTask : Task
{
const string DefaultGeneratedSourceExtension = "g";
List<ITaskItem> generatedResources = new List<ITaskItem>();
List<ITaskItem> generatedCodeFiles = new List<ITaskItem>();
// We will do Dev10 behavior if the new required property MSBuildProjectDirectory is NOT specified. This can happen
// if a Dev10 version of the Microsoft.Xaml.Targets file is being used with Dev11 installed.
bool supportExtensions = false;
string msBuildProjectDirectory;
public PartialClassGenerationTask()
{
this.GeneratedSourceExtension = DefaultGeneratedSourceExtension;
}
[Fx.Tag.KnownXamlExternal]
[Output]
public ITaskItem[] ApplicationMarkup { get; set; }
public string AssemblyName
{ get; set; }
public string[] KnownReferencePaths { get; set; }
[Fx.Tag.KnownXamlExternal]
[Output]
public ITaskItem[] GeneratedResources
{
get
{
return generatedResources.ToArray();
}
set
{
generatedResources = new List<ITaskItem>(value);
}
}
[Fx.Tag.KnownXamlExternal]
[Output]
public ITaskItem[] GeneratedCodeFiles
{
get
{
return generatedCodeFiles.ToArray();
}
set
{
generatedCodeFiles = new List<ITaskItem>(value);
}
}
public string GeneratedSourceExtension
{ get; set; }
[Required]
public string Language
{ get; set; }
[Required]
public string OutputPath
{ get; set; }
// This is Required for Dev11, but to allow things to work with a Dev10 targets file, we are not marking it required.
public string MSBuildProjectDirectory
{
get
{
return this.msBuildProjectDirectory;
}
set
{
this.msBuildProjectDirectory = value;
// The fact that this property is being set indicates that a Dev11 version of the targets
// file is being used, so we should not do Dev10 behavior.
this.supportExtensions = true;
}
}
[Fx.Tag.KnownXamlExternal]
public ITaskItem[] References
{ get; set; }
public string RootNamespace
{ get; set; }
[Fx.Tag.KnownXamlExternal]
public ITaskItem[] SourceCodeFiles
{ get; set; }
[Output]
public bool RequiresCompilationPass2
{ get; set; }
public string BuildTaskPath
{ get; set; }
public bool IsInProcessXamlMarkupCompile
{ get; set; }
public ITaskItem[] XamlBuildTypeGenerationExtensionNames
{ get; set; }
public ITaskItem[] XamlBuildTypeInspectionExtensionNames
{ get; set; }
private static AppDomain inProcessAppDomain;
private static Dictionary<string, DateTime> referencesTimeStampCache;
private Object referencesCacheLock = new Object();
public override bool Execute()
{
VSDesignerPerfEventProvider perfEventProvider = new VSDesignerPerfEventProvider();
perfEventProvider.WriteEvent(VSDesignerPerfEvents.XamlBuildTaskExecuteStart);
try
{
if (IsInProcessXamlMarkupCompile)
{
bool acquiredLock = false;
try
{
Monitor.TryEnter(referencesCacheLock, ref acquiredLock);
if (acquiredLock)
{
return ReuseAppDomainAndExecute();
}
else
{
return GetAppDomainAndExecute();
}
}
finally
{
if (acquiredLock)
{
Monitor.Exit(referencesCacheLock);
}
}
}
else
{
return GetAppDomainAndExecute();
}
}
finally
{
perfEventProvider.WriteEvent(VSDesignerPerfEvents.XamlBuildTaskExecuteEnd);
}
}
bool ReuseAppDomainAndExecute()
{
AppDomain appDomain = null;
bool createdNewAppDomain = false;
try
{
try
{
appDomain = GetInProcessAppDomain(out createdNewAppDomain);
bool ret = ExecuteInternal(appDomain);
return ret;
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
if (createdNewAppDomain)
{
XamlBuildTaskServices.LogException(this.Log, e.Message);
return false;
}
else
{
AppDomain.Unload(inProcessAppDomain);
inProcessAppDomain = null;
return GetAppDomainAndExecute();
}
}
}
finally
{
if (Log != null)
{
Log.MarkAsInactive();
}
}
}
bool GetAppDomainAndExecute()
{
AppDomain appDomain = null;
try
{
appDomain = CreateNewAppDomain();
bool ret = ExecuteInternal(appDomain);
return ret;
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
XamlBuildTaskServices.LogException(this.Log, e.Message);
return false;
}
finally
{
if (appDomain != null)
{
AppDomain.Unload(appDomain);
}
}
}
bool ExecuteInternal(AppDomain appDomain)
{
PartialClassGenerationTaskInternal wrapper = (PartialClassGenerationTaskInternal)appDomain.CreateInstanceAndUnwrap(
Assembly.GetExecutingAssembly().FullName,
typeof(PartialClassGenerationTaskInternal).FullName);
PopulateBuildArtifacts(wrapper);
bool ret = wrapper.Execute();
if (ret)
{
ExtractBuiltArtifacts(wrapper);
}
return ret;
}
AppDomain CreateNewAppDomain()
{
return XamlBuildTaskServices.CreateAppDomain("PartialClassAppDomain_" + Guid.NewGuid(), BuildTaskPath);
}
// For Intellisense builds, we re-use the AppDomain for successive builds instead of creating a new one every time,
// if the references have not changed (there are no new references and they have not been updated since the last build)
// This method accesses the static referencesTimeStampCache (indirectly).
// To ensure thread safety, this method should be called inside a lock/monitor
AppDomain GetInProcessAppDomain(out bool newAppDomain)
{
newAppDomain = false;
if (inProcessAppDomain == null)
{
inProcessAppDomain = CreateNewAppDomain();
newAppDomain = true;
UpdateReferenceCache();
}
else if (AreReferencesChanged())
{
AppDomain.Unload(inProcessAppDomain);
inProcessAppDomain = CreateNewAppDomain();
newAppDomain = true;
UpdateReferenceCache();
}
return inProcessAppDomain;
}
// This method accesses the static referencesTimeStampCache.
// To ensure thread safety, this method should be called inside a lock/monitor
bool AreReferencesChanged()
{
bool refsChanged = false;
if (referencesTimeStampCache == null || referencesTimeStampCache.Count != References.Length)
{
refsChanged = true;
}
else
{
foreach (var reference in References)
{
string fullPath = Path.GetFullPath(reference.ItemSpec);
DateTime timeStamp = File.GetLastWriteTimeUtc(fullPath);
if (!referencesTimeStampCache.ContainsKey(fullPath)
|| timeStamp > referencesTimeStampCache[fullPath]
|| timeStamp == DateTime.MinValue)
{
refsChanged = true;
break;
}
}
}
return refsChanged;
}
// This method accesses the static referencesTimeStampCache.
// To ensure thread safety, this method should be called inside a lock/monitor
void UpdateReferenceCache()
{
referencesTimeStampCache = new Dictionary<string, DateTime>();
foreach (var reference in References)
{
string fullPath = Path.GetFullPath(reference.ItemSpec);
DateTime timeStamp = File.GetLastWriteTimeUtc(fullPath);
referencesTimeStampCache.Add(fullPath, timeStamp);
}
}
void PopulateBuildArtifacts(PartialClassGenerationTaskInternal wrapper)
{
IList<ITaskItem> applicationMarkup = null;
if (this.ApplicationMarkup != null)
{
applicationMarkup = this.ApplicationMarkup
.Select(i => new DelegatingTaskItem(i) as ITaskItem).ToList();
}
wrapper.ApplicationMarkup = applicationMarkup;
wrapper.BuildLogger = this.Log;
wrapper.References = this.References
.Select(i => new DelegatingTaskItem(i) as ITaskItem).ToList();
IList<string> sourceCodeFiles = null;
if (this.SourceCodeFiles != null)
{
sourceCodeFiles = new List<string>(this.SourceCodeFiles.Length);
foreach (ITaskItem taskItem in this.SourceCodeFiles)
{
sourceCodeFiles.Add(taskItem.ItemSpec);
}
}
wrapper.SourceCodeFiles = sourceCodeFiles;
wrapper.Language = this.Language;
wrapper.AssemblyName = this.AssemblyName;
wrapper.OutputPath = this.OutputPath;
wrapper.RootNamespace = this.RootNamespace;
wrapper.GeneratedSourceExtension = this.GeneratedSourceExtension;
wrapper.IsInProcessXamlMarkupCompile = this.IsInProcessXamlMarkupCompile;
wrapper.MSBuildProjectDirectory = this.MSBuildProjectDirectory;
wrapper.XamlBuildTaskTypeGenerationExtensionNames = XamlBuildTaskServices.GetXamlBuildTaskExtensionNames(this.XamlBuildTypeGenerationExtensionNames);
if (this.XamlBuildTypeInspectionExtensionNames != null && this.XamlBuildTypeInspectionExtensionNames.Length > 0)
{
wrapper.MarkupCompilePass2ExtensionsPresent = true;
}
wrapper.SupportExtensions = this.supportExtensions;
}
void ExtractBuiltArtifacts(PartialClassGenerationTaskInternal wrapper)
{
foreach (string resource in wrapper.GeneratedResources)
{
this.generatedResources.Add(new TaskItem(resource));
}
foreach (string code in wrapper.GeneratedCodeFiles)
{
this.generatedCodeFiles.Add(new TaskItem(code));
}
this.RequiresCompilationPass2 = wrapper.RequiresCompilationPass2 ||
(this.XamlBuildTypeInspectionExtensionNames != null && this.XamlBuildTypeInspectionExtensionNames.Length > 0);
}
}
}
| |
using System;
using System.Linq;
using System.Threading;
using Amazon;
using Amazon.Runtime;
using Amazon.Runtime.Internal.Util;
using Amazon.DynamoDBv2.Model;
using Amazon.DynamoDBv2;
using System.Collections.Generic;
using Amazon.DynamoDBv2.DocumentModel;
using System.Text;
using System.IO;
using NUnit.Framework;
using CommonTests.Framework;
using CommonTests.IntegrationTests.DynamoDB;
namespace CommonTests.IntegrationTests
{
[TestFixture]
public class CacheTests
{
private const string TABLENAME = "cache-test-table";
private string testTableName = null;
private AmazonDynamoDBClient client = null;
private bool lastUseSdkCacheValue;
[SetUp]
public void Init()
{
lastUseSdkCacheValue = AWSConfigs.UseSdkCache;
AWSConfigs.UseSdkCache = true;
SdkCache.Clear();
client = TestBase.CreateClient<AmazonDynamoDBClient>();
testTableName = UtilityMethods.GenerateName("CacheTest");
CreateTable(testTableName, true);
}
[TearDown]
public void Cleanup()
{
var tableExists = true;
//var status = AWSSDK_DotNet.IntegrationTests.Tests.DynamoDB.DynamoDBTests.GetStatus(tableName);
//tableExists = (status != null);
var allTables = client.ListTablesAsync().Result.TableNames;
tableExists = allTables.Contains(TABLENAME);
if (tableExists)
DeleteTable(TABLENAME);
if (allTables.Contains(testTableName))
DeleteTable(testTableName);
AWSConfigs.UseSdkCache = lastUseSdkCacheValue;
SdkCache.Clear();
}
[Test]
public void TestCache()
{
Func<string, TableDescription> creator = tn => client.DescribeTableAsync(tn).Result.Table;
var tableName = testTableName;
var tableCache = SdkCache.GetCache<string, TableDescription>(client, DynamoDBTests.TableCacheIdentifier, StringComparer.Ordinal);
Assert.AreEqual(0, tableCache.ItemCount);
using (var counter = new ServiceResponseCounter(client))
{
var table = tableCache.GetValue(tableName, creator);
Assert.AreEqual(1, counter.ResponseCount);
Assert.AreEqual(1, tableCache.ItemCount);
// verify the item is still there
table = tableCache.GetValue(tableName, creator);
Assert.AreEqual(1, counter.ResponseCount);
// verify item was reloaded
tableCache.Clear(tableName);
table = tableCache.GetValue(tableName, creator);
Assert.AreEqual(2, counter.ResponseCount);
Assert.AreEqual(1, tableCache.ItemCount);
// test item expiration
tableCache.MaximumItemLifespan = TimeSpan.FromSeconds(1);
UtilityMethods.Sleep(tableCache.MaximumItemLifespan);
table = tableCache.GetValue(tableName, creator);
Assert.AreEqual(3, counter.ResponseCount);
Assert.AreEqual(1, tableCache.ItemCount);
}
}
[Test]
public void MultipleClientsTest()
{
Table.ClearTableCache();
var tableName = testTableName;
Table table;
using (var nc = TestBase.CreateClient<AmazonDynamoDBClient>())
{
table = Table.LoadTable(nc, tableName);
}
Table.ClearTableCache();
table = Table.LoadTable(client, tableName);
}
[Test]
public void ChangingTableTest()
{
var item = new Document(new Dictionary<string, DynamoDBEntry>
{
{ "Id", 42 },
{ "Name", "Floyd" },
{ "Coffee", "Yes" }
});
var tableCache = SdkCache.GetCache<string, TableDescription>(client, DynamoDBTests.TableCacheIdentifier, StringComparer.Ordinal);
CreateTable(TABLENAME, defaultKeys: true);
var table = Table.LoadTable(client, TABLENAME);
table.PutItemAsync(item).Wait();
using (var counter = new ServiceResponseCounter(client))
{
var doc = table.GetItemAsync(42, "Floyd").Result;
Assert.IsNotNull(doc);
Assert.AreNotEqual(0, doc.Count);
Assert.AreEqual(1, counter.ResponseCount);
AssertExtensions.ExpectExceptionAsync(table.GetItemAsync("Floyd", 42)).Wait();
var oldTableDescription = tableCache.GetValue(TABLENAME, null);
DeleteTable(TABLENAME);
CreateTable(TABLENAME, defaultKeys: false);
table.PutItemAsync(item).Wait();
AssertExtensions.ExpectExceptionAsync(table.GetItemAsync(42, "Yes")).Wait();
counter.Reset();
Table.ClearTableCache();
table = Table.LoadTable(client, TABLENAME);
doc = table.GetItemAsync(42, "Yes").Result;
Assert.IsNotNull(doc);
Assert.AreNotEqual(0, doc.Count);
Assert.AreEqual(2, counter.ResponseCount);
counter.Reset();
Table.ClearTableCache();
PutItem(tableCache, TABLENAME, oldTableDescription);
table = Table.LoadTable(client, TABLENAME);
doc = tableCache.UseCache(TABLENAME,
() => table.GetItemAsync(42, "Yes").Result,
() => table = Table.LoadTable(client, TABLENAME),
shouldRetryForException: null);
Assert.IsNotNull(doc);
Assert.AreNotEqual(0, doc.Count);
Assert.AreEqual(2, counter.ResponseCount);
}
}
private void CreateTable(string name, bool defaultKeys)
{
var keySchema = new List<KeySchemaElement>
{
new KeySchemaElement
{
AttributeName = "Id",
KeyType = KeyType.HASH
},
new KeySchemaElement
{
AttributeName = defaultKeys ? "Name" : "Coffee",
KeyType = KeyType.RANGE
}
};
var attributes = new List<AttributeDefinition>
{
new AttributeDefinition
{
AttributeName = "Id",
AttributeType = ScalarAttributeType.N
},
new AttributeDefinition
{
AttributeName = defaultKeys ? "Name" : "Coffee",
AttributeType = ScalarAttributeType.S
}
};
client.CreateTableAsync(new CreateTableRequest
{
TableName = name,
KeySchema = keySchema,
AttributeDefinitions = attributes,
ProvisionedThroughput = new ProvisionedThroughput
{
ReadCapacityUnits = 5,
WriteCapacityUnits = 5
}
}).Wait();
DynamoDBTests.WaitForTableStatus(client, name, TableStatus.ACTIVE);
}
private void DeleteTable(string name)
{
client.DeleteTableAsync(name).Wait();
DynamoDBTests.WaitForTableStatus(client, name, null);
}
private void PutItem<TKey,TValue>(ICache<TKey,TValue> cache, TKey key, TValue value)
{
cache.Clear(key);
cache.GetValue(key, k => value);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
** Purpose: This class will encapsulate a long and provide an
** Object representation of it.
**
**
===========================================================*/
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
namespace System
{
[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
public struct Int64 : IComparable, IFormattable, IComparable<Int64>, IEquatable<Int64>, IConvertible
{
internal long m_value;
public const long MaxValue = 0x7fffffffffffffffL;
public const long MinValue = unchecked((long)0x8000000000000000L);
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type Int64, this method throws an ArgumentException.
//
int IComparable.CompareTo(Object value)
{
if (value == null)
{
return 1;
}
if (value is Int64)
{
// Need to use compare because subtraction will wrap
// to positive for very large neg numbers, etc.
long i = (long)value;
if (m_value < i) return -1;
if (m_value > i) return 1;
return 0;
}
throw new ArgumentException(SR.Arg_MustBeInt64);
}
public int CompareTo(Int64 value)
{
// Need to use compare because subtraction will wrap
// to positive for very large neg numbers, etc.
if (m_value < value) return -1;
if (m_value > value) return 1;
return 0;
}
public override bool Equals(Object obj)
{
if (!(obj is Int64))
{
return false;
}
return m_value == ((Int64)obj).m_value;
}
[NonVersionable]
public bool Equals(Int64 obj)
{
return m_value == obj;
}
// The value of the lower 32 bits XORed with the uppper 32 bits.
public override int GetHashCode()
{
return (unchecked((int)((long)m_value)) ^ (int)(m_value >> 32));
}
public override String ToString()
{
Contract.Ensures(Contract.Result<String>() != null);
return FormatProvider.FormatInt64(m_value, null, null);
}
public String ToString(IFormatProvider provider)
{
Contract.Ensures(Contract.Result<String>() != null);
return FormatProvider.FormatInt64(m_value, null, provider);
}
public String ToString(String format)
{
Contract.Ensures(Contract.Result<String>() != null);
return FormatProvider.FormatInt64(m_value, format, null);
}
public String ToString(String format, IFormatProvider provider)
{
Contract.Ensures(Contract.Result<String>() != null);
return FormatProvider.FormatInt64(m_value, format, provider);
}
public static long Parse(String s)
{
return FormatProvider.ParseInt64(s, NumberStyles.Integer, null);
}
public static long Parse(String s, NumberStyles style)
{
UInt32.ValidateParseStyleInteger(style);
return FormatProvider.ParseInt64(s, style, null);
}
public static long Parse(String s, IFormatProvider provider)
{
return FormatProvider.ParseInt64(s, NumberStyles.Integer, provider);
}
// Parses a long from a String in the given style. If
// a NumberFormatInfo isn't specified, the current culture's
// NumberFormatInfo is assumed.
//
public static long Parse(String s, NumberStyles style, IFormatProvider provider)
{
UInt32.ValidateParseStyleInteger(style);
return FormatProvider.ParseInt64(s, style, provider);
}
public static Boolean TryParse(String s, out Int64 result)
{
return FormatProvider.TryParseInt64(s, NumberStyles.Integer, null, out result);
}
public static Boolean TryParse(String s, NumberStyles style, IFormatProvider provider, out Int64 result)
{
UInt32.ValidateParseStyleInteger(style);
return FormatProvider.TryParseInt64(s, style, provider, out result);
}
//
// IConvertible implementation
//
TypeCode IConvertible.GetTypeCode()
{
return TypeCode.Int64;
}
/// <internalonly/>
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return Convert.ToBoolean(m_value);
}
/// <internalonly/>
char IConvertible.ToChar(IFormatProvider provider)
{
return Convert.ToChar(m_value);
}
/// <internalonly/>
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(m_value);
}
/// <internalonly/>
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(m_value);
}
/// <internalonly/>
short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(m_value);
}
/// <internalonly/>
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(m_value);
}
/// <internalonly/>
int IConvertible.ToInt32(IFormatProvider provider)
{
return Convert.ToInt32(m_value);
}
/// <internalonly/>
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return Convert.ToUInt32(m_value);
}
/// <internalonly/>
long IConvertible.ToInt64(IFormatProvider provider)
{
return m_value;
}
/// <internalonly/>
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(m_value);
}
/// <internalonly/>
float IConvertible.ToSingle(IFormatProvider provider)
{
return Convert.ToSingle(m_value);
}
/// <internalonly/>
double IConvertible.ToDouble(IFormatProvider provider)
{
return Convert.ToDouble(m_value);
}
/// <internalonly/>
Decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return Convert.ToDecimal(m_value);
}
/// <internalonly/>
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "Int64", "DateTime"));
}
/// <internalonly/>
Object IConvertible.ToType(Type type, IFormatProvider provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
}
| |
#region License
// Copyright 2017 Jose Luis Rovira Martin
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using Essence.Util.Math.Double;
using SysMath = System.Math;
namespace Essence.Maths.Double
{
public struct DoubleMath : IMath<double>
{
public static readonly DoubleMath Instance = new DoubleMath();
public double Zero
{
get { return 0; }
}
public double One
{
get { return 1; }
}
public double Add(double a, double b)
{
return a + b;
}
public double Sub(double a, double b)
{
return a - b;
}
public double Mul(double a, double b)
{
return a * b;
}
public double Div(double a, double b)
{
return a / b;
}
public double Neg(double a)
{
return -a;
}
public double Sqrt(double a)
{
return SysMath.Sqrt(a);
}
public double Atan2(double y, double x)
{
return SysMath.Atan2(y, x);
}
public double ToValue<TConvertible>(TConvertible c) where TConvertible : struct, IConvertible
{
return c.ToDouble(null);
}
}
public struct Vec2d : IVec2<double, Vec2d>
{
public static Vec2d Zero = new Vec2d(0, 0);
public Vec2d(double x, double y)
{
this.X = x;
this.Y = y;
}
int IVec<double, Vec2d>.Dim
{
get { return 2; }
}
void IVec<double, Vec2d>.Get(double[] array)
{
array[0] = this.X;
array[1] = this.Y;
}
public Vec2d Neg()
{
return new Vec2d(-this.X, -this.Y);
}
public Vec2d Add(Vec2d v)
{
return new Vec2d(this.X + v.X, this.Y + v.Y);
}
public Vec2d Sub(Vec2d v)
{
return new Vec2d(this.X - v.X, this.Y - v.Y);
}
public Vec2d Mul(double v)
{
return new Vec2d(this.X * v, this.Y * v);
}
public Vec2d Div(double v)
{
return new Vec2d(this.X / v, this.Y / v);
}
public Vec2d Add(double alpha, Vec2d b, double beta)
{
return new Vec2d(this.X * alpha + b.X * beta, this.Y * alpha + b.Y * beta);
}
public Vec2d Norm()
{
return this.Div(this.Length);
}
public double Length2
{
get { return this.X * this.X + this.Y * this.Y; }
}
public double Length
{
get { return SysMath.Sqrt(this.Length2); }
}
public double Dot(Vec2d b)
{
return this.X * b.X + this.Y * b.Y;
}
public double Cross(Vec2d b)
{
return this.X * b.Y - this.Y * b.X;
}
double IVec1<double, Vec2d>.X
{
get { return this.X; }
}
double IVec2<double, Vec2d>.Y
{
get { return this.Y; }
}
public bool EpsilonEquals(Vec2d vec, double error = MathUtils.EPSILON)
{
return this.X.EpsilonEquals(vec.X, error) && this.Y.EpsilonEquals(vec.Y, error);
}
public readonly double X;
public readonly double Y;
public override string ToString()
{
return string.Format("{0:F2}; {1:F2}", this.X, this.Y);
}
}
public struct Vec2dFactory : IVec2Factory<double, Vec2d>
{
public Vec2d New(double x, double y)
{
return new Vec2d(x, y);
}
}
public struct Vec3d : IVec3<double, Vec3d>
{
public static Vec3d Zero = new Vec3d(0, 0, 0);
public Vec3d(double x, double y, double z)
{
this.X = x;
this.Y = y;
this.Z = z;
}
public static Vec3d FromRGB(byte r, byte g, byte b)
{
return new Vec3d((double)r / 255, (double)g / 255, (double)b / 255);
}
int IVec<double, Vec3d>.Dim
{
get { return 3; }
}
void IVec<double, Vec3d>.Get(double[] array)
{
array[0] = this.X;
array[1] = this.Y;
array[2] = this.Z;
}
public Vec3d Neg()
{
return new Vec3d(-this.X, -this.Y, -this.Z);
}
public Vec3d Add(Vec3d v)
{
return new Vec3d(this.X + v.X, this.Y + v.Y, this.Z + v.Z);
}
public Vec3d Sub(Vec3d v)
{
return new Vec3d(this.X - v.X, this.Y - v.Y, this.Z - v.Z);
}
public Vec3d Mul(double v)
{
return new Vec3d(this.X * v, this.Y * v, this.Z * v);
}
public Vec3d Div(double v)
{
return new Vec3d(this.X / v, this.Y / v, this.Z / v);
}
public Vec3d Add(double alpha, Vec3d b, double beta)
{
return new Vec3d(this.X * alpha + b.X * beta, this.Y * alpha + b.Y * beta, this.Z * alpha + b.Z * beta);
}
public Vec3d Norm()
{
return this.Div(this.Length);
}
public double Length2
{
get { return this.X * this.X + this.Y * this.Y + this.Z * this.Z; /* this.Dot(this) */ }
}
public double Length
{
get { return SysMath.Sqrt(this.Length2); }
}
public double Dot(Vec3d b)
{
return this.X * b.X + this.Y * b.Y + this.Z * b.Z;
}
double IVec2<double, Vec3d>.Cross(Vec3d b)
{
return this.Cross(b).Length;
}
double IVec1<double, Vec3d>.X
{
get { return this.X; }
}
double IVec2<double, Vec3d>.Y
{
get { return this.Y; }
}
double IVec3<double, Vec3d>.Z
{
get { return this.Z; }
}
public Vec3d Cross(Vec3d v)
{
return new Vec3d((this.Y * v.Z) - (this.Z * v.Y),
(this.Z * v.X) - (this.X * v.Z),
(this.X * v.Y) - (this.Y * v.X));
}
public bool EpsilonEquals(Vec3d vec, double error)
{
return this.X.EpsilonEquals(vec.X, error) && this.Y.EpsilonEquals(vec.Y, error) && this.Z.EpsilonEquals(vec.Z, error);
}
public readonly double X;
public readonly double Y;
public readonly double Z;
public override string ToString()
{
return string.Format("{0:F2}; {1:F2}; {2:F2}", this.X, this.Y, this.Z);
}
}
public struct Vec3dFactory : IVec3Factory<double, Vec3d>, IVec2Factory<double, Vec3d>
{
public Vec3d New(double x, double y, double z)
{
return new Vec3d(x, y, z);
}
Vec3d IVec2Factory<double, Vec3d>.New(double x, double y)
{
return new Vec3d(x, y, 0);
}
}
public abstract class Transform2 : ITransform2<Transform2, double, Vec2d>
{
public static Transform2 Identity()
{
return new MatrixTransform2(
1, 0, 0,
0, 1, 0);
}
public static Transform2 Rotate(double r)
{
double c = SysMath.Cos(r);
double s = SysMath.Sin(r);
return new MatrixTransform2(
c, -s, 0,
s, c, 0);
}
public static Transform2 Rotate(Vec2d pt, double r)
{
return Rotate(pt.X, pt.Y, r);
}
public static Transform2 Rotate(double px, double py, double r)
{
double c = SysMath.Cos(r);
double s = SysMath.Sin(r);
return new MatrixTransform2(
c, -s, -px * c + py * s + px,
s, c, -px * s - py * c + py);
}
public static Transform2 Translate(Vec2d t)
{
return Translate(t.X, t.Y);
}
public static Transform2 Translate(double dx, double dy)
{
return new MatrixTransform2(
1, 0, dx,
0, 1, dy);
}
public static Transform2 Translate(double px, double py, double px2, double py2)
{
return Translate(px2 - px, py2 - py);
}
public static Transform2 Scale(double ex, double ey)
{
return new MatrixTransform2(
ex, 0, 0,
0, ey, 0);
}
public static Transform2 Scale(double px, double py, double ex, double ey)
{
return new MatrixTransform2(
ex, 0, px - ex * px,
0, ey, py - ey * py);
}
public abstract Vec2d TransformVector(Vec2d v);
public abstract Vec2d TransformPoint(Vec2d v);
public abstract Transform2 Mult(Transform2 t);
}
public class MatrixTransform2 : Transform2
{
public MatrixTransform2(double a, double b, double tx, double c, double d, double ty)
{
this.a = a;
this.b = b;
this.tx = tx;
this.c = c;
this.d = d;
this.ty = ty;
}
public MatrixTransform2 Mult(MatrixTransform2 t)
{
return new MatrixTransform2(this.a * t.a + this.b * t.c,
this.a * t.b + this.b * t.d,
this.a * t.tx + this.b * t.ty + this.tx,
this.c * t.a + this.d * t.c,
this.c * t.b + this.d * t.d,
this.c * t.tx + this.d * t.ty + this.ty);
}
public override Vec2d TransformVector(Vec2d v)
{
return new Vec2d(v.X * this.a + v.Y * this.b, v.X * this.c + v.Y * this.d);
}
public override Vec2d TransformPoint(Vec2d v)
{
return new Vec2d(v.X * this.a + v.Y * this.b + this.tx, v.X * this.c + v.Y * this.d + this.ty);
}
public override Transform2 Mult(Transform2 t)
{
return this.Mult((MatrixTransform2)t);
}
private readonly double a, b, tx;
private readonly double c, d, ty;
}
}
| |
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Atif Aziz, http://www.raboof.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
#region License, Terms and Author(s) on Updates
//
// A slightly modified version of Atif Aziz's ErrorLogModule for ELMAH
// Copyright (c) 2013 Dragos Hont
//
// Author(s):
//
// dhont https://github.com/dhont
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Diagnostics;
using System.Web;
using Elmah;
namespace ElmahExtensions
{
#region Imports
#endregion
/// <summary>
/// HTTP module implementation that logs unhandled exceptions in an
/// ASP.NET Web application to an error log.
/// </summary>
public class CustomErrorLogModule : HttpModuleBase, IExceptionFiltering
{
public event ExceptionFilterEventHandler Filtering;
public event ErrorLoggedEventHandler Logged;
/// <summary>
/// Initializes the module and prepares it to handle requests.
/// </summary>
protected override void OnInit(HttpApplication application)
{
//if (application == null)
// throw new ArgumentNullException("application");
application = application ?? new HttpApplication();
application.Error += OnError;
CustomErrorSignal.Get(application).Raised += OnCustomErrorSignaled;
}
/// <summary>
/// Gets the <see cref="ErrorLog"/> instance to which the module
/// will log exceptions.
/// </summary>
protected virtual ErrorLog GetErrorLog(HttpContext context)
{
return ErrorLog.GetDefault(context);
}
/// <summary>
/// The handler called when an unhandled exception bubbles up to
/// the module.
/// </summary>
protected virtual void OnError(object sender, EventArgs args)
{
HttpApplication application = (HttpApplication) sender;
LogException(application.Server.GetLastError(), application.Context);
}
/// <summary>
/// The handler called when an exception is explicitly signaled.
/// </summary>
protected virtual void OnCustomErrorSignaled(object sender, CustomErrorSignalEventArgs args)
{
args.ErrorLogEntry = LogException(args.Exception, args.Context);
}
/// <summary>
/// Logs an exception and its context to the error log.
/// </summary>
protected virtual ErrorLogEntry LogException(Exception e, HttpContext context)
{
if (e == null)
throw new ArgumentNullException("e");
//
// Fire an event to check if listeners want to filter out
// logging of the uncaught exception.
//
ExceptionFilterEventArgs args = new ExceptionFilterEventArgs(e, context);
OnFiltering(args);
if (args.Dismissed)
return null;
//
// Log away...
//
ErrorLogEntry entry = null;
try
{
Error error = new Error(e, context);
ErrorLog log = GetErrorLog(context);
error.ApplicationName = log.ApplicationName;
string id = log.Log(error);
entry = new ErrorLogEntry(log, id, error);
}
catch (Exception localException)
{
//
// IMPORTANT! We swallow any exception raised during the
// logging and send them out to the trace . The idea
// here is that logging of exceptions by itself should not
// be critical to the overall operation of the application.
// The bad thing is that we catch ANY kind of exception,
// even system ones and potentially let them slip by.
//
Trace.WriteLine(localException);
}
if (entry != null)
OnLogged(new ErrorLoggedEventArgs(entry));
return entry;
}
/// <summary>
/// Raises the <see cref="Logged"/> event.
/// </summary>
protected virtual void OnLogged(ErrorLoggedEventArgs args)
{
ErrorLoggedEventHandler handler = Logged;
if (handler != null)
handler(this, args);
}
/// <summary>
/// Raises the <see cref="Filtering"/> event.
/// </summary>
protected virtual void OnFiltering(ExceptionFilterEventArgs args)
{
ExceptionFilterEventHandler handler = Filtering;
if (handler != null)
handler(this, args);
}
/// <summary>
/// Determines whether the module will be registered for discovery
/// in partial trust environments or not.
/// </summary>
protected override bool SupportDiscoverability
{
get { return true; }
}
}
public delegate void ErrorLoggedEventHandler(object sender, ErrorLoggedEventArgs args);
[ Serializable ]
public sealed class ErrorLoggedEventArgs : EventArgs
{
private readonly ErrorLogEntry _entry;
public ErrorLoggedEventArgs(ErrorLogEntry entry)
{
if (entry == null)
throw new ArgumentNullException("entry");
_entry = entry;
}
public ErrorLogEntry Entry
{
get { return _entry; }
}
}
}
| |
//! \file GarConvert.cs
//! \date Fri Aug 22 08:22:47 2014
//! \brief Game resources conversion methods.
//
// Copyright (C) 2014-2015 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.IO;
using System.Linq;
using System.Windows;
using System.Windows.Input;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using GameRes;
using GARbro.GUI.Strings;
using GARbro.GUI.Properties;
using Ookii.Dialogs.Wpf;
namespace GARbro.GUI
{
public partial class MainWindow : Window
{
/// <summary>
/// Convert selected images to another format.
/// </summary>
void ConvertMediaExec (object sender, ExecutedRoutedEventArgs e)
{
if (ViewModel.IsArchive)
return;
var source = from entry in CurrentDirectory.SelectedItems.Cast<EntryViewModel>()
where entry.Type == "image" || entry.Type == "audio"
select entry.Source;
if (!source.Any())
{
PopupError (guiStrings.MsgNoMediaFiles, guiStrings.TextMediaConvertError);
return;
}
var convert_dialog = new ConvertMedia();
convert_dialog.Owner = this;
var result = convert_dialog.ShowDialog() ?? false;
if (!result)
return;
var format = convert_dialog.ImageConversionFormat.SelectedItem as ImageFormat;
if (null == format)
{
Trace.WriteLine ("Format is not selected", "ConvertMediaExec");
return;
}
try
{
Directory.SetCurrentDirectory (ViewModel.Path.First());
var converter = new GarConvertMedia (this);
converter.IgnoreErrors = convert_dialog.IgnoreErrors.IsChecked ?? false;
converter.Convert (source, format);
}
catch (Exception X)
{
PopupError (X.Message, guiStrings.TextMediaConvertError);
}
}
}
internal class GarConvertMedia
{
private MainWindow m_main;
private ProgressDialog m_progress_dialog;
private IEnumerable<Entry> m_source;
private ImageFormat m_image_format;
private Exception m_pending_error;
private List<Tuple<string,string>> m_failed = new List<Tuple<string,string>>();
public bool IgnoreErrors { get; set; }
public IEnumerable<Tuple<string,string>> FailedFiles { get { return m_failed; } }
public GarConvertMedia (MainWindow parent)
{
m_main = parent;
}
public void Convert (IEnumerable<Entry> images, ImageFormat format)
{
m_main.StopWatchDirectoryChanges();
m_source = images;
m_image_format = format;
m_progress_dialog = new ProgressDialog ()
{
WindowTitle = guiStrings.TextTitle,
Text = "Converting image",
Description = "",
MinimizeBox = true,
};
m_progress_dialog.DoWork += ConvertWorker;
m_progress_dialog.RunWorkerCompleted += OnConvertComplete;
m_progress_dialog.ShowDialog (m_main);
}
void ConvertWorker (object sender, DoWorkEventArgs e)
{
m_pending_error = null;
try
{
int total = m_source.Count();
int i = 0;
foreach (var entry in m_source)
{
if (m_progress_dialog.CancellationPending)
throw new OperationCanceledException();
var filename = entry.Name;
int progress = i++*100/total;
m_progress_dialog.ReportProgress (progress, string.Format (guiStrings.MsgConvertingFile,
Path.GetFileName (filename)), null);
try
{
if ("image" == entry.Type)
ConvertImage (filename);
else if ("audio" == entry.Type)
ConvertAudio (filename);
}
catch (NotImplementedException X)
{
// target format creation not implemented
m_pending_error = X;
break;
}
catch (Exception X)
{
if (!IgnoreErrors)
throw;
m_failed.Add (Tuple.Create (Path.GetFileName (filename), X.Message));
}
}
}
catch (Exception X)
{
m_pending_error = X;
}
}
public static readonly HashSet<string> CommonAudioFormats = new HashSet<string> { "wav", "mp3", "ogg" };
void ConvertAudio (string filename)
{
using (var file = File.OpenRead (filename))
using (var input = AudioFormat.Read (file))
{
if (null == input)
return;
var source_ext = Path.GetExtension (filename).TrimStart ('.').ToLowerInvariant();
string source_format = input.SourceFormat;
if (CommonAudioFormats.Contains (source_format))
{
if (source_ext == source_format)
return;
string output_name = Path.ChangeExtension (filename, source_format);
using (var output = CreateNewFile (output_name))
{
input.Source.Position = 0;
input.Source.CopyTo (output);
}
}
else
{
if (source_ext == "wav")
return;
string output_name = Path.ChangeExtension (filename, "wav");
using (var output = CreateNewFile (output_name))
AudioFormat.Wav.Write (input, output);
}
}
}
void ConvertImage (string filename)
{
string source_ext = Path.GetExtension (filename).TrimStart ('.').ToLowerInvariant();
if (m_image_format.Extensions.Any (ext => ext == source_ext))
return;
string target_ext = m_image_format.Extensions.First();
string target_name = Path.ChangeExtension (filename, target_ext);
using (var file = File.OpenRead (filename))
{
var image = ImageFormat.Read (filename, file);
if (null == image)
return;
try
{
using (var output = CreateNewFile (target_name))
m_image_format.Write (output, image);
}
catch // delete destination file on conversion failure
{
File.Delete (target_name);
throw;
}
}
}
/// <summary>
/// Creates new file with specified filename, or, if it's already exists, tries to open
/// files named "FILENAME.1.EXT", "FILENAME.2.EXT" and so on.
/// <exception cref="System.IOException">Throws exception after 100th failed attempt.</exception>
/// </summary>
public static Stream CreateNewFile (string filename)
{
string name = filename;
var ext = new Lazy<string> (() => Path.GetExtension (filename));
for (int attempt = 1; ; ++attempt)
{
try
{
return File.Open (name, FileMode.CreateNew);
}
catch (IOException) // file already exists
{
if (100 == attempt) // limit number of attempts
throw;
}
name = Path.ChangeExtension (filename, attempt.ToString()+ext.Value);
}
}
void OnConvertComplete (object sender, RunWorkerCompletedEventArgs e)
{
m_main.ResumeWatchDirectoryChanges();
m_progress_dialog.Dispose();
if (null != m_pending_error)
{
if (m_pending_error is OperationCanceledException)
m_main.SetStatusText (m_pending_error.Message);
else
m_main.PopupError (m_pending_error.Message, guiStrings.TextMediaConvertError);
}
m_main.Activate();
m_main.RefreshView();
}
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using NLog.Config;
#if !NETSTANDARD
namespace NLog.UnitTests.LayoutRenderers
{
using System;
using Microsoft.Win32;
using Xunit;
public class RegistryTests : NLogTestBase, IDisposable
{
private const string TestKey = @"Software\NLogTest";
public RegistryTests()
{
var key = Registry.CurrentUser.CreateSubKey(TestKey);
key.SetValue("Foo", "FooValue");
key.SetValue(null, "UnnamedValue");
#if !NET3_5
//different keys because in 32bit the 64bits uses the 32
RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry32).CreateSubKey("Software\\NLogTest").SetValue("view32", "reg32");
RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64).CreateSubKey("Software\\NLogTest").SetValue("view64", "reg64");
#endif
}
public void Dispose()
{
#if !NET3_5
//different keys because in 32bit the 64bits uses the 32
try
{
RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry32).DeleteSubKey("Software\\NLogTest");
}
catch (Exception)
{
}
try
{
RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64).DeleteSubKey("Software\\NLogTest");
}
catch (Exception)
{
}
#endif
try
{
Registry.CurrentUser.DeleteSubKey(TestKey);
}
catch (Exception)
{
}
}
[Fact]
public void RegistryNamedValueTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${registry:key=HKCU\\Software\\NLogTest:value=Foo}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
LogManager.GetLogger("d").Debug("zzz");
AssertDebugLastMessage("debug", "FooValue");
}
#if !NET3_5
[Fact]
public void RegistryNamedValueTest_hive32()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${registry:key=HKCU\\Software\\NLogTest:value=view32:view=Registry32}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
LogManager.GetLogger("d").Debug("zzz");
AssertDebugLastMessage("debug", "reg32");
}
[Fact]
public void RegistryNamedValueTest_hive64()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${registry:key=HKCU\\Software\\NLogTest:value=view64:view=Registry64}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
LogManager.GetLogger("d").Debug("zzz");
AssertDebugLastMessage("debug", "reg64");
}
#endif
[Fact]
public void RegistryNamedValueTest_forward_slash()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${registry:key=HKCU/Software/NLogTest:value=Foo}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
LogManager.GetLogger("d").Debug("zzz");
AssertDebugLastMessage("debug", "FooValue");
}
[Fact]
public void RegistryUnnamedValueTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${registry:key=HKCU\\Software\\NLogTest}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
LogManager.GetLogger("d").Debug("zzz");
AssertDebugLastMessage("debug", "UnnamedValue");
}
[Fact]
public void RegistryUnnamedValueTest_forward_slash()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${registry:key=HKCU/Software/NLogTest}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
LogManager.GetLogger("d").Debug("zzz");
AssertDebugLastMessage("debug", "UnnamedValue");
}
[Fact]
public void RegistryKeyNotFoundTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${registry:key=HKCU\\Software\\NoSuchKey:defaultValue=xyz}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
LogManager.GetLogger("d").Debug("zzz");
AssertDebugLastMessage("debug", "xyz");
}
[Fact]
public void RegistryKeyNotFoundTest_forward_slash()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${registry:key=HKCU/Software/NoSuchKey:defaultValue=xyz}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
LogManager.GetLogger("d").Debug("zzz");
AssertDebugLastMessage("debug", "xyz");
}
[Fact]
public void RegistryValueNotFoundTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${registry:key=HKCU\\Software\\NLogTest:value=NoSuchValue:defaultValue=xyz}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
LogManager.GetLogger("d").Debug("zzz");
AssertDebugLastMessage("debug", "xyz");
}
[Fact]
public void RegistryDefaultValueTest()
{
using (new NoThrowNLogExceptions())
{
//example: 0003: NLog.UnitTests
AssertLayoutRendererOutput("${registry:value=NOT_EXISTENT:key=HKLM/NOT_EXISTENT:defaultValue=logdefaultvalue}",
"logdefaultvalue");
}
}
[Fact]
public void RegistryDefaultValueTest_with_colon()
{
using (new NoThrowNLogExceptions())
{
//example: 0003: NLog.UnitTests
AssertLayoutRendererOutput("${registry:value=NOT_EXISTENT:key=HKLM/NOT_EXISTENT:defaultValue=C\\:temp}",
"C:temp");
}
}
[Fact]
public void RegistryDefaultValueTest_with_slash()
{
using (new NoThrowNLogExceptions())
{
//example: 0003: NLog.UnitTests
AssertLayoutRendererOutput("${registry:value=NOT_EXISTENT:key=HKLM/NOT_EXISTENT:defaultValue=C/temp}",
"C/temp");
}
}
[Fact]
public void RegistryDefaultValueTest_with_foward_slash()
{
using (new NoThrowNLogExceptions())
{
//example: 0003: NLog.UnitTests
AssertLayoutRendererOutput("${registry:value=NOT_EXISTENT:key=HKLM/NOT_EXISTENT:defaultValue=C\\\\temp}",
"C\\temp");
}
}
[Fact]
public void RegistryDefaultValueTest_with_foward_slash2()
{
//example: 0003: NLog.UnitTests
using (new NoThrowNLogExceptions())
{
AssertLayoutRendererOutput("${registry:value=NOT_EXISTENT:key=HKLM/NOT_EXISTENT:defaultValue=C\\temp:requireEscapingSlashesInDefaultValue=false}",
"C\\temp");
}
}
[Fact]
public void Registry_nosubky()
{
using (new NoThrowNLogExceptions())
{
//example: 0003: NLog.UnitTests
AssertLayoutRendererOutput("${registry:key=HKEY_CURRENT_CONFIG}", "");
}
}
[Fact]
public void RegistryDefaultValueNull()
{
using (new NoThrowNLogExceptions())
{
//example: 0003: NLog.UnitTests
AssertLayoutRendererOutput("${registry:value=NOT_EXISTENT:key=HKLM/NOT_EXISTENT}", "");
}
}
[Fact]
public void RegistryTestWrongKey_no_ex()
{
using (new NoThrowNLogExceptions())
{
AssertLayoutRendererOutput("${registry:value=NOT_EXISTENT:key=garabageHKLM/NOT_EXISTENT:defaultValue=empty}", "");
}
}
[Fact]
public void RegistryTestWrongKey_ex()
{
LogManager.ThrowExceptions = true;
Assert.Throws<ArgumentException>(
() => { AssertLayoutRendererOutput("${registry:value=NOT_EXISTENT:key=garabageHKLM/NOT_EXISTENT:defaultValue=empty}", ""); });
}
}
}
#endif
| |
// 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.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Primitives;
using Microsoft.Net.Http.Headers;
namespace Microsoft.AspNetCore.Localization
{
/// <summary>
/// Enables automatic setting of the culture for <see cref="HttpRequest"/>s based on information
/// sent by the client in headers and logic provided by the application.
/// </summary>
public class RequestLocalizationMiddleware
{
private const int MaxCultureFallbackDepth = 5;
private readonly RequestDelegate _next;
private readonly RequestLocalizationOptions _options;
private readonly ILogger _logger;
/// <summary>
/// Creates a new <see cref="RequestLocalizationMiddleware"/>.
/// </summary>
/// <param name="next">The <see cref="RequestDelegate"/> representing the next middleware in the pipeline.</param>
/// <param name="options">The <see cref="RequestLocalizationOptions"/> representing the options for the
/// <param name="loggerFactory">The <see cref="ILoggerFactory"/> used for logging.</param>
/// <see cref="RequestLocalizationMiddleware"/>.</param>
public RequestLocalizationMiddleware(RequestDelegate next, IOptions<RequestLocalizationOptions> options, ILoggerFactory loggerFactory)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
_next = next ?? throw new ArgumentNullException(nameof(next));
_logger = loggerFactory?.CreateLogger<RequestLocalizationMiddleware>() ?? throw new ArgumentNullException(nameof(loggerFactory));
_options = options.Value;
}
/// <summary>
/// Invokes the logic of the middleware.
/// </summary>
/// <param name="context">The <see cref="HttpContext"/>.</param>
/// <returns>A <see cref="Task"/> that completes when the middleware has completed processing.</returns>
public async Task Invoke(HttpContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var requestCulture = _options.DefaultRequestCulture;
IRequestCultureProvider? winningProvider = null;
if (_options.RequestCultureProviders != null)
{
foreach (var provider in _options.RequestCultureProviders)
{
var providerResultCulture = await provider.DetermineProviderCultureResult(context);
if (providerResultCulture == null)
{
continue;
}
var cultures = providerResultCulture.Cultures;
var uiCultures = providerResultCulture.UICultures;
CultureInfo? cultureInfo = null;
CultureInfo? uiCultureInfo = null;
if (_options.SupportedCultures != null)
{
cultureInfo = GetCultureInfo(
cultures,
_options.SupportedCultures,
_options.FallBackToParentCultures);
if (cultureInfo == null)
{
_logger.UnsupportedCultures(provider.GetType().Name, cultures);
}
}
if (_options.SupportedUICultures != null)
{
uiCultureInfo = GetCultureInfo(
uiCultures,
_options.SupportedUICultures,
_options.FallBackToParentUICultures);
if (uiCultureInfo == null)
{
_logger.UnsupportedUICultures(provider.GetType().Name, uiCultures);
}
}
if (cultureInfo == null && uiCultureInfo == null)
{
continue;
}
cultureInfo ??= _options.DefaultRequestCulture.Culture;
uiCultureInfo ??= _options.DefaultRequestCulture.UICulture;
var result = new RequestCulture(cultureInfo, uiCultureInfo);
requestCulture = result;
winningProvider = provider;
break;
}
}
context.Features.Set<IRequestCultureFeature>(new RequestCultureFeature(requestCulture, winningProvider));
SetCurrentThreadCulture(requestCulture);
if (_options.ApplyCurrentCultureToResponseHeaders)
{
var headers = context.Response.Headers;
headers.ContentLanguage = requestCulture.UICulture.Name;
}
await _next(context);
}
private static void SetCurrentThreadCulture(RequestCulture requestCulture)
{
CultureInfo.CurrentCulture = requestCulture.Culture;
CultureInfo.CurrentUICulture = requestCulture.UICulture;
}
private static CultureInfo? GetCultureInfo(
IList<StringSegment> cultureNames,
IList<CultureInfo> supportedCultures,
bool fallbackToParentCultures)
{
foreach (var cultureName in cultureNames)
{
// Allow empty string values as they map to InvariantCulture, whereas null culture values will throw in
// the CultureInfo ctor
if (cultureName != null)
{
var cultureInfo = GetCultureInfo(cultureName, supportedCultures, fallbackToParentCultures, currentDepth: 0);
if (cultureInfo != null)
{
return cultureInfo;
}
}
}
return null;
}
private static CultureInfo? GetCultureInfo(StringSegment name, IList<CultureInfo>? supportedCultures)
{
// Allow only known culture names as this API is called with input from users (HTTP requests) and
// creating CultureInfo objects is expensive and we don't want it to throw either.
if (name == null || supportedCultures == null)
{
return null;
}
var culture = supportedCultures.FirstOrDefault(
supportedCulture => StringSegment.Equals(supportedCulture.Name, name, StringComparison.OrdinalIgnoreCase));
if (culture == null)
{
return null;
}
return CultureInfo.ReadOnly(culture);
}
private static CultureInfo? GetCultureInfo(
StringSegment cultureName,
IList<CultureInfo> supportedCultures,
bool fallbackToParentCultures,
int currentDepth)
{
var culture = GetCultureInfo(cultureName, supportedCultures);
if (culture == null && fallbackToParentCultures && currentDepth < MaxCultureFallbackDepth)
{
var lastIndexOfHyphen = cultureName.LastIndexOf('-');
if (lastIndexOfHyphen > 0)
{
// Trim the trailing section from the culture name, e.g. "fr-FR" becomes "fr"
var parentCultureName = cultureName.Subsegment(0, lastIndexOfHyphen);
culture = GetCultureInfo(parentCultureName, supportedCultures, fallbackToParentCultures, currentDepth + 1);
}
}
return culture;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using OpenMetaverse;
using OpenSim.Region.ScriptEngine.Shared.Api;
namespace OpenSim.Region.ScriptEngine.Shared.Api.Plugins
{
public class Timer
{
public class TimerInfo
{
public uint localID;
public UUID itemID;
//public double interval;
public long interval;
//public DateTime next;
public long next;
public TimerInfo Clone()
{
return (TimerInfo)this.MemberwiseClone();
}
}
public AsyncCommandManager m_CmdManager;
public int TimersCount
{
get
{
lock (TimerListLock)
return Timers.Count;
}
}
public Timer(AsyncCommandManager CmdManager)
{
m_CmdManager = CmdManager;
}
//
// TIMER
//
static private string MakeTimerKey(uint localID, UUID itemID)
{
return localID.ToString() + itemID.ToString();
}
private Dictionary<string,TimerInfo> Timers = new Dictionary<string,TimerInfo>();
private object TimerListLock = new object();
public void SetTimerEvent(uint m_localID, UUID m_itemID, double sec)
{
if (sec == 0) // Disabling timer
{
UnSetTimerEvents(m_localID, m_itemID);
return;
}
// Add to timer
TimerInfo ts = new TimerInfo();
ts.localID = m_localID;
ts.itemID = m_itemID;
ts.interval = Convert.ToInt64(sec * 10000000); // How many 100 nanoseconds (ticks) should we wait
// 2193386136332921 ticks
// 219338613 seconds
//ts.next = DateTime.Now.ToUniversalTime().AddSeconds(ts.interval);
ts.next = DateTime.Now.Ticks + ts.interval;
string key = MakeTimerKey(m_localID, m_itemID);
lock (TimerListLock)
{
// Adds if timer doesn't exist, otherwise replaces with new timer
Timers[key] = ts;
}
}
public void UnSetTimerEvents(uint m_localID, UUID m_itemID)
{
// Remove from timer
string key = MakeTimerKey(m_localID, m_itemID);
lock (TimerListLock)
{
if (Timers.ContainsKey(key))
{
Timers.Remove(key);
}
}
}
public void CheckTimerEvents()
{
// Nothing to do here?
if (Timers.Count == 0)
return;
lock (TimerListLock)
{
// Go through all timers
Dictionary<string, TimerInfo>.ValueCollection tvals = Timers.Values;
foreach (TimerInfo ts in tvals)
{
// Time has passed?
if (ts.next < DateTime.Now.Ticks)
{
//m_log.Debug("Time has passed: Now: " + DateTime.Now.Ticks + ", Passed: " + ts.next);
// Add it to queue
m_CmdManager.m_ScriptEngine.PostScriptEvent(ts.itemID,
new EventParams("timer", new Object[0],
new DetectParams[0]));
// set next interval
//ts.next = DateTime.Now.ToUniversalTime().AddSeconds(ts.interval);
ts.next = DateTime.Now.Ticks + ts.interval;
}
}
}
}
public Object[] GetSerializationData(UUID itemID)
{
List<Object> data = new List<Object>();
lock (TimerListLock)
{
Dictionary<string, TimerInfo>.ValueCollection tvals = Timers.Values;
foreach (TimerInfo ts in tvals)
{
if (ts.itemID == itemID)
{
data.Add(ts.interval);
data.Add(ts.next-DateTime.Now.Ticks);
}
}
}
return data.ToArray();
}
public void CreateFromData(uint localID, UUID itemID, UUID objectID,
Object[] data)
{
int idx = 0;
while (idx < data.Length)
{
TimerInfo ts = new TimerInfo();
ts.localID = localID;
ts.itemID = itemID;
ts.interval = (long)data[idx];
ts.next = DateTime.Now.Ticks + (long)data[idx+1];
idx += 2;
lock (TimerListLock)
{
Timers.Add(MakeTimerKey(localID, itemID), ts);
}
}
}
public List<TimerInfo> GetTimersInfo()
{
List<TimerInfo> retList = new List<TimerInfo>();
lock (TimerListLock)
{
foreach (TimerInfo i in Timers.Values)
retList.Add(i.Clone());
}
return retList;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using com.calitha.goldparser;
using Epi.Core.EnterInterpreter;
namespace Epi.Core.EnterInterpreter.Rules
{
/*
<FuncName1> ::= ABS
|COS
|DAY|DAYS
|ENVIRON|EXISTS|EXP
|FILEDATE|FINDTEXT|FORMAT
|HOUR|HOURS
|LN|LOG
|MINUTES|Month|MONTHS
|NUMTODATE|NUMTOTIME
|RECORDCOUNT|RND|ROUND
|SECOND|SECONDS|STEP|SUBSTRING|SIN
|TRUNC|TXTTODATE|TXTTONUM|TAN
|UPPERCASE
|YEAR|YEARS
<FuncName2> ::= SYSTEMTIME|SYSTEMDATE
<FunctionCall> ::= <FuncName1> '(' <FunctionParameterList> ')'
| <FuncName1> '(' <FunctionCall> ')'
| <FuncName2>
<FunctionParameterList> ::= <EmptyFunctionParameterList> | <NonEmptyFunctionParameterList>
<NonEmptyFunctionParameterList> ::= <MultipleFunctionParameterList> | <SingleFunctionParameterList>
<MultipleFunctionParameterList> ::= <NonEmptyFunctionParameterList> ',' <Expression>
<SingleFunctionParameterList> ::= <Expression>
<EmptyFunctionParameterList> ::=
*/
/// <summary>
/// Class for executing FunctionCall reductions.
/// </summary>
public partial class Rule_FunctionCall : EnterRule
{
private string functionName = null;
private EnterRule functionCall = null;
private string ClassName = null;
private string MethodName = null;
private List<EnterRule> ParameterList = new List<EnterRule>();
#region Constructors
/// <summary>
/// Constructor for Rule_FunctionCall
/// </summary>
/// <param name="pToken">The token to build the reduction with.</param>
public Rule_FunctionCall(Rule_Context pContext, NonterminalToken pToken) : base(pContext)
{
/*
<FunctionCall> ::= <FuncName1> '(' <FunctionParameterList> ')'
| <FuncName1> '(' <FunctionCall> ')'
| <FuncName2>
*/
NonterminalToken T;
if (pToken.Tokens.Length == 1)
{
if (pToken.Rule.ToString().Equals("<FunctionCall>"))
{
T = (NonterminalToken)pToken.Tokens[0];
}
else
{
T = pToken;
}
}
else
{
T = (NonterminalToken)pToken.Tokens[2];
}
string temp = null;
string[] temp2 = null;
if (pToken.Tokens[0] is NonterminalToken)
{
temp = this.ExtractTokens(((NonterminalToken)pToken.Tokens[0]).Tokens).Replace(" . ", ".");
temp2 = temp.Split('.');
}
else
{
temp = ((TerminalToken)pToken.Tokens[0]).Text.Replace(" . ", ".");
}
if(temp2 != null && temp2.Length > 1)
{
this.ClassName = temp2[0].Trim();
this.MethodName = temp2[1].Trim();
this.ParameterList = EnterRule.GetFunctionParameters(pContext, (NonterminalToken)pToken.Tokens[2]);
}
else
{
functionName = this.GetCommandElement(pToken.Tokens, 0).ToString();
switch (functionName.ToUpper())
{
case "ABS":
functionCall = new Rule_Abs(pContext, T);
break;
case "COS":
functionCall = new Rule_Cos(pContext, T);
break;
case "DAY":
functionCall = new Rule_Day(pContext, T);
break;
case "DAYS":
functionCall = new Rule_Days(pContext, T);
break;
case "FORMAT":
functionCall = new Rule_Format(pContext, T);
break;
case "HOUR":
functionCall = new Rule_Hour(pContext, T);
break;
case "HOURS":
functionCall = new Rule_Hours(pContext, T);
break;
case "MINUTE":
functionCall = new Rule_Minute(pContext, T);
break;
case "MINUTES":
functionCall = new Rule_Minutes(pContext, T);
break;
case "MONTH":
functionCall = new Rule_Month(pContext, T);
break;
case "MONTHS":
functionCall = new Rule_Months(pContext, T);
break;
case "NUMTODATE":
functionCall = new Rule_NumToDate(pContext, T);
break;
case "NUMTOTIME":
functionCall = new Rule_NumToTime(pContext, T);
break;
case "RECORDCOUNT":
functionCall = new Rule_RecordCount(pContext, T);
break;
case "SECOND":
functionCall = new Rule_Second(pContext, T);
break;
case "SECONDS":
functionCall = new Rule_Seconds(pContext, T);
break;
case "SYSTEMDATE":
functionCall = new Rule_SystemDate(pContext, T);
break;
case "SYSTEMTIME":
functionCall = new Rule_SystemTime(pContext, T);
break;
case "TXTTODATE":
functionCall = new Rule_TxtToDate(pContext, T);
break;
case "TXTTONUM":
functionCall = new Rule_TxtToNum(pContext, T);
break;
case "YEAR":
functionCall = new Rule_Year(pContext, T);
break;
case "YEARS":
functionCall = new Rule_Years(pContext, T);
break;
case "SUBSTRING":
functionCall = new Rule_Substring(pContext, T);
break;
case "RND":
functionCall = new Rule_Rnd(pContext, T);
break;
case "EXP":
functionCall = new Rule_Exp_Func(pContext, T);
break;
case "LINEBREAK":
functionCall = new Rule_LineBreak(pContext, T);
break;
case "LN":
functionCall = new Rule_LN_Func(pContext, T);
break;
case "ROUND":
functionCall = new Rule_Round(pContext, T);
break;
case "LOG":
functionCall = new Rule_LOG_Func(pContext, T);
break;
case "SIN":
functionCall = new Rule_Sin(pContext, T);
break;
case "TAN":
functionCall = new Rule_Tan(pContext, T);
break;
case "TRUNC":
functionCall = new Rule_TRUNC(pContext, T);
break;
case "STEP":
functionCall = new Rule_Step(pContext, T);
break;
case "UPPERCASE":
functionCall = new Rule_UpperCase(pContext, T);
break;
case "FINDTEXT":
functionCall = new Rule_FindText(pContext, T);
break;
case "ENVIRON":
functionCall = new Rule_FindText(pContext, T);
break;
case "EXISTS":
functionCall = new Rule_Exists(pContext, T);
break;
case "FILEDATE":
functionCall = new Rule_FileDate(pContext, T);
break;
case "ZSCORE":
functionCall = new Rule_ZSCORE(pContext, T);
break;
case "PFROMZ":
functionCall = new Rule_PFROMZ(pContext, T);
break;
case "EPIWEEK":
functionCall = new Rule_EPIWEEK(pContext, T);
break;
case "STRLEN":
functionCall = new Rule_STRLEN(pContext, T);
break;
default:
throw new Exception("Function name " + functionName.ToUpper() + " is not a recognized function.");
}
}
}
#endregion
#region Public Methods
/// <summary>
/// Executes the reduction.
/// </summary>
/// <returns>Returns the result of executing the reduction.</returns>
public override object Execute()
{
object result = null;
if (string.IsNullOrEmpty(this.functionName))
{
if (this.Context.DLLClassList.ContainsKey(this.ClassName.ToLower()))
{
object[] args = this.ParameterList.ToArray();
if (this.ParameterList.Count > 0)
{
args = new object[this.ParameterList.Count];
for (int i = 0; i < this.ParameterList.Count; i++)
{
args[i] = this.ParameterList[i].Execute();
}
}
else
{
args = new object[0];
}
result = this.Context.DLLClassList[this.ClassName].Execute(this.MethodName, args);
}
}
else
{
if (this.functionCall != null)
{
result = this.functionCall.Execute();
}
}
return result;
}
public override void ToJavaScript(StringBuilder pJavaScriptBuilder)
{
if (string.IsNullOrEmpty(this.functionName))
{
}
else
{
if (this.functionCall != null)
{
this.functionCall.ToJavaScript(pJavaScriptBuilder);
}
}
}
#endregion
}
/// <summary>
/// Class for the FunctionParameterList reduction
/// </summary>
public partial class Rule_FunctionParameterList : EnterRule
{
public Stack<EnterRule> paramList = null;
#region Constructors
/// <summary>
/// Constructor for Rule_FunctionParameterList
/// </summary>
/// <param name="pToken">The token to build the reduction with.</param>
public Rule_FunctionParameterList(Rule_Context pContext, NonterminalToken pToken) : base(pContext)
{
//<FunctionParameterList> ::= <EmptyFunctionParameterList>
//<FunctionParameterList> ::= <NonEmptyFunctionParameterList>
NonterminalToken T = (NonterminalToken)pToken.Tokens[0];
switch (T.Rule.Lhs.ToString())
{
case "<NonEmptyFunctionParameterList>":
this.paramList = new Stack<EnterRule>();
//this.paramList.Push(new Rule_NonEmptyFunctionParameterList(T, this.paramList));
new Rule_NonEmptyFunctionParameterList(pContext, T, this.paramList);
break;
case "<SingleFunctionParameterList>":
this.paramList = new Stack<EnterRule>();
new Rule_SingleFunctionParameterList(pContext, T, this.paramList);
break;
case "<EmptyFunctionParameterList>":
//this.paramList = new Rule_EmptyFunctionParameterList(T);
// do nothing the parameterlist is empty
break;
case "<MultipleFunctionParameterList>":
this.paramList = new Stack<EnterRule>();
//this.MultipleParameterList = new Rule_MultipleFunctionParameterList(pToken);
new Rule_MultipleFunctionParameterList(pContext, T, this.paramList);
break;
}
}
#endregion
#region Public Methods
/// <summary>
/// rule to build zero or more funtion parameters builds parameters and allows the associated function to call the parameters when needed
/// </summary>
/// <returns>object</returns>
public override object Execute()
{
object result = null;
return result;
}
#endregion
}
/// <summary>
/// Class for the Rule_EmptyFunctionParameterList reduction
/// </summary>
public partial class Rule_EmptyFunctionParameterList : EnterRule
{
#region Constructors
public Rule_EmptyFunctionParameterList(Rule_Context pContext, NonterminalToken pToken) : base(pContext)
{
//<EmptyFunctionParameterList> ::=
}
#endregion
#region Public Methods
/// <summary>
/// rule to return an empty parameter
/// </summary>
/// <returns>object</returns>
public override object Execute()
{
return String.Empty;
}
#endregion
}
/// <summary>
/// Class for the Rule_NonEmptyFunctionParameterList reduction.
/// </summary>
public partial class Rule_NonEmptyFunctionParameterList : EnterRule
{
protected Stack<EnterRule> MultipleParameterList = null;
//private Reduction SingleParameterList = null;
#region Constructors
public Rule_NonEmptyFunctionParameterList(Rule_Context pContext, NonterminalToken pToken) : base(pContext)
{
//<NonEmptyFunctionParameterList> ::= <MultipleFunctionParameterList>
//<NonEmptyFunctionParameterList> ::= <SingleFunctionParameterList>
NonterminalToken T = (NonterminalToken) pToken.Tokens[0];
switch (T.Rule.Lhs.ToString())
{
case "<MultipleFunctionParameterList>":
this.MultipleParameterList = new Stack<EnterRule>();
//this.MultipleParameterList = new Rule_MultipleFunctionParameterList(pToken);
new Rule_MultipleFunctionParameterList(pContext, T, this.MultipleParameterList);
break;
case "<SingleFunctionParameterList>":
//this.SingleParameterList = new Rule_SingleFunctionParameterList(pToken);
new Rule_SingleFunctionParameterList(pContext, T, this.MultipleParameterList);
break;
}
}
public Rule_NonEmptyFunctionParameterList(Rule_Context pContext, NonterminalToken pToken, Stack<EnterRule> pList) : base(pContext)
{
//<NonEmptyFunctionParameterList> ::= <MultipleFunctionParameterList>
//<NonEmptyFunctionParameterList> ::= <SingleFunctionParameterList>
NonterminalToken T = (NonterminalToken) pToken.Tokens[0];
switch (T.Rule.Lhs.ToString())
{
case "<MultipleFunctionParameterList>":
new Rule_MultipleFunctionParameterList(pContext, T, pList);
break;
case "<SingleFunctionParameterList>":
new Rule_SingleFunctionParameterList(pContext, T, pList);
break;
default:
break;
}
if (pToken.Tokens.Length > 2)
{
Rule_Expression Expression = new Rule_Expression(pContext, (NonterminalToken)pToken.Tokens[2]);
pList.Push(Expression);
}
}
#endregion
#region Public Methods
/// <summary>
/// builds a multi parameters list which is executed in the calling function's execute method.
/// </summary>
/// <returns>object</returns>
public override object Execute()
{
return null;
}
#endregion
}
/// <summary>
/// Class for the Rule_MultipleFunctionParameterList reduction.
/// </summary>
public partial class Rule_MultipleFunctionParameterList : EnterRule
{
private EnterRule Expression = null;
private EnterRule nonEmptyList = null;
#region Constructors
public Rule_MultipleFunctionParameterList(Rule_Context pContext, NonterminalToken pToken, Stack<EnterRule> pList) : base(pContext)
{
//<MultipleFunctionParameterList> ::= <NonEmptyFunctionParameterList> ',' <Expression>
NonterminalToken nonEmptyToken = (NonterminalToken)pToken.Tokens[0];
NonterminalToken ExpressionToken = (NonterminalToken)pToken.Tokens[2];
// nonEmptyList = new Rule_NonEmptyFunctionParameterList(pContext, nonEmptyToken, pList);
//this.Expression = new Rule_Expression(pContext, ExpressionToken);
pList.Push(EnterRule.BuildStatments(pContext, nonEmptyToken));
pList.Push(EnterRule.BuildStatments(pContext, ExpressionToken));
//pList.Push(this.Expression);
}
#endregion
#region Public Methods
/// <summary>
/// assists in building a multi parameters list which is executed in the calling function's execute method.
/// </summary>
/// <returns>object</returns>
public override object Execute()
{
object result = null;
//nonEmptyList.Execute();
//result = Expression.Execute();
return result;
}
#endregion
}
/// <summary>
/// Class for the Rule_SingleFunctionParameterList reduction.
/// </summary>
public partial class Rule_SingleFunctionParameterList : EnterRule
{
private EnterRule Expression = null;
#region Constructors
public Rule_SingleFunctionParameterList(Rule_Context pContext, NonterminalToken pToken, Stack<EnterRule> pList) : base(pContext)
{
//<SingleFunctionParameterList> ::= <Expression>
this.Expression = new Rule_Expression(pContext, (NonterminalToken)pToken.Tokens[0]);
pList.Push(this.Expression);
}
#endregion
#region Public Methods
/// <summary>
/// executes the parameter expression of a function.
/// </summary>
/// <returns>object</returns>
public override object Execute()
{
object result = null;
result = this.Expression.Execute();
return result;
}
#endregion
}
/// <summary>
/// Utility class for helper methods for the Epi Functions.
/// </summary>
public static class FunctionUtils
{
public enum DateInterval
{
Second,
Minute,
Hour,
Day,
Month,
Year
}
/// <summary>
/// Gets the appropriate date value based on the date and interval.
/// </summary>
/// <param name="interval">The interval to retrieve from the date.</param>
/// <param name="date">The date to get the value from.</param>
/// <returns></returns>
public static object GetDatePart(DateInterval interval, DateTime date)
{
object returnValue = null;
switch (interval)
{
case DateInterval.Second:
returnValue = date.Second;
break;
case DateInterval.Minute:
returnValue = date.Minute;
break;
case DateInterval.Hour:
returnValue = date.Hour;
break;
case DateInterval.Day:
returnValue = date.Day;
break;
case DateInterval.Month:
returnValue = date.Month;
break;
case DateInterval.Year:
returnValue = date.Year;
break;
}
return returnValue;
}
/// <summary>
/// Gets the difference between two dates based on an interval.
/// </summary>
/// <param name="interval">The interval to use (seconds, minutes, hours, days, months, years)</param>
/// <param name="date1">The date to use for comparison.</param>
/// <param name="date2">The date to compare against the first date.</param>
/// <returns></returns>
public static object GetDateDiff(DateInterval interval, DateTime date1, DateTime date2)
{
object returnValue = null;
TimeSpan t;
double diff = 0;
//returns negative value if date1 is more recent
t = date2 - date1;
switch (interval)
{
case DateInterval.Second:
diff = t.TotalSeconds;
break;
case DateInterval.Minute:
diff = t.TotalMinutes;
break;
case DateInterval.Hour:
diff = t.TotalHours;
break;
case DateInterval.Day:
diff = t.TotalDays;
break;
case DateInterval.Month:
diff = t.TotalDays / 365.25 * 12.0;
break;
case DateInterval.Year:
diff = t.TotalDays / 365.25;
break;
}
returnValue = Convert.ToInt32(diff);
return returnValue;
}
/// <summary>
/// Removes all double quotes from a string.
/// </summary>
/// <param name="s">The string to remove quotes from.</param>
/// <returns>Returns the modified string with no double quotes.</returns>
public static string StripQuotes(string s)
{
return s.Trim(new char[] { '\"' });
}
}
}
| |
// Generated by SharpKit.QooxDoo.Generator
using System;
using System.Collections.Generic;
using SharpKit.Html;
using SharpKit.JavaScript;
namespace qx.ui.mobile.form
{
/// <summary>
/// <para>The NumberField is a single-line number input field. It uses HTML5 input field type
/// “number”.</para>
/// </summary>
[JsType(JsMode.Prototype, Name = "qx.ui.mobile.form.NumberField", OmitOptionalParameters = true, Export = false)]
public partial class NumberField : qx.ui.mobile.form.Input, qx.ui.form.IStringForm
{
#region Events
/// <summary>
/// <para>Fired when the value was modified</para>
/// </summary>
public event Action<qx.eventx.type.Data> OnChangeValue;
/// <summary>
/// <para>The event is fired on every keystroke modifying the value of the field.</para>
/// <para>The method <see cref="qx.event.type.Data.GetData"/> returns the
/// current value of the text field.</para>
/// </summary>
public event Action<qx.eventx.type.Data> OnInput;
#endregion Events
#region Properties
/// <summary>
/// <para>The default CSS class used for this widget. The default CSS class
/// should contain the common appearance of the widget.
/// It is set to the container element of the widget. Use <see cref="AddCssClass"/>
/// to enhance the default appearance of the widget.</para>
/// </summary>
/// <remarks>
/// Allow nulls: true
/// </remarks>
[JsProperty(Name = "defaultCssClass", NativeField = true)]
public string DefaultCssClass { get; set; }
/// <summary>
/// <para>The maximum text field value (may be negative). This value must be larger
/// than <see cref="Maximum"/>.</para>
/// </summary>
[JsProperty(Name = "maximum", NativeField = true)]
public double Maximum { get; set; }
/// <summary>
/// <para>The minimum text field value (may be negative). This value must be smaller
/// than <see cref="Minimum"/>.</para>
/// </summary>
[JsProperty(Name = "minimum", NativeField = true)]
public double Minimum { get; set; }
/// <summary>
/// <para>The amount to increment on each event.</para>
/// </summary>
[JsProperty(Name = "step", NativeField = true)]
public double Step { get; set; }
/// <summary>
/// <para>Whether the <see cref="ChangeValue"/> event should be fired on every key
/// input. If set to true, the changeValue event is equal to the
/// <see cref="Input"/> event.</para>
/// </summary>
[JsProperty(Name = "liveUpdate", NativeField = true)]
public bool LiveUpdate { get; set; }
/// <summary>
/// <para>Maximal number of characters that can be entered in the input field.</para>
/// </summary>
/// <remarks>
/// Allow nulls: true
/// </remarks>
[JsProperty(Name = "maxLength", NativeField = true)]
public double MaxLength { get; set; }
/// <summary>
/// <para>String value which will be shown as a hint if the field is all of:
/// unset, unfocused and enabled. Set to null to not show a placeholder
/// text.</para>
/// </summary>
/// <remarks>
/// Allow nulls: true
/// </remarks>
[JsProperty(Name = "placeholder", NativeField = true)]
public string Placeholder { get; set; }
/// <summary>
/// <para>Whether the field is read only</para>
/// </summary>
/// <remarks>
/// Allow nulls: true
/// </remarks>
[JsProperty(Name = "readOnly", NativeField = true)]
public bool ReadOnly { get; set; }
#endregion Properties
#region Methods
public NumberField() { throw new NotImplementedException(); }
/// <param name="value">The value of the widget.</param>
public NumberField(object value = null) { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property maximum.</para>
/// </summary>
[JsMethod(Name = "getMaximum")]
public double GetMaximum() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property minimum.</para>
/// </summary>
[JsMethod(Name = "getMinimum")]
public double GetMinimum() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property step.</para>
/// </summary>
[JsMethod(Name = "getStep")]
public double GetStep() { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property maximum
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property maximum.</param>
[JsMethod(Name = "initMaximum")]
public void InitMaximum(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property minimum
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property minimum.</param>
[JsMethod(Name = "initMinimum")]
public void InitMinimum(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property step
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property step.</param>
[JsMethod(Name = "initStep")]
public void InitStep(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property maximum.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetMaximum")]
public void ResetMaximum() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property minimum.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetMinimum")]
public void ResetMinimum() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property step.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetStep")]
public void ResetStep() { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property maximum.</para>
/// </summary>
/// <param name="value">New value for property maximum.</param>
[JsMethod(Name = "setMaximum")]
public void SetMaximum(double value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property minimum.</para>
/// </summary>
/// <param name="value">New value for property minimum.</param>
[JsMethod(Name = "setMinimum")]
public void SetMinimum(double value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property step.</para>
/// </summary>
/// <param name="value">New value for property step.</param>
[JsMethod(Name = "setStep")]
public void SetStep(double value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property liveUpdate.</para>
/// </summary>
[JsMethod(Name = "getLiveUpdate")]
public bool GetLiveUpdate() { throw new NotImplementedException(); }
/// <summary>
/// <para>The element’s user set value.</para>
/// </summary>
/// <returns>The value.</returns>
[JsMethod(Name = "getValue")]
public string GetValue() { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property liveUpdate
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property liveUpdate.</param>
[JsMethod(Name = "initLiveUpdate")]
public void InitLiveUpdate(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Check whether the (computed) value of the boolean property liveUpdate equals true.</para>
/// </summary>
[JsMethod(Name = "isLiveUpdate")]
public void IsLiveUpdate() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property liveUpdate.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetLiveUpdate")]
public void ResetLiveUpdate() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the element’s value to its initial value.</para>
/// </summary>
[JsMethod(Name = "resetValue")]
public void ResetValue() { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property liveUpdate.</para>
/// </summary>
/// <param name="value">New value for property liveUpdate.</param>
[JsMethod(Name = "setLiveUpdate")]
public void SetLiveUpdate(bool value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the element’s value.</para>
/// </summary>
/// <param name="value">The new value of the element.</param>
[JsMethod(Name = "setValue")]
public void SetValue(string value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Toggles the (computed) value of the boolean property liveUpdate.</para>
/// </summary>
[JsMethod(Name = "toggleLiveUpdate")]
public void ToggleLiveUpdate() { throw new NotImplementedException(); }
/// <summary>
/// <para>Removes the focus from this widget.</para>
/// </summary>
[JsMethod(Name = "blur")]
public void Blur() { throw new NotImplementedException(); }
/// <summary>
/// <para>Points the focus of the form to this widget.</para>
/// </summary>
[JsMethod(Name = "focus")]
public void Focus() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property maxLength.</para>
/// </summary>
[JsMethod(Name = "getMaxLength")]
public double GetMaxLength() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property placeholder.</para>
/// </summary>
[JsMethod(Name = "getPlaceholder")]
public string GetPlaceholder() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property readOnly.</para>
/// </summary>
[JsMethod(Name = "getReadOnly")]
public bool GetReadOnly() { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property maxLength
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property maxLength.</param>
[JsMethod(Name = "initMaxLength")]
public void InitMaxLength(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property placeholder
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property placeholder.</param>
[JsMethod(Name = "initPlaceholder")]
public void InitPlaceholder(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property readOnly
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property readOnly.</param>
[JsMethod(Name = "initReadOnly")]
public void InitReadOnly(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Check whether the (computed) value of the boolean property readOnly equals true.</para>
/// </summary>
[JsMethod(Name = "isReadOnly")]
public void IsReadOnly() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property maxLength.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetMaxLength")]
public void ResetMaxLength() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property placeholder.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetPlaceholder")]
public void ResetPlaceholder() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property readOnly.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetReadOnly")]
public void ResetReadOnly() { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property maxLength.</para>
/// </summary>
/// <param name="value">New value for property maxLength.</param>
[JsMethod(Name = "setMaxLength")]
public void SetMaxLength(double value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property placeholder.</para>
/// </summary>
/// <param name="value">New value for property placeholder.</param>
[JsMethod(Name = "setPlaceholder")]
public void SetPlaceholder(string value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property readOnly.</para>
/// </summary>
/// <param name="value">New value for property readOnly.</param>
[JsMethod(Name = "setReadOnly")]
public void SetReadOnly(bool value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Toggles the (computed) value of the boolean property readOnly.</para>
/// </summary>
[JsMethod(Name = "toggleReadOnly")]
public void ToggleReadOnly() { throw new NotImplementedException(); }
#endregion Methods
}
}
| |
#region license
// Copyright (c) 2003, 2004, 2005 Rodrigo B. de Oliveira (rbo@acm.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
using Boo.Lang.Compiler.TypeSystem.Core;
using Boo.Lang.Compiler.TypeSystem.Services;
using Boo.Lang.Compiler.Util;
namespace Boo.Lang.Compiler.TypeSystem.Generics
{
public abstract class AbstractGenericParameter : IGenericParameter
{
TypeSystemServices _tss;
protected AbstractGenericParameter(TypeSystemServices tss)
{
_tss = tss;
}
abstract public int GenericParameterPosition { get; }
abstract public bool MustHaveDefaultConstructor { get; }
abstract public Variance Variance { get; }
abstract public bool IsClass { get; }
abstract public bool IsValueType { get; }
abstract public IType[] GetTypeConstraints();
abstract public IEntity DeclaringEntity { get; }
protected IType DeclaringType
{
get
{
if (DeclaringEntity is IType)
return (IType)DeclaringEntity;
if (DeclaringEntity is IMethod)
return ((IMethod)DeclaringEntity).DeclaringType;
return null;
}
}
protected IMethod DeclaringMethod
{
get { return DeclaringEntity as IMethod; }
}
bool IType.IsAbstract
{
get { return false; }
}
bool IType.IsInterface
{
get { return false; }
}
bool IType.IsEnum
{
get { return false; }
}
public bool IsByRef
{
get { return false; }
}
bool IType.IsFinal
{
get { return true; }
}
bool IType.IsArray
{
get { return false; }
}
bool IType.IsPointer
{
get { return false; }
}
public int GetTypeDepth()
{
return DeclaringType.GetTypeDepth() + 1;
}
IType IType.ElementType
{
get { return null; }
}
public IType BaseType
{
get { return FindBaseType(); }
}
public IEntity GetDefaultMember()
{
return null;
}
public IType[] GetInterfaces()
{
return Array.FindAll(GetTypeConstraints(), type => type.IsInterface);
}
public bool IsSubclassOf(IType other)
{
return (other == BaseType || BaseType.IsSubclassOf(other));
}
public virtual bool IsAssignableFrom(IType other)
{
if (other == this)
return true;
if (other.IsNull())
return IsClass;
var otherParameter = other as IGenericParameter;
if (otherParameter != null && Array.Exists(otherParameter.GetTypeConstraints(), constraint => TypeCompatibilityRules.IsAssignableFrom(this, constraint)))
return true;
return false;
}
IGenericTypeInfo IType.GenericInfo
{
get { return null; }
}
IConstructedTypeInfo IType.ConstructedInfo
{
get { return null; }
}
abstract public string Name { get; }
public string FullName
{
get { return string.Format("{0}.{1}", DeclaringEntity.FullName, Name); }
}
public EntityType EntityType
{
get { return EntityType.Type; }
}
public IType Type
{
get { return this; }
}
INamespace INamespace.ParentNamespace
{
get { return DeclaringType; }
}
IEnumerable<IEntity> INamespace.GetMembers()
{
return NullNamespace.EmptyEntityArray;
}
bool INamespace.Resolve(ICollection<IEntity> resultingSet, string name, EntityType typesToConsider)
{
var resolved = false;
foreach (IType type in GetTypeConstraints())
resolved |= type.Resolve(resultingSet, name, typesToConsider);
resolved |= _tss.ObjectType.Resolve(resultingSet, name, typesToConsider);
return resolved;
}
override public string ToString()
{
return Name;
}
bool IEntityWithAttributes.IsDefined(IType attributeType)
{
throw new NotImplementedException();
}
protected IType FindBaseType()
{
foreach (IType type in GetTypeConstraints())
if (!type.IsInterface)
return type;
return _tss.ObjectType;
}
private ArrayTypeCache _arrayTypes;
public IArrayType MakeArrayType(int rank)
{
if (null == _arrayTypes)
_arrayTypes = new ArrayTypeCache(this);
return _arrayTypes.MakeArrayType(rank);
}
public IType MakePointerType()
{
return null;
}
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using System.Xml;
using System.Text;
using Axiom.Core;
using Multiverse.ToolBox;
namespace Multiverse.Tools.WorldEditor
{
class AmbientLight : IWorldObject, IObjectDelete
{
protected WorldEditor app;
protected Boundary parent;
protected ColorEx color;
protected WorldTreeNode parentNode;
protected WorldTreeNode node;
protected bool inTree;
// protected bool inScene;
protected List<ToolStripButton> buttonBar;
#region IWorldObject Members
public AmbientLight(WorldEditor worldEditor, Boundary parent, ColorEx lightColor)
{
this.app = worldEditor;
this.parent = parent;
this.color = lightColor;
}
public AmbientLight(WorldEditor worldEditor, Boundary parent)
{
this.app = worldEditor;
this.parent = parent;
this.color = app.Config.DefaultAmbientLightColor;
}
public AmbientLight(WorldEditor worldEditor, Boundary parent, XmlReader r)
{
this.app = worldEditor;
this.parent = parent;
fromXml(r);
}
public void AddToTree(WorldTreeNode parentNode)
{
this.parentNode = parentNode;
inTree = true;
// create a node for the collection and add it to the parent
this.node = app.MakeTreeNode(this, "Ambient Light");
parentNode.Nodes.Add(node);
// build the menu
CommandMenuBuilder menuBuilder = new CommandMenuBuilder();
menuBuilder.Add("Copy Description", "", app.copyToClipboardMenuButton_Click);
menuBuilder.Add("Help", "Ambient_Light", app.HelpClickHandler);
menuBuilder.Add("Delete", new DeleteObjectCommandFactory(app, parent, this), app.DefaultCommandClickHandler);
node.ContextMenuStrip = menuBuilder.Menu;
// int count; (unused)
buttonBar = menuBuilder.ButtonBar;
}
[BrowsableAttribute(false)]
public bool AcceptObjectPlacement
{
get
{
return false;
}
set
{
//not implemented for this type of object
}
}
[BrowsableAttribute(false)]
public bool WorldViewSelectable
{
get
{
return false;
}
set
{
// This property is not relevent for this object.
}
}
public void Clone(IWorldContainer copyParent)
{
AmbientLight clone = new AmbientLight(app, parent, color);
copyParent.Add(clone);
}
public void UpdateScene(UpdateTypes type, UpdateHint hint)
{
}
[BrowsableAttribute(false)]
public bool IsGlobal
{
get
{
return false;
}
}
[BrowsableAttribute(false)]
public bool IsTopLevel
{
get
{
return false;
}
}
[BrowsableAttribute(false)]
public string ObjectAsString
{
get
{
string objString = String.Format("Name:{0}\r\n", ObjectType);
objString += String.Format("\tColor:\r\n");
objString += String.Format("\t\tR={0}\r\n", color.r);
objString += String.Format("\t\tG={0}\r\n", color.g);
objString += String.Format("\t\tB={0}\r\n", color.b);
objString += "\r\n";
return objString;
}
}
[BrowsableAttribute(false)]
public List<ToolStripButton> ButtonBar
{
get
{
return buttonBar;
}
}
[EditorAttribute(typeof(ColorValueUITypeEditor), typeof(System.Drawing.Design.UITypeEditor)),
DescriptionAttribute("Color of the ambient light (click [...] to use the color picker dialog to select a color)."), CategoryAttribute("Miscellaneous")]
public ColorEx Color
{
get
{
return color;
}
set
{
color = value;
}
}
public void RemoveFromTree()
{
if (node.IsSelected)
{
node.UnSelect();
}
parentNode.Nodes.Remove(node);
parentNode = null;
node = null;
}
public void AddToScene()
{
return;
}
public void RemoveFromScene()
{
return;
}
public void CheckAssets()
{
}
public void ToXml(System.Xml.XmlWriter w)
{
w.WriteStartElement("AmbientLight");
w.WriteStartElement("Color");
w.WriteAttributeString("R", this.color.r.ToString());
w.WriteAttributeString("G", this.color.g.ToString());
w.WriteAttributeString("B", this.color.b.ToString());
w.WriteEndElement(); // end color
w.WriteEndElement(); // end AmbientLight
}
public void fromXml(XmlReader r)
{
//parse the sub-elements
while (r.Read())
{
// look for the start of an element
if (r.NodeType == XmlNodeType.Element)
{
// parse that element
// save the name of the element
string elementName = r.Name;
switch (elementName)
{
case "Color":
color = XmlHelperClass.ParseColorAttributes(r);
break;
}
}
else if (r.NodeType == XmlNodeType.EndElement)
{
break;
}
}
}
[BrowsableAttribute(false)]
public Axiom.MathLib.Vector3 FocusLocation
{
get
{
return this.parent.FocusLocation;
}
}
[DescriptionAttribute("The type of this object."), CategoryAttribute("Miscellaneous"), BrowsableAttribute(true)]
public string ObjectType
{
get
{
return "AmbientLight";
}
}
[BrowsableAttribute(false)]
public bool Highlight
{
get
{
return parent.Highlight;
}
set
{
parent.Highlight = value;
}
}
[BrowsableAttribute(false)]
public WorldTreeNode Node
{
get
{
return node;
}
}
public void ToManifest(System.IO.StreamWriter w)
{
}
#endregion
#region IWorldDelete
[BrowsableAttribute(false)]
public IWorldContainer Parent
{
get
{
return parent;
}
}
#endregion IWorldDelete
#region IDisposable Members
public void Dispose()
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="jet_commit_id.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation.
// </copyright>
// <summary>
// Information context surrounded data emitted from JET_PFNEMITLOGDATA.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Microsoft.Isam.Esent.Interop.Windows8
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.InteropServices;
/// <summary>
/// Information context surrounded data emitted from JET_PFNEMITLOGDATA.
/// </summary>
[SuppressMessage(
"Microsoft.StyleCop.CSharp.NamingRules",
"SA1305:FieldNamesMustNotUseHungarianNotation",
Justification = "This should match the name of the unmanaged structure.")]
[SuppressMessage(
"Microsoft.StyleCop.CSharp.NamingRules",
"SA1307:AccessibleFieldsMustBeginWithUpperCaseLetter",
Justification = "This should match the unmanaged API, which isn't capitalized.")]
[StructLayout(LayoutKind.Sequential)]
[Serializable]
internal struct NATIVE_COMMIT_ID
{
/// <summary>
/// Signature for this log sequence.
/// </summary>
public NATIVE_SIGNATURE signLog;
/// <summary>
/// Reserved value for proper alignment on x86.
/// </summary>
public int reserved;
/// <summary>
/// Commit-id for this commit transaction.
/// </summary>
public long commitId;
}
/// <summary>
/// Information context surrounded data emitted from JET_PFNEMITLOGDATA.
/// </summary>
[SuppressMessage(
"Microsoft.StyleCop.CSharp.NamingRules",
"SA1300:ElementMustBeginWithUpperCaseLetter",
Justification = "This should match the unmanaged API, which isn't capitalized.")]
public class JET_COMMIT_ID : IComparable<JET_COMMIT_ID>, IEquatable<JET_COMMIT_ID>
{
/// <summary>
/// Signature for this log sequence.
/// </summary>
private readonly JET_SIGNATURE signLog;
/// <summary>
/// Commit-id for this commit transaction.
/// </summary>
private readonly long commitId;
/// <summary>
/// Initializes a new instance of the <see cref="JET_COMMIT_ID"/> class.
/// </summary>
/// <param name="native">The native version of the structure.
/// to use as the data source.</param>
internal JET_COMMIT_ID(NATIVE_COMMIT_ID native)
{
this.signLog = new JET_SIGNATURE(native.signLog);
this.commitId = native.commitId;
}
#if MANAGEDESENT_ON_CORECLR
/// <summary>
/// Initializes a new instance of the <see cref="JET_COMMIT_ID"/> class. This
/// is for testing purposes only.
/// </summary>
/// <remarks>This is being implemented in new Windows UI only because the Desktop test
/// code uses reflection to create the object, and the new Windows UI reflection does not
/// appear to work in this scenario -- Activator.CreateInstance() reflection seems to only
/// work with exising public constructors.</remarks>
/// <param name="signature">The log signature for this sequence.</param>
/// <param name="commitId">The commit identifier for this commit transaction.</param>
internal JET_COMMIT_ID(JET_SIGNATURE signature, long commitId)
{
this.signLog = signature;
this.commitId = commitId;
}
#endif // MANAGEDESENT_ON_CORECLR
/// <summary>
/// Determine whether one commitid is before another commitid.
/// </summary>
/// <param name="lhs">The first commitid to compare.</param>
/// <param name="rhs">The second commitid to compare.</param>
/// <returns>True if lhs comes before rhs.</returns>
public static bool operator <(JET_COMMIT_ID lhs, JET_COMMIT_ID rhs)
{
return lhs.CompareTo(rhs) < 0;
}
/// <summary>
/// Determine whether one commitid is before another commitid.
/// </summary>
/// <param name="lhs">The first commitid to compare.</param>
/// <param name="rhs">The second commitid to compare.</param>
/// <returns>True if lhs comes after rhs.</returns>
public static bool operator >(JET_COMMIT_ID lhs, JET_COMMIT_ID rhs)
{
return lhs.CompareTo(rhs) > 0;
}
/// <summary>
/// Determine whether one commitid is before another commitid.
/// </summary>
/// <param name="lhs">The first commitid to compare.</param>
/// <param name="rhs">The second commitid to compare.</param>
/// <returns>True if lhs comes before or equal to rhs.</returns>
public static bool operator <=(JET_COMMIT_ID lhs, JET_COMMIT_ID rhs)
{
return lhs.CompareTo(rhs) <= 0;
}
/// <summary>
/// Determine whether one commitid is before another commitid.
/// </summary>
/// <param name="lhs">The first commitid to compare.</param>
/// <param name="rhs">The second commitid to compare.</param>
/// <returns>True if lhs comes after or equal to rhs.</returns>
public static bool operator >=(JET_COMMIT_ID lhs, JET_COMMIT_ID rhs)
{
return lhs.CompareTo(rhs) >= 0;
}
/// <summary>
/// Determine whether one commitid is is equal to another commitid.
/// </summary>
/// <param name="lhs">The first commitid to compare.</param>
/// <param name="rhs">The second commitid to compare.</param>
/// <returns>True if lhs comes is equal to rhs.</returns>
public static bool operator ==(JET_COMMIT_ID lhs, JET_COMMIT_ID rhs)
{
return lhs.CompareTo(rhs) == 0;
}
/// <summary>
/// Determine whether one commitid is not equal to another commitid.
/// </summary>
/// <param name="lhs">The first commitid to compare.</param>
/// <param name="rhs">The second commitid to compare.</param>
/// <returns>True if lhs comes is not equal to rhs.</returns>
public static bool operator !=(JET_COMMIT_ID lhs, JET_COMMIT_ID rhs)
{
return lhs.CompareTo(rhs) != 0;
}
/// <summary>
/// Generate a string representation of the structure.
/// </summary>
/// <returns>The structure as a string.</returns>
public override string ToString()
{
return string.Format(
CultureInfo.InvariantCulture,
"JET_COMMIT_ID({0}:{1}",
this.signLog,
this.commitId);
}
/// <summary>
/// Returns a value comparing this instance with another.
/// </summary>
/// <param name="other">An instance to compare with this instance.</param>
/// <returns>
/// A signed value representing the relative positions of the instances.
/// </returns>
public int CompareTo(JET_COMMIT_ID other)
{
if ((object)other == null)
{
return this.commitId > 0 ? 1 : 0;
}
if (this.signLog != other.signLog)
{
throw new ArgumentException("The commit-ids belong to different log-streams");
}
return this.commitId.CompareTo(other.commitId);
}
/// <summary>
/// Returns a value indicating whether this instance is equal
/// to another instance.
/// </summary>
/// <param name="other">An object to compare with this instance.</param>
/// <returns>true if the two instances are equal.</returns>
public bool Equals(JET_COMMIT_ID other)
{
return this.CompareTo(other) == 0;
}
/// <summary>
/// Returns a value indicating whether this instance is equal
/// to another instance.
/// </summary>
/// <param name="obj">An object to compare with this instance.</param>
/// <returns>true if the two instances are equal.</returns>
public override bool Equals(object obj)
{
if (obj == null || GetType() != obj.GetType())
{
return false;
}
return this.CompareTo((JET_COMMIT_ID)obj) == 0;
}
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>The hash code for this instance.</returns>
public override int GetHashCode()
{
return this.commitId.GetHashCode()
^ this.signLog.GetHashCode();
}
/// <summary>
/// Converts the class to a NATIVE_COMMIT_ID structure.
/// </summary>
/// <returns>A NATIVE_COMMIT_ID structure.</returns>
internal NATIVE_COMMIT_ID GetNativeCommitId()
{
NATIVE_COMMIT_ID native = new NATIVE_COMMIT_ID();
native.signLog = this.signLog.GetNativeSignature();
native.commitId = checked((long)this.commitId);
return native;
}
}
}
| |
using YAF.Lucene.Net.Support;
using System.IO;
using System.Text;
namespace YAF.Lucene.Net.Search
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Encapsulates sort criteria for returned hits.
///
/// <para/>The fields used to determine sort order must be carefully chosen.
/// <see cref="Documents.Document"/>s must contain a single term in such a field,
/// and the value of the term should indicate the document's relative position in
/// a given sort order. The field must be indexed, but should not be tokenized,
/// and does not need to be stored (unless you happen to want it back with the
/// rest of your document data). In other words:
///
/// <para/><code>document.Add(new Field("byNumber", x.ToString(CultureInfo.InvariantCulture), Field.Store.NO, Field.Index.NOT_ANALYZED));</code>
///
///
/// <para/><h3>Valid Types of Values</h3>
///
/// <para/>There are four possible kinds of term values which may be put into
/// sorting fields: <see cref="int"/>s, <see cref="long"/>s, <see cref="float"/>s, or <see cref="string"/>s. Unless
/// <see cref="SortField"/> objects are specified, the type of value
/// in the field is determined by parsing the first term in the field.
///
/// <para/><see cref="int"/> term values should contain only digits and an optional
/// preceding negative sign. Values must be base 10 and in the range
/// <see cref="int.MinValue"/> and <see cref="int.MaxValue"/> inclusive.
/// Documents which should appear first in the sort
/// should have low value integers, later documents high values
/// (i.e. the documents should be numbered <c>1..n</c> where
/// <c>1</c> is the first and <c>n</c> the last).
///
/// <para/><see cref="long"/> term values should contain only digits and an optional
/// preceding negative sign. Values must be base 10 and in the range
/// <see cref="long.MinValue"/> and <see cref="long.MaxValue"/> inclusive.
/// Documents which should appear first in the sort
/// should have low value integers, later documents high values.
///
/// <para/><see cref="float"/> term values should conform to values accepted by
/// <see cref="float"/> (except that <c>NaN</c>
/// and <c>Infinity</c> are not supported).
/// <see cref="Documents.Document"/>s which should appear first in the sort
/// should have low values, later documents high values.
///
/// <para/><see cref="string"/> term values can contain any valid <see cref="string"/>, but should
/// not be tokenized. The values are sorted according to their
/// comparable natural order (<see cref="System.StringComparer.Ordinal"/>). Note that using this type
/// of term value has higher memory requirements than the other
/// two types.
///
/// <para/><h3>Object Reuse</h3>
///
/// <para/>One of these objects can be
/// used multiple times and the sort order changed between usages.
///
/// <para/>This class is thread safe.
///
/// <para/><h3>Memory Usage</h3>
///
/// <para/>Sorting uses of caches of term values maintained by the
/// internal HitQueue(s). The cache is static and contains an <see cref="int"/>
/// or <see cref="float"/> array of length <c>IndexReader.MaxDoc</c> for each field
/// name for which a sort is performed. In other words, the size of the
/// cache in bytes is:
///
/// <para/><code>4 * IndexReader.MaxDoc * (# of different fields actually used to sort)</code>
///
/// <para/>For <see cref="string"/> fields, the cache is larger: in addition to the
/// above array, the value of every term in the field is kept in memory.
/// If there are many unique terms in the field, this could
/// be quite large.
///
/// <para/>Note that the size of the cache is not affected by how many
/// fields are in the index and <i>might</i> be used to sort - only by
/// the ones actually used to sort a result set.
///
/// <para/>Created: Feb 12, 2004 10:53:57 AM
/// <para/>
/// @since lucene 1.4
/// </summary>
public class Sort
{
/// <summary>
/// Represents sorting by computed relevance. Using this sort criteria returns
/// the same results as calling
/// <see cref="IndexSearcher.Search(Query, int)"/>without a sort criteria,
/// only with slightly more overhead.
/// </summary>
public static readonly Sort RELEVANCE = new Sort();
/// <summary>
/// Represents sorting by index order. </summary>
public static readonly Sort INDEXORDER = new Sort(SortField.FIELD_DOC);
// internal representation of the sort criteria
internal SortField[] fields;
/// <summary>
/// Sorts by computed relevance. This is the same sort criteria as calling
/// <see cref="IndexSearcher.Search(Query, int)"/> without a sort criteria,
/// only with slightly more overhead.
/// </summary>
public Sort()
: this(SortField.FIELD_SCORE)
{
}
/// <summary>
/// Sorts by the criteria in the given <see cref="SortField"/>. </summary>
public Sort(SortField field)
{
SetSort(field);
}
/// <summary>
/// Sorts in succession by the criteria in each <see cref="SortField"/>. </summary>
public Sort(params SortField[] fields)
{
SetSort(fields);
}
/// <summary>Sets the sort to the given criteria. </summary>
public virtual void SetSort(SortField field)
{
this.fields = new SortField[] { field };
}
/// <summary>Sets the sort to the given criteria in succession. </summary>
public virtual void SetSort(params SortField[] fields)
{
this.fields = fields;
}
/// <summary> Representation of the sort criteria.</summary>
/// <returns> Array of <see cref="SortField"/> objects used in this sort criteria
/// </returns>
[WritableArray]
public virtual SortField[] GetSort()
{
return fields;
}
/// <summary>
/// Rewrites the <see cref="SortField"/>s in this <see cref="Sort"/>, returning a new <see cref="Sort"/> if any of the fields
/// changes during their rewriting.
/// <para/>
/// @lucene.experimental
/// </summary>
/// <param name="searcher"> <see cref="IndexSearcher"/> to use in the rewriting </param>
/// <returns> <c>this</c> if the Sort/Fields have not changed, or a new <see cref="Sort"/> if there
/// is a change </returns>
/// <exception cref="IOException"> Can be thrown by the rewriting</exception>
public virtual Sort Rewrite(IndexSearcher searcher)
{
bool changed = false;
SortField[] rewrittenSortFields = new SortField[fields.Length];
for (int i = 0; i < fields.Length; i++)
{
rewrittenSortFields[i] = fields[i].Rewrite(searcher);
if (fields[i] != rewrittenSortFields[i])
{
changed = true;
}
}
return (changed) ? new Sort(rewrittenSortFields) : this;
}
public override string ToString()
{
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < fields.Length; i++)
{
buffer.Append(fields[i].ToString());
if ((i + 1) < fields.Length)
{
buffer.Append(',');
}
}
return buffer.ToString();
}
/// <summary>
/// Returns <c>true</c> if <paramref name="o"/> is equal to this. </summary>
public override bool Equals(object o)
{
if (this == o)
{
return true;
}
if (!(o is Sort))
{
return false;
}
Sort other = (Sort)o;
return Arrays.Equals(this.fields, other.fields);
}
/// <summary>
/// Returns a hash code value for this object. </summary>
public override int GetHashCode()
{
return 0x45aaf665 + Arrays.GetHashCode(fields);
}
/// <summary>
/// Returns <c>true</c> if the relevance score is needed to sort documents. </summary>
public virtual bool NeedsScores
{
get
{
foreach (SortField sortField in fields)
{
if (sortField.NeedsScores)
{
return true;
}
}
return false;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using JetBrains.Annotations;
using JoinRpg.Data.Interfaces;
using JoinRpg.Data.Interfaces.Claims;
using JoinRpg.Data.Write.Interfaces;
using JoinRpg.DataModel;
using JoinRpg.Domain;
using JoinRpg.Helpers;
using JoinRpg.Interfaces;
namespace JoinRpg.Services.Impl
{
//TODO: Split on specific and not specific to domain helpers
public class DbServiceImplBase
{
protected readonly IUnitOfWork UnitOfWork;
private readonly ICurrentUserAccessor currentUserAccessor;
protected IUserRepository UserRepository => _userRepository.Value;
private readonly Lazy<IUserRepository> _userRepository;
protected IAccommodationRepository AccomodationRepository => _accomodationRepository.Value;
private readonly Lazy<IAccommodationRepository> _accomodationRepository;
protected IProjectRepository ProjectRepository => _projectRepository.Value;
private readonly Lazy<IProjectRepository> _projectRepository;
protected IClaimsRepository ClaimsRepository => _claimRepository.Value;
private readonly Lazy<IClaimsRepository> _claimRepository;
protected IForumRepository ForumRepository => _forumRepository.Value;
private readonly Lazy<IForumRepository> _forumRepository;
private readonly Lazy<IPlotRepository> _plotRepository;
protected IPlotRepository PlotRepository => _plotRepository.Value;
private readonly Lazy<ICharacterRepository> _charactersRepository;
protected ICharacterRepository CharactersRepository => _charactersRepository.Value;
private int? _impersonatedUserId;
/// <summary>
/// Returns current user database Id
/// </summary>
protected int CurrentUserId => _impersonatedUserId ?? currentUserAccessor.UserId;
// TODO: Fix impersonation
/// <summary>
/// Returns true if current user is admin
/// </summary>
protected bool IsCurrentUserAdmin => currentUserAccessor.IsAdmin;
/// <summary>
/// Time of service creation. Used to mark consistent time for all operations performed by service
/// </summary>
protected DateTime Now { get; }
protected DbServiceImplBase(IUnitOfWork unitOfWork, ICurrentUserAccessor currentUserAccessor)
{
UnitOfWork = unitOfWork;
this.currentUserAccessor = currentUserAccessor;
_userRepository = new Lazy<IUserRepository>(unitOfWork.GetUsersRepository);
_projectRepository = new Lazy<IProjectRepository>(unitOfWork.GetProjectRepository);
_claimRepository = new Lazy<IClaimsRepository>(unitOfWork.GetClaimsRepository);
_plotRepository = new Lazy<IPlotRepository>(unitOfWork.GetPlotRepository);
_forumRepository = new Lazy<IForumRepository>(unitOfWork.GetForumRepository);
_accomodationRepository = new Lazy<IAccommodationRepository>(UnitOfWork.GetAccomodationRepository);
_charactersRepository =
new Lazy<ICharacterRepository>(unitOfWork.GetCharactersRepository);
Now = DateTime.UtcNow;
}
protected void StartImpersonate(int userId) => _impersonatedUserId = userId;
protected void ResetImpersonation() => _impersonatedUserId = null;
[NotNull]
protected async Task<T> LoadProjectSubEntityAsync<T>(int projectId, int subentityId)
where T : class, IProjectEntity
{
var field = await UnitOfWork.GetDbSet<T>().FindAsync(subentityId);
if (field != null && field.Project.ProjectId == projectId)
{
return field;
}
throw new DbEntityValidationException();
}
protected static string Required(string stringValue)
{
if (string.IsNullOrWhiteSpace(stringValue))
{
throw new DbEntityValidationException();
}
return stringValue.Trim();
}
protected static IReadOnlyCollection<T> Required<T>(IReadOnlyCollection<T> items)
{
if (items.Count == 0)
{
throw new DbEntityValidationException();
}
return items;
}
protected static IReadOnlyCollection<T> Required<T>(
Expression<Func<IReadOnlyCollection<T>>> itemsLambda)
{
var name = itemsLambda.AsPropertyName();
var items = itemsLambda.Compile()();
if (items.Count == 0)
{
throw new FieldRequiredException(name);
}
return items;
}
protected bool SmartDelete<T>(T field) where T : class, IDeletableSubEntity
{
if (field == null)
{
return false;
}
if (field.CanBePermanentlyDeleted)
{
_ = UnitOfWork.GetDbSet<T>().Remove(field);
return true;
}
else
{
field.IsActive = false;
return false;
}
}
[ItemNotNull]
protected async Task<int[]> ValidateCharacterGroupList(int projectId,
IReadOnlyCollection<int> groupIds,
bool ensureNotSpecial = false)
{
var characterGroups = await ProjectRepository.LoadGroups(projectId, groupIds);
if (characterGroups.Count != groupIds.Distinct().Count())
{
var missing = string.Join(", ",
groupIds.Except(characterGroups.Select(cg => cg.CharacterGroupId)));
throw new Exception($"Groups {missing} doesn't belong to project");
}
if (ensureNotSpecial && characterGroups.Any(cg => cg.IsSpecial))
{
throw new DbEntityValidationException();
}
return groupIds.ToArray();
}
protected async Task<ICollection<Character>> ValidateCharactersList(int projectId,
IReadOnlyCollection<int> characterIds)
{
var characters =
await CharactersRepository.GetCharacters(projectId, characterIds);
if (characters.Count != characterIds.Distinct().Count())
{
throw new DbEntityValidationException();
}
return characters.ToArray();
}
protected void MarkCreatedNow([NotNull] ICreatedUpdatedTrackedForEntity entity)
{
entity.UpdatedAt = entity.CreatedAt = Now;
entity.UpdatedById = entity.CreatedById = CurrentUserId;
}
protected void Create<T>([NotNull] T entity)
where T : class, ICreatedUpdatedTrackedForEntity
{
MarkCreatedNow(entity);
_ = UnitOfWork.GetDbSet<T>().Add(entity);
}
protected void MarkChanged([NotNull] ICreatedUpdatedTrackedForEntity entity)
{
entity.UpdatedAt = Now;
entity.UpdatedById = CurrentUserId;
}
protected void MarkTreeModified([NotNull] Project project) => project.CharacterTreeModifiedAt = Now;
protected async Task<User> GetCurrentUser() => await UserRepository.GetById(CurrentUserId);
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Newtonsoft.Json.Linq;
using NUnit.Framework;
using ReactNative.UIManager;
using ReactNative.UIManager.Annotations;
using System;
namespace ReactNative.Tests.UIManager
{
[TestFixture]
public class ViewManagersPropCacheTests
{
[Test]
public void ViewManagersPropCache_ArgumentChecks()
{
AssertEx.Throws<ArgumentNullException>(
() => ViewManagersPropCache.GetNativePropsForView<object>(null, typeof(object)),
ex => Assert.AreEqual("viewManagerType", ex.ParamName));
AssertEx.Throws<ArgumentNullException>(
() => ViewManagersPropCache.GetNativePropsForView<object>(typeof(object), null),
ex => Assert.AreEqual("shadowNodeType", ex.ParamName));
AssertEx.Throws<ArgumentNullException>(
() => ViewManagersPropCache.GetNativePropSettersForViewManagerType<object>(null),
ex => Assert.AreEqual("type", ex.ParamName));
AssertEx.Throws<ArgumentNullException>(
() => ViewManagersPropCache.GetNativePropSettersForShadowNodeType
(null),
ex => Assert.AreEqual("type", ex.ParamName));
}
[Test]
public void ViewManagersPropCache_ViewManager_Empty()
{
var setters = ViewManagersPropCache.GetNativePropSettersForShadowNodeType(typeof(EmptyTest));
Assert.AreEqual(0, setters.Count);
}
[Test]
public void ViewManagersPropCache_ShadowNode_Empty()
{
var setters = ViewManagersPropCache.GetNativePropSettersForShadowNodeType(typeof(ReactShadowNode));
Assert.AreEqual(0, setters.Count);
}
[Test]
public void ViewManagersPropCache_ViewManager_Set()
{
var instance = new ViewManagerValueTest();
var setters = ViewManagersPropCache.GetNativePropSettersForViewManagerType<object>(typeof(ViewManagerValueTest));
Assert.AreEqual(3, setters.Count);
var props = new JObject
{
{ "Foo", "v1" },
{ "Bar1", "v2" },
{ "Bar2", "v3" },
};
AssertEx.Throws<NotSupportedException>(() => setters["Foo"].UpdateShadowNodeProp(new ShadowNodeValueTest(), props));
AssertEx.Throws<ArgumentNullException>(
() => setters["Foo"].UpdateViewManagerProp(null, null, props),
ex => Assert.AreEqual("viewManager", ex.ParamName));
AssertEx.Throws<ArgumentNullException>(
() => setters["Foo"].UpdateViewManagerProp(instance, null, null),
ex => Assert.AreEqual("props", ex.ParamName));
setters["Foo"].UpdateViewManagerProp(instance, null, props);
setters["Bar1"].UpdateViewManagerProp(instance, null, props);
setters["Bar2"].UpdateViewManagerProp(instance, null, props);
Assert.AreEqual("v1", instance.FooValue);
Assert.AreEqual("v2", instance.BarValues[0]);
Assert.AreEqual("v3", instance.BarValues[1]);
}
[Test]
public void ViewManagersPropCache_ShadowNode_Set()
{
var instance = new ShadowNodeValueTest();
var setters = ViewManagersPropCache.GetNativePropSettersForShadowNodeType(typeof(ShadowNodeValueTest));
Assert.AreEqual(3, setters.Count);
var props = new JObject
{
{ "Foo", 42 },
{ "Qux1", "v2" },
{ "Qux2", "v3" },
};
AssertEx.Throws<NotSupportedException>(() => setters["Foo"].UpdateViewManagerProp(new ViewManagerValueTest(), null, props));
AssertEx.Throws<ArgumentNullException>(
() => setters["Foo"].UpdateShadowNodeProp(null, props),
ex => Assert.AreEqual("shadowNode", ex.ParamName));
AssertEx.Throws<ArgumentNullException>(
() => setters["Foo"].UpdateShadowNodeProp(instance, null),
ex => Assert.AreEqual("props", ex.ParamName));
setters["Foo"].UpdateShadowNodeProp(instance, props);
setters["Qux1"].UpdateShadowNodeProp(instance, props);
setters["Qux2"].UpdateShadowNodeProp(instance, props);
Assert.AreEqual(42, instance.FooValue);
Assert.AreEqual("v2", instance.QuxValues[0]);
Assert.AreEqual("v3", instance.QuxValues[1]);
}
[Test]
public void ViewManagersPropCache_GetNativePropsForView()
{
var props = ViewManagersPropCache.GetNativePropsForView<object>(typeof(ViewManagerValueTest), typeof(ShadowNodeValueTest));
Assert.AreEqual(5, props.Count);
Assert.AreEqual("number", props["Foo"].Value<string>());
Assert.AreEqual("String", props["Bar1"].Value<string>());
Assert.AreEqual("String", props["Bar2"].Value<string>());
Assert.AreEqual("String", props["Qux1"].Value<string>());
Assert.AreEqual("String", props["Qux2"].Value<string>());
}
[Test]
public void ViewManagersPropCache_Defaults()
{
var instance = new DefaultsTest();
var setters = ViewManagersPropCache.GetNativePropSettersForViewManagerType<object>(typeof(DefaultsTest));
var props = new JObject();
instance.ByteValue = byte.MaxValue;
instance.SByteValue = sbyte.MaxValue;
instance.Int16Value = short.MaxValue;
instance.UInt16Value = ushort.MaxValue;
instance.Int32Value = int.MaxValue;
instance.UInt32Value = uint.MaxValue;
instance.Int64Value = long.MaxValue;
instance.UInt64Value = ulong.MaxValue;
instance.SingleValue = float.MaxValue;
instance.DoubleValue = double.MaxValue;
instance.DecimalValue = decimal.MaxValue;
instance.BooleanValue = true;
instance.StringValue = "foo";
instance.ArrayValue = new int[0];
instance.MapValue = new object();
instance.NullableValue = true;
instance.GroupValue = new[] { "a", "b", "c" };
setters["TestByte"].UpdateViewManagerProp(instance, null, props);
setters["TestSByte"].UpdateViewManagerProp(instance, null, props);
setters["TestInt16"].UpdateViewManagerProp(instance, null, props);
setters["TestUInt16"].UpdateViewManagerProp(instance, null, props);
setters["TestInt32"].UpdateViewManagerProp(instance, null, props);
setters["TestUInt32"].UpdateViewManagerProp(instance, null, props);
setters["TestInt64"].UpdateViewManagerProp(instance, null, props);
setters["TestUInt64"].UpdateViewManagerProp(instance, null, props);
setters["TestSingle"].UpdateViewManagerProp(instance, null, props);
setters["TestDouble"].UpdateViewManagerProp(instance, null, props);
setters["TestDecimal"].UpdateViewManagerProp(instance, null, props);
setters["TestBoolean"].UpdateViewManagerProp(instance, null, props);
setters["TestString"].UpdateViewManagerProp(instance, null, props);
setters["TestArray"].UpdateViewManagerProp(instance, null, props);
setters["TestMap"].UpdateViewManagerProp(instance, null, props);
setters["TestNullable"].UpdateViewManagerProp(instance, null, props);
setters["foo"].UpdateViewManagerProp(instance, null, props);
setters["bar"].UpdateViewManagerProp(instance, null, props);
setters["baz"].UpdateViewManagerProp(instance, null, props);
Assert.AreEqual(0, instance.ByteValue);
Assert.AreEqual(0, instance.SByteValue);
Assert.AreEqual(0, instance.Int16Value);
Assert.AreEqual(0, instance.UInt16Value);
Assert.AreEqual(0, instance.Int32Value);
Assert.AreEqual((uint)0, instance.UInt32Value);
Assert.AreEqual(0, instance.Int64Value);
Assert.AreEqual((ulong)0, instance.UInt64Value);
Assert.AreEqual(0, instance.SingleValue);
Assert.AreEqual(0, instance.DoubleValue);
Assert.AreEqual(0, instance.DecimalValue);
Assert.IsFalse(instance.BooleanValue);
Assert.IsNull(instance.StringValue);
Assert.IsNull(instance.ArrayValue);
Assert.IsNull(instance.MapValue);
Assert.IsFalse(instance.NullableValue.HasValue);
Assert.IsNull(instance.GroupValue[0]);
Assert.IsNull(instance.GroupValue[1]);
Assert.IsNull(instance.GroupValue[2]);
}
class EmptyTest : MockViewManager
{
}
class ViewManagerValueTest : MockViewManager
{
public string FooValue;
[ReactProp("Foo")]
public void Foo(object element, string value)
{
FooValue = value;
}
public string[] BarValues = new string[2];
[ReactPropGroup("Bar1", "Bar2")]
public void Bar(object element, int index, string value)
{
BarValues[index] = value;
}
}
class ShadowNodeValueTest : ReactShadowNode
{
public int FooValue;
[ReactProp("Foo")]
public void Foo(int value)
{
FooValue = value;
}
public string[] QuxValues = new string[2];
[ReactPropGroup("Qux1", "Qux2")]
public void Qux(int index, string value)
{
QuxValues[index] = value;
}
}
class DefaultsTest : MockViewManager
{
#region ViewManager Test Methods
public byte ByteValue;
public sbyte SByteValue;
public short Int16Value;
public ushort UInt16Value;
public int Int32Value;
public uint UInt32Value;
public long Int64Value;
public ulong UInt64Value;
public float SingleValue;
public double DoubleValue;
public decimal DecimalValue;
public bool BooleanValue;
public string StringValue;
public int[] ArrayValue;
public object MapValue;
public bool? NullableValue;
public string[] GroupValue = new string[3];
[ReactProp("TestByte")]
public void TestByte(object element, byte value)
{
ByteValue = value;
}
[ReactProp("TestSByte")]
public void TestSByte(object element, sbyte value)
{
SByteValue = value;
}
[ReactProp("TestInt16")]
public void TestInt16(object element, short value)
{
Int16Value = value;
}
[ReactProp("TestUInt16")]
public void TestUInt16(object element, ushort value)
{
UInt16Value = value;
}
[ReactProp("TestInt32")]
public void TestInt32(object element, int value)
{
Int32Value = value;
}
[ReactProp("TestUInt32")]
public void TestUInt32(object element, uint value)
{
UInt32Value = value;
}
[ReactProp("TestInt64")]
public void TestInt64(object element, long value)
{
Int64Value = value;
}
[ReactProp("TestUInt64")]
public void TestUInt64(object element, ulong value)
{
UInt64Value = value;
}
[ReactProp("TestSingle")]
public void TestSingle(object element, float value)
{
SingleValue = value;
}
[ReactProp("TestDouble")]
public void TestDouble(object element, double value)
{
DoubleValue = value;
}
[ReactProp("TestDecimal")]
public void TestDecimal(object element, decimal value)
{
DecimalValue = value;
}
[ReactProp("TestBoolean")]
public void TestBoolean(object element, bool value)
{
BooleanValue = value;
}
[ReactProp("TestString")]
public void TestString(object element, string value)
{
StringValue = value;
}
[ReactProp("TestArray")]
public void TestArray(object element, int[] value)
{
ArrayValue = value;
}
[ReactProp("TestNullable")]
public void TestNullable(object element, bool? value)
{
NullableValue = value;
}
[ReactProp("TestMap")]
public void TestMap(object element, object value)
{
MapValue = value;
}
[ReactPropGroup("foo", "bar", "baz")]
public void TestGroup(object element, int index, string value)
{
GroupValue[index] = value;
}
#endregion
}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
namespace _4PosBackOffice.NET
{
[Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]
partial class frmOrder
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmOrder() : base()
{
FormClosed += frmOrder_FormClosed;
Load += frmOrder_Load;
KeyPress += frmOrder_KeyPress;
//This call is required by the Windows Form Designer.
InitializeComponent();
}
//Form overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]
protected override void Dispose(bool Disposing)
{
if (Disposing) {
if ((components != null)) {
components.Dispose();
}
}
base.Dispose(Disposing);
}
//Required by the Windows Form Designer
private System.ComponentModel.IContainer components;
public System.Windows.Forms.ToolTip ToolTip1;
public System.Windows.Forms.Button _cmdInformation_1;
public System.Windows.Forms.Button _cmdInformation_0;
private System.Windows.Forms.Button withEventsField_cmdNext;
public System.Windows.Forms.Button cmdNext {
get { return withEventsField_cmdNext; }
set {
if (withEventsField_cmdNext != null) {
withEventsField_cmdNext.Click -= cmdNext_Click;
}
withEventsField_cmdNext = value;
if (withEventsField_cmdNext != null) {
withEventsField_cmdNext.Click += cmdNext_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdBack;
public System.Windows.Forms.Button cmdBack {
get { return withEventsField_cmdBack; }
set {
if (withEventsField_cmdBack != null) {
withEventsField_cmdBack.Click -= cmdBack_Click;
}
withEventsField_cmdBack = value;
if (withEventsField_cmdBack != null) {
withEventsField_cmdBack.Click += cmdBack_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdEdit;
public System.Windows.Forms.Button cmdEdit {
get { return withEventsField_cmdEdit; }
set {
if (withEventsField_cmdEdit != null) {
withEventsField_cmdEdit.Click -= cmdEdit_Click;
}
withEventsField_cmdEdit = value;
if (withEventsField_cmdEdit != null) {
withEventsField_cmdEdit.Click += cmdEdit_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdBlank;
public System.Windows.Forms.Button cmdBlank {
get { return withEventsField_cmdBlank; }
set {
if (withEventsField_cmdBlank != null) {
withEventsField_cmdBlank.Click -= cmdBlank_Click;
}
withEventsField_cmdBlank = value;
if (withEventsField_cmdBlank != null) {
withEventsField_cmdBlank.Click += cmdBlank_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdAuto;
public System.Windows.Forms.Button cmdAuto {
get { return withEventsField_cmdAuto; }
set {
if (withEventsField_cmdAuto != null) {
withEventsField_cmdAuto.Click -= cmdAuto_Click;
}
withEventsField_cmdAuto = value;
if (withEventsField_cmdAuto != null) {
withEventsField_cmdAuto.Click += cmdAuto_Click;
}
}
}
public System.Windows.Forms.Label _lblData_7;
public System.Windows.Forms.Label _lblData_6;
public System.Windows.Forms.Label _lblData_5;
public System.Windows.Forms.Label _lblLabels_36;
public System.Windows.Forms.Label _lblLabels_37;
public System.Windows.Forms.Label _lblLabels_38;
public System.Windows.Forms.Label _lbl_2;
public System.Windows.Forms.Label _lbl_1;
public System.Windows.Forms.Label _lblLabels_2;
public System.Windows.Forms.Label _lblLabels_6;
public System.Windows.Forms.Label _lblLabels_7;
public System.Windows.Forms.Label _lblLabels_8;
public System.Windows.Forms.Label _lblLabels_9;
public System.Windows.Forms.Label _lblData_0;
public System.Windows.Forms.Label _lblData_1;
public System.Windows.Forms.Label _lblData_2;
public System.Windows.Forms.Label _lblData_3;
public System.Windows.Forms.Label _lblData_4;
public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_1;
public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_2;
public System.Windows.Forms.GroupBox _frmMode_1;
private System.Windows.Forms.TextBox withEventsField_txtSearch;
public System.Windows.Forms.TextBox txtSearch {
get { return withEventsField_txtSearch; }
set {
if (withEventsField_txtSearch != null) {
withEventsField_txtSearch.Enter -= txtSearch_Enter;
withEventsField_txtSearch.KeyDown -= txtSearch_KeyDown;
withEventsField_txtSearch.KeyPress -= txtSearch_KeyPress;
}
withEventsField_txtSearch = value;
if (withEventsField_txtSearch != null) {
withEventsField_txtSearch.Enter += txtSearch_Enter;
withEventsField_txtSearch.KeyDown += txtSearch_KeyDown;
withEventsField_txtSearch.KeyPress += txtSearch_KeyPress;
}
}
}
private myDataGridView withEventsField_DataList1;
public myDataGridView DataList1 {
get { return withEventsField_DataList1; }
set {
if (withEventsField_DataList1 != null) {
withEventsField_DataList1.DoubleClick -= DataList1_DblClick;
withEventsField_DataList1.KeyPress -= DataList1_KeyPress;
}
withEventsField_DataList1 = value;
if (withEventsField_DataList1 != null) {
withEventsField_DataList1.DoubleClick += DataList1_DblClick;
withEventsField_DataList1.KeyPress += DataList1_KeyPress;
}
}
}
public System.Windows.Forms.Label _lbl_0;
public System.Windows.Forms.GroupBox _frmMode_0;
//Public WithEvents cmdInformation As Microsoft.VisualBasic.Compatibility.VB6.ButtonArray
//Public WithEvents frmMode As Microsoft.VisualBasic.Compatibility.VB6.GroupBoxArray
//Public WithEvents lbl As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
//Public WithEvents lblData As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
//Public WithEvents lblLabels As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
public OvalShapeArray Shape1;
public Microsoft.VisualBasic.PowerPacks.ShapeContainer ShapeContainer1;
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
[System.Diagnostics.DebuggerStepThrough()]
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmOrder));
this.components = new System.ComponentModel.Container();
this.ToolTip1 = new System.Windows.Forms.ToolTip(components);
this.ShapeContainer1 = new Microsoft.VisualBasic.PowerPacks.ShapeContainer();
this._cmdInformation_1 = new System.Windows.Forms.Button();
this._cmdInformation_0 = new System.Windows.Forms.Button();
this.cmdNext = new System.Windows.Forms.Button();
this.cmdBack = new System.Windows.Forms.Button();
this._frmMode_1 = new System.Windows.Forms.GroupBox();
this.cmdEdit = new System.Windows.Forms.Button();
this.cmdBlank = new System.Windows.Forms.Button();
this.cmdAuto = new System.Windows.Forms.Button();
this._lblData_7 = new System.Windows.Forms.Label();
this._lblData_6 = new System.Windows.Forms.Label();
this._lblData_5 = new System.Windows.Forms.Label();
this._lblLabels_36 = new System.Windows.Forms.Label();
this._lblLabels_37 = new System.Windows.Forms.Label();
this._lblLabels_38 = new System.Windows.Forms.Label();
this._lbl_2 = new System.Windows.Forms.Label();
this._lbl_1 = new System.Windows.Forms.Label();
this._lblLabels_2 = new System.Windows.Forms.Label();
this._lblLabels_6 = new System.Windows.Forms.Label();
this._lblLabels_7 = new System.Windows.Forms.Label();
this._lblLabels_8 = new System.Windows.Forms.Label();
this._lblLabels_9 = new System.Windows.Forms.Label();
this._lblData_0 = new System.Windows.Forms.Label();
this._lblData_1 = new System.Windows.Forms.Label();
this._lblData_2 = new System.Windows.Forms.Label();
this._lblData_3 = new System.Windows.Forms.Label();
this._lblData_4 = new System.Windows.Forms.Label();
this._Shape1_1 = new Microsoft.VisualBasic.PowerPacks.RectangleShape();
this._Shape1_2 = new Microsoft.VisualBasic.PowerPacks.RectangleShape();
this._frmMode_0 = new System.Windows.Forms.GroupBox();
this.txtSearch = new System.Windows.Forms.TextBox();
this.DataList1 = new myDataGridView();
this._lbl_0 = new System.Windows.Forms.Label();
//Me.cmdInformation = New Microsoft.VisualBasic.Compatibility.VB6.ButtonArray(components)
//Me.frmMode = New Microsoft.VisualBasic.Compatibility.VB6.GroupBoxArray(components)
//Me.lbl = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components)
//Me.lblData = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components)
//Me.lblLabels = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components)
this.Shape1 = new OvalShapeArray(components);
this._frmMode_1.SuspendLayout();
this._frmMode_0.SuspendLayout();
this.SuspendLayout();
this.ToolTip1.Active = true;
((System.ComponentModel.ISupportInitialize)this.DataList1).BeginInit();
//CType(Me.cmdInformation, System.ComponentModel.ISupportInitialize).BeginInit()
//CType(Me.frmMode, System.ComponentModel.ISupportInitialize).BeginInit()
//CType(Me.lbl, System.ComponentModel.ISupportInitialize).BeginInit()
//CType(Me.lblData, System.ComponentModel.ISupportInitialize).BeginInit()
//CType(Me.lblLabels, System.ComponentModel.ISupportInitialize).BeginInit()
((System.ComponentModel.ISupportInitialize)this.Shape1).BeginInit();
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Text = "Create / Amend an Order";
this.ClientSize = new System.Drawing.Size(362, 472);
this.Location = new System.Drawing.Point(3, 22);
this.ControlBox = false;
this.KeyPreview = true;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Control;
this.Enabled = true;
this.Cursor = System.Windows.Forms.Cursors.Default;
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.HelpButton = false;
this.WindowState = System.Windows.Forms.FormWindowState.Normal;
this.Name = "frmOrder";
this._cmdInformation_1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this._cmdInformation_1.Text = "Order Information Report(*)";
this._cmdInformation_1.Size = new System.Drawing.Size(166, 31);
this._cmdInformation_1.Location = new System.Drawing.Point(186, 6);
this._cmdInformation_1.TabIndex = 28;
this._cmdInformation_1.BackColor = System.Drawing.SystemColors.Control;
this._cmdInformation_1.CausesValidation = true;
this._cmdInformation_1.Enabled = true;
this._cmdInformation_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._cmdInformation_1.Cursor = System.Windows.Forms.Cursors.Default;
this._cmdInformation_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._cmdInformation_1.TabStop = true;
this._cmdInformation_1.Name = "_cmdInformation_1";
this._cmdInformation_0.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this._cmdInformation_0.Text = "Order Information Report";
this._cmdInformation_0.Size = new System.Drawing.Size(166, 31);
this._cmdInformation_0.Location = new System.Drawing.Point(6, 6);
this._cmdInformation_0.TabIndex = 27;
this._cmdInformation_0.BackColor = System.Drawing.SystemColors.Control;
this._cmdInformation_0.CausesValidation = true;
this._cmdInformation_0.Enabled = true;
this._cmdInformation_0.ForeColor = System.Drawing.SystemColors.ControlText;
this._cmdInformation_0.Cursor = System.Windows.Forms.Cursors.Default;
this._cmdInformation_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._cmdInformation_0.TabStop = true;
this._cmdInformation_0.Name = "_cmdInformation_0";
this.cmdNext.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdNext.Text = "&Next";
this.cmdNext.Size = new System.Drawing.Size(97, 34);
this.cmdNext.Location = new System.Drawing.Point(246, 435);
this.cmdNext.TabIndex = 1;
this.cmdNext.TabStop = false;
this.cmdNext.BackColor = System.Drawing.SystemColors.Control;
this.cmdNext.CausesValidation = true;
this.cmdNext.Enabled = true;
this.cmdNext.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdNext.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdNext.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdNext.Name = "cmdNext";
this.cmdBack.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdBack.Text = "E&xit";
this.cmdBack.Size = new System.Drawing.Size(97, 34);
this.cmdBack.Location = new System.Drawing.Point(15, 435);
this.cmdBack.TabIndex = 0;
this.cmdBack.TabStop = false;
this.cmdBack.BackColor = System.Drawing.SystemColors.Control;
this.cmdBack.CausesValidation = true;
this.cmdBack.Enabled = true;
this.cmdBack.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdBack.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdBack.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdBack.Name = "cmdBack";
this._frmMode_1.Text = "Select a supplier to transact with.";
this._frmMode_1.Size = new System.Drawing.Size(346, 379);
this._frmMode_1.Location = new System.Drawing.Point(6, 45);
this._frmMode_1.TabIndex = 6;
this._frmMode_1.BackColor = System.Drawing.SystemColors.Control;
this._frmMode_1.Enabled = true;
this._frmMode_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._frmMode_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._frmMode_1.Visible = true;
this._frmMode_1.Padding = new System.Windows.Forms.Padding(0);
this._frmMode_1.Name = "_frmMode_1";
this.cmdEdit.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdEdit.Text = "&Edit Current Order";
this.cmdEdit.Size = new System.Drawing.Size(97, 52);
this.cmdEdit.Location = new System.Drawing.Point(9, 318);
this.cmdEdit.TabIndex = 29;
this.cmdEdit.TabStop = false;
this.cmdEdit.BackColor = System.Drawing.SystemColors.Control;
this.cmdEdit.CausesValidation = true;
this.cmdEdit.Enabled = true;
this.cmdEdit.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdEdit.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdEdit.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdEdit.Name = "cmdEdit";
this.cmdBlank.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdBlank.Text = "&Create a Blank Order";
this.cmdBlank.Size = new System.Drawing.Size(97, 52);
this.cmdBlank.Location = new System.Drawing.Point(126, 318);
this.cmdBlank.TabIndex = 26;
this.cmdBlank.TabStop = false;
this.cmdBlank.BackColor = System.Drawing.SystemColors.Control;
this.cmdBlank.CausesValidation = true;
this.cmdBlank.Enabled = true;
this.cmdBlank.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdBlank.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdBlank.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdBlank.Name = "cmdBlank";
this.cmdAuto.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdAuto.Text = "Create &Recommended Order";
this.cmdAuto.Size = new System.Drawing.Size(97, 52);
this.cmdAuto.Location = new System.Drawing.Point(240, 318);
this.cmdAuto.TabIndex = 25;
this.cmdAuto.TabStop = false;
this.cmdAuto.BackColor = System.Drawing.SystemColors.Control;
this.cmdAuto.CausesValidation = true;
this.cmdAuto.Enabled = true;
this.cmdAuto.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdAuto.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdAuto.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdAuto.Name = "cmdAuto";
this._lblData_7.BackColor = System.Drawing.Color.FromArgb(224, 224, 224);
this._lblData_7.Text = "Supplier_ShippingCode";
this._lblData_7.ForeColor = System.Drawing.SystemColors.WindowText;
this._lblData_7.Size = new System.Drawing.Size(190, 16);
this._lblData_7.Location = new System.Drawing.Point(141, 267);
this._lblData_7.TabIndex = 24;
this._lblData_7.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._lblData_7.Enabled = true;
this._lblData_7.Cursor = System.Windows.Forms.Cursors.Default;
this._lblData_7.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblData_7.UseMnemonic = true;
this._lblData_7.Visible = true;
this._lblData_7.AutoSize = false;
this._lblData_7.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._lblData_7.Name = "_lblData_7";
this._lblData_6.BackColor = System.Drawing.Color.FromArgb(224, 224, 224);
this._lblData_6.Text = "Supplier_RepresentativeNumber";
this._lblData_6.ForeColor = System.Drawing.SystemColors.WindowText;
this._lblData_6.Size = new System.Drawing.Size(190, 16);
this._lblData_6.Location = new System.Drawing.Point(141, 249);
this._lblData_6.TabIndex = 23;
this._lblData_6.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._lblData_6.Enabled = true;
this._lblData_6.Cursor = System.Windows.Forms.Cursors.Default;
this._lblData_6.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblData_6.UseMnemonic = true;
this._lblData_6.Visible = true;
this._lblData_6.AutoSize = false;
this._lblData_6.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._lblData_6.Name = "_lblData_6";
this._lblData_5.BackColor = System.Drawing.Color.FromArgb(224, 224, 224);
this._lblData_5.Text = "Supplier_RepresentativeName";
this._lblData_5.ForeColor = System.Drawing.SystemColors.WindowText;
this._lblData_5.Size = new System.Drawing.Size(190, 16);
this._lblData_5.Location = new System.Drawing.Point(141, 231);
this._lblData_5.TabIndex = 22;
this._lblData_5.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._lblData_5.Enabled = true;
this._lblData_5.Cursor = System.Windows.Forms.Cursors.Default;
this._lblData_5.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblData_5.UseMnemonic = true;
this._lblData_5.Visible = true;
this._lblData_5.AutoSize = false;
this._lblData_5.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._lblData_5.Name = "_lblData_5";
this._lblLabels_36.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lblLabels_36.Text = "Account Number:";
this._lblLabels_36.Size = new System.Drawing.Size(83, 13);
this._lblLabels_36.Location = new System.Drawing.Point(50, 267);
this._lblLabels_36.TabIndex = 21;
this._lblLabels_36.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_36.Enabled = true;
this._lblLabels_36.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_36.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_36.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_36.UseMnemonic = true;
this._lblLabels_36.Visible = true;
this._lblLabels_36.AutoSize = true;
this._lblLabels_36.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblLabels_36.Name = "_lblLabels_36";
this._lblLabels_37.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lblLabels_37.Text = "Representative Number:";
this._lblLabels_37.Size = new System.Drawing.Size(115, 13);
this._lblLabels_37.Location = new System.Drawing.Point(18, 248);
this._lblLabels_37.TabIndex = 20;
this._lblLabels_37.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_37.Enabled = true;
this._lblLabels_37.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_37.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_37.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_37.UseMnemonic = true;
this._lblLabels_37.Visible = true;
this._lblLabels_37.AutoSize = true;
this._lblLabels_37.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblLabels_37.Name = "_lblLabels_37";
this._lblLabels_38.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lblLabels_38.Text = "Representative Name:";
this._lblLabels_38.Size = new System.Drawing.Size(106, 13);
this._lblLabels_38.Location = new System.Drawing.Point(27, 230);
this._lblLabels_38.TabIndex = 19;
this._lblLabels_38.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_38.Enabled = true;
this._lblLabels_38.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_38.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_38.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_38.UseMnemonic = true;
this._lblLabels_38.Visible = true;
this._lblLabels_38.AutoSize = true;
this._lblLabels_38.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblLabels_38.Name = "_lblLabels_38";
this._lbl_2.BackColor = System.Drawing.Color.Transparent;
this._lbl_2.Text = "&2. Ordering Details";
this._lbl_2.Size = new System.Drawing.Size(107, 13);
this._lbl_2.Location = new System.Drawing.Point(9, 207);
this._lbl_2.TabIndex = 18;
this._lbl_2.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._lbl_2.Enabled = true;
this._lbl_2.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_2.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_2.UseMnemonic = true;
this._lbl_2.Visible = true;
this._lbl_2.AutoSize = true;
this._lbl_2.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lbl_2.Name = "_lbl_2";
this._lbl_1.BackColor = System.Drawing.Color.Transparent;
this._lbl_1.Text = "&1. General";
this._lbl_1.Size = new System.Drawing.Size(61, 13);
this._lbl_1.Location = new System.Drawing.Point(9, 18);
this._lbl_1.TabIndex = 17;
this._lbl_1.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._lbl_1.Enabled = true;
this._lbl_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_1.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_1.UseMnemonic = true;
this._lbl_1.Visible = true;
this._lbl_1.AutoSize = true;
this._lbl_1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lbl_1.Name = "_lbl_1";
this._lblLabels_2.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lblLabels_2.Text = "Supplier Name:";
this._lblLabels_2.Size = new System.Drawing.Size(87, 13);
this._lblLabels_2.Location = new System.Drawing.Point(13, 39);
this._lblLabels_2.TabIndex = 16;
this._lblLabels_2.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_2.Enabled = true;
this._lblLabels_2.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_2.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_2.UseMnemonic = true;
this._lblLabels_2.Visible = true;
this._lblLabels_2.AutoSize = true;
this._lblLabels_2.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblLabels_2.Name = "_lblLabels_2";
this._lblLabels_6.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lblLabels_6.Text = "Physical Address:";
this._lblLabels_6.Size = new System.Drawing.Size(94, 13);
this._lblLabels_6.Location = new System.Drawing.Point(6, 78);
this._lblLabels_6.TabIndex = 15;
this._lblLabels_6.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_6.Enabled = true;
this._lblLabels_6.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_6.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_6.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_6.UseMnemonic = true;
this._lblLabels_6.Visible = true;
this._lblLabels_6.AutoSize = true;
this._lblLabels_6.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblLabels_6.Name = "_lblLabels_6";
this._lblLabels_7.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lblLabels_7.Text = "Postal Address:";
this._lblLabels_7.Size = new System.Drawing.Size(76, 13);
this._lblLabels_7.Location = new System.Drawing.Point(24, 138);
this._lblLabels_7.TabIndex = 14;
this._lblLabels_7.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_7.Enabled = true;
this._lblLabels_7.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_7.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_7.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_7.UseMnemonic = true;
this._lblLabels_7.Visible = true;
this._lblLabels_7.AutoSize = true;
this._lblLabels_7.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblLabels_7.Name = "_lblLabels_7";
this._lblLabels_8.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lblLabels_8.Text = "Telephone:";
this._lblLabels_8.Size = new System.Drawing.Size(55, 13);
this._lblLabels_8.Location = new System.Drawing.Point(42, 57);
this._lblLabels_8.TabIndex = 13;
this._lblLabels_8.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_8.Enabled = true;
this._lblLabels_8.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_8.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_8.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_8.UseMnemonic = true;
this._lblLabels_8.Visible = true;
this._lblLabels_8.AutoSize = true;
this._lblLabels_8.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblLabels_8.Name = "_lblLabels_8";
this._lblLabels_9.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lblLabels_9.Text = "Fax:";
this._lblLabels_9.Size = new System.Drawing.Size(22, 13);
this._lblLabels_9.Location = new System.Drawing.Point(210, 57);
this._lblLabels_9.TabIndex = 12;
this._lblLabels_9.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_9.Enabled = true;
this._lblLabels_9.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_9.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_9.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_9.UseMnemonic = true;
this._lblLabels_9.Visible = true;
this._lblLabels_9.AutoSize = true;
this._lblLabels_9.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblLabels_9.Name = "_lblLabels_9";
this._lblData_0.BackColor = System.Drawing.Color.FromArgb(224, 224, 224);
this._lblData_0.Text = "Supplier_Name";
this._lblData_0.ForeColor = System.Drawing.SystemColors.WindowText;
this._lblData_0.Size = new System.Drawing.Size(226, 16);
this._lblData_0.Location = new System.Drawing.Point(105, 39);
this._lblData_0.TabIndex = 11;
this._lblData_0.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._lblData_0.Enabled = true;
this._lblData_0.Cursor = System.Windows.Forms.Cursors.Default;
this._lblData_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblData_0.UseMnemonic = true;
this._lblData_0.Visible = true;
this._lblData_0.AutoSize = false;
this._lblData_0.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._lblData_0.Name = "_lblData_0";
this._lblData_1.BackColor = System.Drawing.Color.FromArgb(224, 224, 224);
this._lblData_1.Text = "Supplier_Telephone";
this._lblData_1.ForeColor = System.Drawing.SystemColors.WindowText;
this._lblData_1.Size = new System.Drawing.Size(94, 16);
this._lblData_1.Location = new System.Drawing.Point(105, 57);
this._lblData_1.TabIndex = 10;
this._lblData_1.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._lblData_1.Enabled = true;
this._lblData_1.Cursor = System.Windows.Forms.Cursors.Default;
this._lblData_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblData_1.UseMnemonic = true;
this._lblData_1.Visible = true;
this._lblData_1.AutoSize = false;
this._lblData_1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._lblData_1.Name = "_lblData_1";
this._lblData_2.BackColor = System.Drawing.Color.FromArgb(224, 224, 224);
this._lblData_2.Text = "Supplier_Facimile";
this._lblData_2.ForeColor = System.Drawing.SystemColors.WindowText;
this._lblData_2.Size = new System.Drawing.Size(94, 16);
this._lblData_2.Location = new System.Drawing.Point(237, 57);
this._lblData_2.TabIndex = 9;
this._lblData_2.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._lblData_2.Enabled = true;
this._lblData_2.Cursor = System.Windows.Forms.Cursors.Default;
this._lblData_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblData_2.UseMnemonic = true;
this._lblData_2.Visible = true;
this._lblData_2.AutoSize = false;
this._lblData_2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._lblData_2.Name = "_lblData_2";
this._lblData_3.BackColor = System.Drawing.Color.FromArgb(224, 224, 224);
this._lblData_3.Text = "Supplier_PhysicalAddress";
this._lblData_3.ForeColor = System.Drawing.SystemColors.WindowText;
this._lblData_3.Size = new System.Drawing.Size(226, 58);
this._lblData_3.Location = new System.Drawing.Point(105, 78);
this._lblData_3.TabIndex = 8;
this._lblData_3.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._lblData_3.Enabled = true;
this._lblData_3.Cursor = System.Windows.Forms.Cursors.Default;
this._lblData_3.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblData_3.UseMnemonic = true;
this._lblData_3.Visible = true;
this._lblData_3.AutoSize = false;
this._lblData_3.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._lblData_3.Name = "_lblData_3";
this._lblData_4.BackColor = System.Drawing.Color.FromArgb(224, 224, 224);
this._lblData_4.Text = "Supplier_PostalAddress";
this._lblData_4.ForeColor = System.Drawing.SystemColors.WindowText;
this._lblData_4.Size = new System.Drawing.Size(226, 58);
this._lblData_4.Location = new System.Drawing.Point(105, 141);
this._lblData_4.TabIndex = 7;
this._lblData_4.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._lblData_4.Enabled = true;
this._lblData_4.Cursor = System.Windows.Forms.Cursors.Default;
this._lblData_4.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblData_4.UseMnemonic = true;
this._lblData_4.Visible = true;
this._lblData_4.AutoSize = false;
this._lblData_4.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._lblData_4.Name = "_lblData_4";
this._Shape1_1.BackColor = System.Drawing.Color.FromArgb(192, 192, 255);
this._Shape1_1.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque;
this._Shape1_1.Size = new System.Drawing.Size(328, 172);
this._Shape1_1.Location = new System.Drawing.Point(9, 20);
this._Shape1_1.BorderColor = System.Drawing.SystemColors.WindowText;
this._Shape1_1.BorderStyle = System.Drawing.Drawing2D.DashStyle.Solid;
this._Shape1_1.BorderWidth = 1;
this._Shape1_1.FillColor = System.Drawing.Color.Black;
this._Shape1_1.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Transparent;
this._Shape1_1.Visible = true;
this._Shape1_1.Name = "_Shape1_1";
this._Shape1_2.BackColor = System.Drawing.Color.FromArgb(192, 192, 255);
this._Shape1_2.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque;
this._Shape1_2.Size = new System.Drawing.Size(328, 70);
this._Shape1_2.Location = new System.Drawing.Point(9, 209);
this._Shape1_2.BorderColor = System.Drawing.SystemColors.WindowText;
this._Shape1_2.BorderStyle = System.Drawing.Drawing2D.DashStyle.Solid;
this._Shape1_2.BorderWidth = 1;
this._Shape1_2.FillColor = System.Drawing.Color.Black;
this._Shape1_2.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Transparent;
this._Shape1_2.Visible = true;
this._Shape1_2.Name = "_Shape1_2";
this._frmMode_0.Text = "Select a supplier to transact with.";
this._frmMode_0.Size = new System.Drawing.Size(346, 379);
this._frmMode_0.Location = new System.Drawing.Point(6, 48);
this._frmMode_0.TabIndex = 2;
this._frmMode_0.BackColor = System.Drawing.SystemColors.Control;
this._frmMode_0.Enabled = true;
this._frmMode_0.ForeColor = System.Drawing.SystemColors.ControlText;
this._frmMode_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._frmMode_0.Visible = true;
this._frmMode_0.Padding = new System.Windows.Forms.Padding(0);
this._frmMode_0.Name = "_frmMode_0";
this.txtSearch.AutoSize = false;
this.txtSearch.Size = new System.Drawing.Size(283, 19);
this.txtSearch.Location = new System.Drawing.Point(54, 18);
this.txtSearch.TabIndex = 3;
this.txtSearch.AcceptsReturn = true;
this.txtSearch.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
this.txtSearch.BackColor = System.Drawing.SystemColors.Window;
this.txtSearch.CausesValidation = true;
this.txtSearch.Enabled = true;
this.txtSearch.ForeColor = System.Drawing.SystemColors.WindowText;
this.txtSearch.HideSelection = true;
this.txtSearch.ReadOnly = false;
this.txtSearch.MaxLength = 0;
this.txtSearch.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtSearch.Multiline = false;
this.txtSearch.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.txtSearch.ScrollBars = System.Windows.Forms.ScrollBars.None;
this.txtSearch.TabStop = true;
this.txtSearch.Visible = true;
this.txtSearch.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.txtSearch.Name = "txtSearch";
//'DataList1.OcxState = CType(resources.GetObject("'DataList1.OcxState"), System.Windows.Forms.AxHost.State)
this.DataList1.Size = new System.Drawing.Size(328, 329);
this.DataList1.Location = new System.Drawing.Point(9, 42);
this.DataList1.TabIndex = 4;
this.DataList1.Name = "DataList1";
this._lbl_0.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lbl_0.Text = "&Search :";
this._lbl_0.Size = new System.Drawing.Size(40, 13);
this._lbl_0.Location = new System.Drawing.Point(11, 21);
this._lbl_0.TabIndex = 5;
this._lbl_0.BackColor = System.Drawing.Color.Transparent;
this._lbl_0.Enabled = true;
this._lbl_0.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_0.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_0.UseMnemonic = true;
this._lbl_0.Visible = true;
this._lbl_0.AutoSize = true;
this._lbl_0.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lbl_0.Name = "_lbl_0";
this.Controls.Add(_cmdInformation_1);
this.Controls.Add(_cmdInformation_0);
this.Controls.Add(cmdNext);
this.Controls.Add(cmdBack);
this.Controls.Add(_frmMode_1);
this.Controls.Add(_frmMode_0);
this._frmMode_1.Controls.Add(cmdEdit);
this._frmMode_1.Controls.Add(cmdBlank);
this._frmMode_1.Controls.Add(cmdAuto);
this._frmMode_1.Controls.Add(_lblData_7);
this._frmMode_1.Controls.Add(_lblData_6);
this._frmMode_1.Controls.Add(_lblData_5);
this._frmMode_1.Controls.Add(_lblLabels_36);
this._frmMode_1.Controls.Add(_lblLabels_37);
this._frmMode_1.Controls.Add(_lblLabels_38);
this._frmMode_1.Controls.Add(_lbl_2);
this._frmMode_1.Controls.Add(_lbl_1);
this._frmMode_1.Controls.Add(_lblLabels_2);
this._frmMode_1.Controls.Add(_lblLabels_6);
this._frmMode_1.Controls.Add(_lblLabels_7);
this._frmMode_1.Controls.Add(_lblLabels_8);
this._frmMode_1.Controls.Add(_lblLabels_9);
this._frmMode_1.Controls.Add(_lblData_0);
this._frmMode_1.Controls.Add(_lblData_1);
this._frmMode_1.Controls.Add(_lblData_2);
this._frmMode_1.Controls.Add(_lblData_3);
this._frmMode_1.Controls.Add(_lblData_4);
this.ShapeContainer1.Shapes.Add(_Shape1_1);
this.ShapeContainer1.Shapes.Add(_Shape1_2);
this._frmMode_1.Controls.Add(ShapeContainer1);
this._frmMode_0.Controls.Add(txtSearch);
this._frmMode_0.Controls.Add(DataList1);
this._frmMode_0.Controls.Add(_lbl_0);
//Me.cmdInformation.SetIndex(_cmdInformation_1, CType(1, Short))
//Me.cmdInformation.SetIndex(_cmdInformation_0, CType(0, Short))
//Me.frmMode.SetIndex(_frmMode_1, CType(1, Short))
//Me.frmMode.SetIndex(_frmMode_0, CType(0, Short))
//Me.lbl.SetIndex(_lbl_2, CType(2, Short))
//Me.lbl.SetIndex(_lbl_1, CType(1, Short))
//Me.lbl.SetIndex(_lbl_0, CType(0, Short))
//Me.lblData.SetIndex(_lblData_7, CType(7, Short))
//Me.lblData.SetIndex(_lblData_6, CType(6, Short))
//Me.lblData.SetIndex(_lblData_5, CType(5, Short))
//Me.lblData.SetIndex(_lblData_0, CType(0, Short))
//Me.lblData.SetIndex(_lblData_1, CType(1, Short))
//M() ''e.lblData.SetIndex(_lblData_2, CType(2, Short))
//M() 'e.lblData.SetIndex(_lblData_3, CType(3, Short))
//Me.lblData.SetIndex(_lblData_4, CType(4, Short))
//Me.lblLabels.SetIndex(_lblLabels_36, CType(36, Short))
//Me.lblLabels.SetIndex(_lblLabels_37, CType(37, Short))
//Me.lblLabels.SetIndex(_lblLabels_38, CType(38, Short))
//Me.lblLabels.SetIndex(_lblLabels_2, CType(2, Short))
//Me.lblLabels.SetIndex(_lblLabels_6, CType(6, Short))
//Me.lblLabels.SetIndex(_lblLabels_7, CType(7, Short))
//Me.lblLabels.SetIndex(_lblLabels_8, CType(8, Short))
//Me.lblLabels.SetIndex(_lblLabels_9, CType(9, Short))
//Me.Shape1.SetIndex(_Shape1_1, CType(1, Short))
//Me.Shape1.SetIndex(_Shape1_2, CType(2, Short))
((System.ComponentModel.ISupportInitialize)this.Shape1).EndInit();
//CType(Me.lblLabels, System.ComponentModel.ISupportInitialize).EndInit()
//CType(Me.lblData, System.ComponentModel.ISupportInitialize).EndInit()
//CType(Me.lbl, System.ComponentModel.ISupportInitialize).EndInit()
//CType(Me.frmMode, System.ComponentModel.ISupportInitialize).EndInit()
//CType(Me.cmdInformation, System.ComponentModel.ISupportInitialize).EndInit()
((System.ComponentModel.ISupportInitialize)this.DataList1).EndInit();
this._frmMode_1.ResumeLayout(false);
this._frmMode_0.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using MatterHackers.Agg;
using MatterHackers.Agg.UI;
using MatterHackers.Agg.VertexSource;
namespace MatterHackers.MatterControl.CustomWidgets
{
public class DataViewGraph : GuiWidget
{
private HistoryData dataHistoryArray;
private ColorF LineColor = ColorF.Black;
public DataViewGraph()
{
dataHistoryArray = new HistoryData(10);
DoubleBuffer = true;
}
public bool DynamicallyScaleRange { get; set; } = true;
private Color _goalColor = Color.Yellow;
public Color GoalColor
{
get
{
return _goalColor;
}
set
{
_goalColor = value;
Invalidate();
}
}
private double _goalValue;
public double GoalValue
{
get
{
return _goalValue;
}
set
{
_goalValue = value;
Invalidate();
}
}
public override RectangleDouble LocalBounds
{
get => base.LocalBounds; set
{
dataHistoryArray = new HistoryData(Math.Min(1000, Math.Max(1, (int)value.Width)));
base.LocalBounds = value;
}
}
public double MaxValue { get; set; } = double.MinValue;
public double MinValue { get; set; } = double.MaxValue;
public bool ShowGoal { get; set; }
public int TotalAdds { get; private set; }
public void AddData(double newData)
{
if (DynamicallyScaleRange)
{
MaxValue = System.Math.Max(MaxValue, newData);
MinValue = System.Math.Min(MinValue, newData);
}
dataHistoryArray.Add(newData);
TotalAdds++;
if (this.ActuallyVisibleOnScreen())
{
Invalidate();
}
}
public double GetAverageValue()
{
return dataHistoryArray.GetAverageValue();
}
public override void OnDraw(Graphics2D graphics2D)
{
var linesToDrawStorage = new VertexStorage();
double range = MaxValue - MinValue;
if (ShowGoal)
{
var yPos = (GoalValue - MinValue) * Height / range;
graphics2D.Line(0, yPos, Width, yPos, GoalColor);
}
Color backgroundGridColor = Color.Gray;
double pixelSkip = Height;
for (int i = 0; i < Width / pixelSkip; i++)
{
double xPos = Width - ((i * pixelSkip + TotalAdds) % Width);
int inset = (int)((i % 2) == 0 ? Height / 6 : Height / 3);
graphics2D.Line(xPos, inset, xPos, Height - inset, new Color(backgroundGridColor, 120));
}
for (int i = 0; i < Width - 1; i++)
{
if (i == 0)
{
linesToDrawStorage.MoveTo(i + Width - dataHistoryArray.Count, (dataHistoryArray.GetItem(i) - MinValue) * Height / range);
}
else
{
linesToDrawStorage.LineTo(i + Width - dataHistoryArray.Count, (dataHistoryArray.GetItem(i) - MinValue) * Height / range);
}
}
graphics2D.Render(new Stroke(linesToDrawStorage), LineColor);
base.OnDraw(graphics2D);
}
public void Reset()
{
dataHistoryArray.Reset();
}
internal class HistoryData
{
internal double currentDataSum;
private readonly int capacity;
private readonly List<double> data;
internal HistoryData(int capacity)
{
this.capacity = capacity;
data = new List<double>();
Reset();
}
public int Count
{
get
{
return data.Count;
}
}
internal void Add(double value)
{
if (data.Count == capacity)
{
currentDataSum -= data[0];
data.RemoveAt(0);
}
data.Add(value);
currentDataSum += value;
}
internal double GetAverageValue()
{
return currentDataSum / data.Count;
}
internal double GetItem(int itemIndex)
{
if (itemIndex < data.Count)
{
return data[itemIndex];
}
else
{
return 0;
}
}
internal double GetMaxValue()
{
double max = -double.MinValue;
for (int i = 0; i < data.Count; i++)
{
if (data[i] > max)
{
max = data[i];
}
}
return max;
}
internal double GetMinValue()
{
double min = double.MaxValue;
for (int i = 0; i < data.Count; i++)
{
if (data[i] < min)
{
min = data[i];
}
}
return min;
}
internal void Reset()
{
currentDataSum = 0;
data.Clear();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using BTDB.Buffer;
namespace BTDB.KVDBLayer.BTreeMem
{
class BTreeRoot : IBTreeRootNode
{
readonly long _transactionId;
long _keyValueCount;
IBTreeNode _rootNode;
public BTreeRoot(long transactionId)
{
_transactionId = transactionId;
}
public void CreateOrUpdate(CreateOrUpdateCtx ctx)
{
ctx.TransactionId = _transactionId;
if (ctx.Stack == null) ctx.Stack = new List<NodeIdxPair>();
else ctx.Stack.Clear();
if (_rootNode == null)
{
_rootNode = ctx.WholeKeyLen > BTreeLeafComp.MaxTotalLen ? BTreeLeaf.CreateFirst(ctx) : BTreeLeafComp.CreateFirst(ctx);
_keyValueCount = 1;
ctx.Stack.Add(new NodeIdxPair { Node = _rootNode, Idx = 0 });
ctx.KeyIndex = 0;
ctx.Created = true;
return;
}
ctx.Depth = 0;
_rootNode.CreateOrUpdate(ctx);
if (ctx.Split)
{
_rootNode = new BTreeBranch(ctx.TransactionId, ctx.Node1, ctx.Node2);
ctx.Stack.Insert(0, new NodeIdxPair { Node = _rootNode, Idx = ctx.SplitInRight ? 1 : 0 });
}
else if (ctx.Update)
{
_rootNode = ctx.Node1;
}
if (ctx.Created)
{
_keyValueCount++;
}
}
public FindResult FindKey(List<NodeIdxPair> stack, out long keyIndex, byte[] prefix, ByteBuffer key)
{
stack.Clear();
if (_rootNode == null)
{
keyIndex = -1;
return FindResult.NotFound;
}
var result = _rootNode.FindKey(stack, out keyIndex, prefix, key);
if (result == FindResult.Previous)
{
if (keyIndex < 0)
{
keyIndex = 0;
stack[stack.Count - 1] = new NodeIdxPair { Node = stack[stack.Count - 1].Node, Idx = 0 };
result = FindResult.Next;
}
else
{
if (!KeyStartsWithPrefix(prefix, GetKeyFromStack(stack)))
{
result = FindResult.Next;
keyIndex++;
if (!FindNextKey(stack))
{
return FindResult.NotFound;
}
}
}
if (!KeyStartsWithPrefix(prefix, GetKeyFromStack(stack)))
{
return FindResult.NotFound;
}
}
return result;
}
internal static bool KeyStartsWithPrefix(byte[] prefix, ByteBuffer key)
{
if (key.Length < prefix.Length) return false;
var keyBuffer = key.Buffer;
var offset = key.Offset;
for (int i = 0; i < prefix.Length; i++)
{
if (keyBuffer[offset + i] != prefix[i]) return false;
}
return true;
}
static ByteBuffer GetKeyFromStack(List<NodeIdxPair> stack)
{
return ((IBTreeLeafNode)stack[stack.Count - 1].Node).GetKey(stack[stack.Count - 1].Idx);
}
public long CalcKeyCount()
{
return _keyValueCount;
}
public byte[] GetLeftMostKey()
{
return _rootNode.GetLeftMostKey();
}
public void FillStackByIndex(List<NodeIdxPair> stack, long keyIndex)
{
Debug.Assert(keyIndex >= 0 && keyIndex < _keyValueCount);
stack.Clear();
_rootNode.FillStackByIndex(stack, keyIndex);
}
public long FindLastWithPrefix(byte[] prefix)
{
if (_rootNode == null) return -1;
return _rootNode.FindLastWithPrefix(prefix);
}
public bool NextIdxValid(int idx)
{
return false;
}
public void FillStackByLeftMost(List<NodeIdxPair> stack, int idx)
{
stack.Add(new NodeIdxPair { Node = _rootNode, Idx = 0 });
_rootNode.FillStackByLeftMost(stack, 0);
}
public void FillStackByRightMost(List<NodeIdxPair> stack, int idx)
{
throw new ArgumentException();
}
public int GetLastChildrenIdx()
{
return 0;
}
public IBTreeNode EraseRange(long transactionId, long firstKeyIndex, long lastKeyIndex)
{
throw new ArgumentException();
}
public long TransactionId
{
get { return _transactionId; }
}
public IBTreeRootNode NewTransactionRoot()
{
return new BTreeRoot(_transactionId + 1) { _keyValueCount = _keyValueCount, _rootNode = _rootNode };
}
public void EraseRange(long firstKeyIndex, long lastKeyIndex)
{
Debug.Assert(firstKeyIndex >= 0);
Debug.Assert(lastKeyIndex < _keyValueCount);
if (firstKeyIndex == 0 && lastKeyIndex == _keyValueCount - 1)
{
_rootNode = null;
_keyValueCount = 0;
return;
}
_keyValueCount -= lastKeyIndex - firstKeyIndex + 1;
_rootNode = _rootNode.EraseRange(TransactionId, firstKeyIndex, lastKeyIndex);
}
public bool FindNextKey(List<NodeIdxPair> stack)
{
int idx = stack.Count - 1;
while (idx >= 0)
{
var pair = stack[idx];
if (pair.Node.NextIdxValid(pair.Idx))
{
stack.RemoveRange(idx + 1, stack.Count - idx - 1);
stack[idx] = new NodeIdxPair { Node = pair.Node, Idx = pair.Idx + 1 };
pair.Node.FillStackByLeftMost(stack, pair.Idx + 1);
return true;
}
idx--;
}
return false;
}
public bool FindPreviousKey(List<NodeIdxPair> stack)
{
int idx = stack.Count - 1;
while (idx >= 0)
{
var pair = stack[idx];
if (pair.Idx > 0)
{
stack.RemoveRange(idx + 1, stack.Count - idx - 1);
stack[idx] = new NodeIdxPair { Node = pair.Node, Idx = pair.Idx - 1 };
pair.Node.FillStackByRightMost(stack, pair.Idx - 1);
return true;
}
idx--;
}
return false;
}
public void BuildTree(long keyCount, Func<BTreeLeafMember> memberGenerator)
{
_keyValueCount = keyCount;
if (keyCount == 0)
{
_rootNode = null;
return;
}
_rootNode = BuildTreeNode(keyCount, memberGenerator);
}
IBTreeNode BuildTreeNode(long keyCount, Func<BTreeLeafMember> memberGenerator)
{
var leafs = (keyCount + BTreeLeafComp.MaxMembers - 1) / BTreeLeafComp.MaxMembers;
var order = 0L;
var done = 0L;
return BuildBranchNode(leafs, () =>
{
order++;
var reach = keyCount * order / leafs;
var todo = (int)(reach - done);
done = reach;
var keyvalues = new BTreeLeafMember[todo];
long totalKeyLen = 0;
for (int i = 0; i < keyvalues.Length; i++)
{
keyvalues[i] = memberGenerator();
totalKeyLen += keyvalues[i].Key.Length;
}
if (totalKeyLen > BTreeLeafComp.MaxTotalLen)
{
return new BTreeLeaf(_transactionId, keyvalues);
}
return new BTreeLeafComp(_transactionId, keyvalues);
});
}
IBTreeNode BuildBranchNode(long count, Func<IBTreeNode> generator)
{
if (count == 1) return generator();
var children = (count + BTreeBranch.MaxChildren - 1) / BTreeBranch.MaxChildren;
var order = 0L;
var done = 0L;
return BuildBranchNode(children, () =>
{
order++;
var reach = count * order / children;
var todo = (int)(reach - done);
done = reach;
return new BTreeBranch(_transactionId, todo, generator);
});
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Reflection;
using System.Text;
namespace AWI.SmartTracker
{
/// <summary>
/// Summary description for Form2.
/// </summary>
public class HelpForm : System.Windows.Forms.Form
{
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.LinkLabel label5;
private System.Windows.Forms.Label lblVersion;
private System.Windows.Forms.Label lblBuild;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.PictureBox m_picLogin;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public HelpForm()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
string title = ((AssemblyTitleAttribute)Attribute.GetCustomAttribute(
Assembly.GetExecutingAssembly(), typeof(AssemblyTitleAttribute), false))
.Title;
string version = ((AssemblyFileVersionAttribute)Attribute.GetCustomAttribute(
Assembly.GetExecutingAssembly(), typeof(AssemblyFileVersionAttribute), false))
.Version;
StringBuilder desc = new StringBuilder(title);
#if LITE
desc.Append(" Lite");
#endif
#if SANI
desc.Append(" (Sani Faucet)");
#endif
desc.Append(" V");
desc.Append(version);
lblVersion.Text = desc.ToString();
DateTime date = new DateTime(2000, 1, 1);
string[] parts = Assembly.GetExecutingAssembly().FullName.Split(',');
string[] versionParts = parts[1].Split('.');
date = date.AddDays(Int32.Parse(versionParts[2]));
date = date.AddSeconds(Int32.Parse(versionParts[3]) * 2);
if (System.TimeZoneInfo.Local.IsDaylightSavingTime(date))
{
date = date.AddHours(1);
}
lblBuild.Text = string.Format("Built {0}",
date.ToString("g", System.Globalization.CultureInfo.InvariantCulture));
}
/// <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(HelpForm));
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.LinkLabel();
this.lblVersion = new System.Windows.Forms.Label();
this.lblBuild = new System.Windows.Forms.Label();
this.label9 = new System.Windows.Forms.Label();
this.m_picLogin = new System.Windows.Forms.PictureBox();
((System.ComponentModel.ISupportInitialize)(this.m_picLogin)).BeginInit();
this.SuspendLayout();
//
// label1
//
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.ForeColor = System.Drawing.Color.Blue;
this.label1.Location = new System.Drawing.Point(12, 88);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(258, 23);
this.label1.TabIndex = 0;
this.label1.Text = "ActiveWave Inc.";
//
// label2
//
this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.ForeColor = System.Drawing.Color.Blue;
this.label2.Location = new System.Drawing.Point(12, 118);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(258, 23);
this.label2.TabIndex = 1;
this.label2.Text = "Congress Corporate Plaza";
//
// label3
//
this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.ForeColor = System.Drawing.Color.Blue;
this.label3.Location = new System.Drawing.Point(12, 148);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(258, 23);
this.label3.TabIndex = 2;
this.label3.Text = "902 Clintmoore Road. Suite 118";
//
// label4
//
this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label4.ForeColor = System.Drawing.Color.Blue;
this.label4.Location = new System.Drawing.Point(12, 178);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(258, 23);
this.label4.TabIndex = 3;
this.label4.Text = "Boca Raton, FL 33487";
//
// label5
//
this.label5.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label5.ForeColor = System.Drawing.Color.Blue;
this.label5.Location = new System.Drawing.Point(12, 208);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(258, 23);
this.label5.TabIndex = 4;
this.label5.TabStop = true;
this.label5.Text = "www.activewaveinc.com";
//
// lblVersion
//
this.lblVersion.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblVersion.ForeColor = System.Drawing.Color.Blue;
this.lblVersion.Location = new System.Drawing.Point(12, 248);
this.lblVersion.Name = "lblVersion";
this.lblVersion.Size = new System.Drawing.Size(260, 23);
this.lblVersion.TabIndex = 6;
this.lblVersion.Text = "Smart Tracker V?.?.0.0";
//
// lblBuild
//
this.lblBuild.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblBuild.ForeColor = System.Drawing.Color.Blue;
this.lblBuild.Location = new System.Drawing.Point(12, 278);
this.lblBuild.Name = "lblBuild";
this.lblBuild.Size = new System.Drawing.Size(258, 23);
this.lblBuild.TabIndex = 7;
this.lblBuild.Text = "Build ??? ??, ????";
//
// label9
//
this.label9.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label9.ForeColor = System.Drawing.Color.Blue;
this.label9.Location = new System.Drawing.Point(12, 308);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(260, 23);
this.label9.TabIndex = 8;
//
// m_picLogin
//
this.m_picLogin.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.m_picLogin.BackColor = System.Drawing.Color.White;
this.m_picLogin.Image = ((System.Drawing.Image)(resources.GetObject("m_picLogin.Image")));
this.m_picLogin.Location = new System.Drawing.Point(2, 2);
this.m_picLogin.Name = "m_picLogin";
this.m_picLogin.Size = new System.Drawing.Size(280, 75);
this.m_picLogin.TabIndex = 15;
this.m_picLogin.TabStop = false;
//
// HelpForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.BackColor = System.Drawing.Color.White;
this.ClientSize = new System.Drawing.Size(282, 343);
this.Controls.Add(this.m_picLogin);
this.Controls.Add(this.label9);
this.Controls.Add(this.lblBuild);
this.Controls.Add(this.lblVersion);
this.Controls.Add(this.label5);
this.Controls.Add(this.label4);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "HelpForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "About Smart Tracker ";
((System.ComponentModel.ISupportInitialize)(this.m_picLogin)).EndInit();
this.ResumeLayout(false);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
namespace Trionic5Tools
{
/// <summary>
/// ECUFileType
/// </summary>
public enum ECUFileType
{
Trionic52File,
Trionic55File,
Trionic7File,
Trionic8File,
UnknownFile
}
/// <summary>
/// </summary>
abstract public class IECUFile
{
/// <summary>
/// </summary>
///
public abstract string LibraryPath
{
get;
set;
}
public delegate void DecodeProgress(object sender, DecodeProgressEventArgs e);
abstract public event DecodeProgress onDecodeProgress;
public delegate void TransactionLogChanged(object sender, TransactionsEventArgs e);
abstract public event TransactionLogChanged onTransactionLogChanged;
abstract public int GetMaxInjection();
abstract public void SetHardcodedRPMLimit(string filename, int rpmlimit);
abstract public int GetHardcodedRPMLimit(string filename);
abstract public int GetHardcodedRPMLimitTwo(string filename);
abstract public MapSensorType DetermineMapSensorType();
abstract public TuningStage DetermineTuningStage(out float max_boostRequest);
abstract public byte[] ReadData(uint offset, uint length);
abstract public int[] GetSymbolAsIntArray(string symbolname);
abstract public int GetSymbolAsInt(string symbolname);
abstract public int[] GetXaxisValues(string filename, string symbolname);
abstract public int[] GetYaxisValues(string filename, string symbolname);
public abstract int[] Temp_steg_array
{
get;
set;
}
public abstract int[] Kyltemp_steg_array
{
get;
set;
}
public abstract int[] Kyltemp_tab_array
{
get;
set;
}
public abstract int[] Lamb_kyl_array
{
get;
set;
}
public abstract int[] Lufttemp_steg_array
{
get;
set;
}
public abstract int[] Lufttemp_tab_array
{
get;
set;
}
public abstract int[] Luft_kompfak_array
{
get;
set;
}
/*Temp_steg = GetSymbolAsIntArray("Temp_steg!");
Kyltemp_steg = GetSymbolAsIntArray("Kyltemp_steg!");
Kyltemp_tab = GetSymbolAsIntArray("Kyltemp_tab!");
Lamb_kyl = GetSymbolAsIntArray("Lamb_kyl!");
Lufttemp_steg = GetSymbolAsIntArray("Lufttemp_steg!");
Lufttemp_tab = GetSymbolAsIntArray("Lufttemp_tab!");
Luft_kompfak = GetSymbolAsIntArray("Luft_kompfak!");*/
abstract public int GetRegulationDivisorValue();
abstract public void SetRegulationDivisorValue(int rpm);
abstract public int GetManualRpmLow();
abstract public DataTable CheckForAnomalies();
abstract public void SetTransactionLog(TrionicTransactionLog transactionLog);
//abstract public int GetInjectorType();
//abstract public void SetInjectorType(InjectorType type);
abstract public void WriteInjectorTypeMarker(InjectorType injectorType);
abstract public void WriteTurboTypeMarker(TurboType turboType);
abstract public void WriteTuningStageMarker(TuningStage tuningStage);
abstract public int ReadInjectorTypeMarker();
abstract public int ReadTurboTypeMarker();
abstract public int ReadTuningStageMarker();
abstract public long GetStartVectorAddress(string filename, int number);
abstract public long[] GetVectorAddresses(string filename);
abstract public int GetManualRpmHigh();
abstract public int GetAutoRpmLow();
abstract public int GetAutoRpmHigh();
abstract public int GetMaxBoostError();
abstract public void SetManualRpmLow(int rpm);
abstract public void SetManualRpmHigh(int rpm);
abstract public void SetAutoRpmLow(int rpm);
abstract public void SetAutoRpmHigh(int rpm);
abstract public void SetMaxBoostError(int boosterror);
abstract public void SetAutoUpdateChecksum(bool autoUpdate);
abstract public Int64 GetMemorySyncCounter();
abstract public DateTime GetMemorySyncDate();
abstract public void SetMemorySyncCounter(Int64 countervalue);
abstract public void SetMemorySyncDate(DateTime syncdt);
abstract public byte[] ReadDataFromFile(string filename, uint offset, uint length);
abstract public bool WriteDataNoLog(byte[] data, uint offset);
abstract public bool WriteData(byte[] data, uint offset);
abstract public bool WriteData(byte[] data, uint offset, string note);
abstract public bool WriteDataNoCounterIncrease(byte[] data, uint offset);
abstract public bool ValidateChecksum();
abstract public void UpdateChecksum();
abstract public bool HasSymbol(string symbolname);
abstract public bool IsTableSixteenBits(string symbolname);
abstract public double GetCorrectionFactorForMap(string symbolname);
abstract public int[] GetMapXaxisValues(string symbolname);
abstract public void GetMapAxisDescriptions(string symbolname, out string x, out string y, out string z);
abstract public void GetMapMatrixWitdhByName(string symbolname, out int columns, out int rows);
abstract public int[] GetMapYaxisValues(string symbolname);
abstract public double GetOffsetForMap(string symbolname);
abstract public void SelectFile(string filename);
abstract public void BackupFile();
abstract public string GetSoftwareVersion();
abstract public string GetPartnumber();
abstract public Trionic5FileInformation ParseFile();
abstract public Trionic5FileInformation GetFileInfo();
abstract public ECUFileType DetermineFileType();
abstract public MapSensorType GetMapSensorType(bool autoDetectMapsensorType);
abstract public bool Exists();
abstract public Trionic5Properties GetTrionicProperties();
abstract public void SetTrionicOptions(Trionic5Properties properties);
}
public class TransactionsEventArgs : System.EventArgs
{
private TransactionEntry _entry;
public TransactionEntry Entry
{
get { return _entry; }
set { _entry = value; }
}
public TransactionsEventArgs(TransactionEntry entry)
{
this._entry = entry;
}
}
public class DecodeProgressEventArgs : System.EventArgs
{
private int _progress;
public int Progress
{
get { return _progress; }
set { _progress = value; }
}
public DecodeProgressEventArgs(int progress)
{
this._progress = progress;
}
}
}
| |
//
// Encog(tm) Core v3.3 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Encog.Engine.Network.Activation;
using Encog.ML.Factory;
using Encog.Util.CSV;
using Encog.ML;
using Encog.ML.Train;
using Encog.ML.Data;
namespace Encog.Plugin.SystemPlugin
{
public class SystemActivationPlugin : IEncogPluginService1
{
/// <inheritdoc/>
public String PluginDescription
{
get
{
return "This plugin provides the built in machine " +
"learning methods for Encog.";
}
}
/// <inheritdoc/>
public String PluginName
{
get
{
return "HRI-System-Methods";
}
}
/// <summary>
/// This is a type-1 plugin.
/// </summary>
public int PluginType
{
get
{
return 1;
}
}
/// <summary>
/// Allocate an activation function.
/// </summary>
/// <param name="name">The name of the activation function.</param>
/// <returns>The activation function.</returns>
private IActivationFunction AllocateAF(String name)
{
if (String.Compare(name, MLActivationFactory.AF_BIPOLAR) == 0)
{
return new ActivationBiPolar();
}
if (String.Compare(name, MLActivationFactory.AF_COMPETITIVE) == 0)
{
return new ActivationCompetitive();
}
if (String.Compare(name, MLActivationFactory.AF_GAUSSIAN) == 0)
{
return new ActivationGaussian();
}
if (String.Compare(name, MLActivationFactory.AF_LINEAR) == 0)
{
return new ActivationLinear();
}
if (String.Compare(name, MLActivationFactory.AF_LOG) == 0)
{
return new ActivationLOG();
}
if (String.Compare(name, MLActivationFactory.AF_RAMP) == 0)
{
return new ActivationRamp();
}
if (String.Compare(name, MLActivationFactory.AF_SIGMOID) == 0)
{
return new ActivationSigmoid();
}
if (String.Compare(name, MLActivationFactory.AF_SIN) == 0)
{
return new ActivationSIN();
}
if (String.Compare(name, MLActivationFactory.AF_SOFTMAX) == 0)
{
return new ActivationSoftMax();
}
if (String.Compare(name, MLActivationFactory.AF_STEP) == 0)
{
return new ActivationStep();
}
if (String.Compare(name, MLActivationFactory.AF_TANH) == 0)
{
return new ActivationTANH();
}
if ( String.Compare(name, MLActivationFactory.AF_SSIGMOID) ==0 )
{
return new ActivationSteepenedSigmoid();
}
return null;
}
/// <inheritdoc/>
public IActivationFunction CreateActivationFunction(String fn)
{
String name;
double[] p;
int index = fn.IndexOf('[');
if (index != -1)
{
name = fn.Substring(0, index).ToLower();
int index2 = fn.IndexOf(']');
if (index2 == -1)
{
throw new EncogError(
"Unbounded [ while parsing activation function.");
}
String a = fn.Substring(index + 1, index2);
p = NumberList.FromList(CSVFormat.EgFormat, a);
}
else
{
name = fn.ToLower();
p = new double[0];
}
IActivationFunction af = AllocateAF(name);
if (af == null)
{
return null;
}
if (af.ParamNames.Length != p.Length)
{
throw new EncogError(name + " expected "
+ af.ParamNames.Length + ", but " + p.Length
+ " were provided.");
}
for (int i = 0; i < af.ParamNames.Length; i++)
{
af.Params[i] = p[i];
}
return af;
}
/// <inheritdoc/>
public IMLMethod CreateMethod(String methodType, String architecture,
int input, int output)
{
return null;
}
/// <inheritdoc/>
public IMLTrain CreateTraining(IMLMethod method, IMLDataSet training,
String type, String args)
{
return null;
}
/// <inheritdoc/>
public int PluginServiceType
{
get
{
return EncogPluginBaseConst.SERVICE_TYPE_GENERAL;
}
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Linq;
using System.Globalization;
using System.ComponentModel;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
using Newtonsoft.Json.Serialization;
namespace Newtonsoft.Json.Schema
{
/// <summary>
/// Generates a <see cref="JsonSchema"/> from a specified <see cref="Type"/>.
/// </summary>
public class JsonSchemaGenerator
{
/// <summary>
/// Gets or sets how undefined schemas are handled by the serializer.
/// </summary>
public UndefinedSchemaIdHandling UndefinedSchemaIdHandling { get; set; }
private IContractResolver _contractResolver;
/// <summary>
/// Gets or sets the contract resolver.
/// </summary>
/// <value>The contract resolver.</value>
public IContractResolver ContractResolver
{
get
{
if (_contractResolver == null)
return DefaultContractResolver.Instance;
return _contractResolver;
}
set { _contractResolver = value; }
}
private class TypeSchema
{
public Type Type { get; private set; }
public JsonSchema Schema { get; private set;}
public TypeSchema(Type type, JsonSchema schema)
{
ValidationUtils.ArgumentNotNull(type, "type");
ValidationUtils.ArgumentNotNull(schema, "schema");
Type = type;
Schema = schema;
}
}
private JsonSchemaResolver _resolver;
private IList<TypeSchema> _stack = new List<TypeSchema>();
private JsonSchema _currentSchema;
private JsonSchema CurrentSchema
{
get { return _currentSchema; }
}
private void Push(TypeSchema typeSchema)
{
_currentSchema = typeSchema.Schema;
_stack.Add(typeSchema);
_resolver.LoadedSchemas.Add(typeSchema.Schema);
}
private TypeSchema Pop()
{
TypeSchema popped = _stack[_stack.Count - 1];
_stack.RemoveAt(_stack.Count - 1);
TypeSchema newValue = _stack.LastOrDefault();
if (newValue != null)
{
_currentSchema = newValue.Schema;
}
else
{
_currentSchema = null;
}
return popped;
}
/// <summary>
/// Generate a <see cref="JsonSchema"/> from the specified type.
/// </summary>
/// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param>
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
public JsonSchema Generate(Type type)
{
return Generate(type, new JsonSchemaResolver(), false);
}
/// <summary>
/// Generate a <see cref="JsonSchema"/> from the specified type.
/// </summary>
/// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param>
/// <param name="resolver">The <see cref="JsonSchemaResolver"/> used to resolve schema references.</param>
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
public JsonSchema Generate(Type type, JsonSchemaResolver resolver)
{
return Generate(type, resolver, false);
}
/// <summary>
/// Generate a <see cref="JsonSchema"/> from the specified type.
/// </summary>
/// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param>
/// <param name="rootSchemaNullable">Specify whether the generated root <see cref="JsonSchema"/> will be nullable.</param>
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
public JsonSchema Generate(Type type, bool rootSchemaNullable)
{
return Generate(type, new JsonSchemaResolver(), rootSchemaNullable);
}
/// <summary>
/// Generate a <see cref="JsonSchema"/> from the specified type.
/// </summary>
/// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param>
/// <param name="resolver">The <see cref="JsonSchemaResolver"/> used to resolve schema references.</param>
/// <param name="rootSchemaNullable">Specify whether the generated root <see cref="JsonSchema"/> will be nullable.</param>
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
public JsonSchema Generate(Type type, JsonSchemaResolver resolver, bool rootSchemaNullable)
{
ValidationUtils.ArgumentNotNull(type, "type");
ValidationUtils.ArgumentNotNull(resolver, "resolver");
_resolver = resolver;
return GenerateInternal(type, (!rootSchemaNullable) ? Required.Always : Required.Default, false);
}
private string GetTitle(Type type)
{
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(type);
if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Title))
return containerAttribute.Title;
return null;
}
private string GetDescription(Type type)
{
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(type);
if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Description))
return containerAttribute.Description;
#if !PocketPC
DescriptionAttribute descriptionAttribute = ReflectionUtils.GetAttribute<DescriptionAttribute>(type);
if (descriptionAttribute != null)
return descriptionAttribute.Description;
#endif
return null;
}
private string GetTypeId(Type type, bool explicitOnly)
{
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(type);
if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Id))
return containerAttribute.Id;
if (explicitOnly)
return null;
switch (UndefinedSchemaIdHandling)
{
case UndefinedSchemaIdHandling.UseTypeName:
return type.FullName;
case UndefinedSchemaIdHandling.UseAssemblyQualifiedName:
return type.AssemblyQualifiedName;
default:
return null;
}
}
private JsonSchema GenerateInternal(Type type, Required valueRequired, bool required)
{
ValidationUtils.ArgumentNotNull(type, "type");
string resolvedId = GetTypeId(type, false);
string explicitId = GetTypeId(type, true);
if (!string.IsNullOrEmpty(resolvedId))
{
JsonSchema resolvedSchema = _resolver.GetSchema(resolvedId);
if (resolvedSchema != null)
{
// resolved schema is not null but referencing member allows nulls
// change resolved schema to allow nulls. hacky but what are ya gonna do?
if (valueRequired != Required.Always && !HasFlag(resolvedSchema.Type, JsonSchemaType.Null))
resolvedSchema.Type |= JsonSchemaType.Null;
if (required && resolvedSchema.Required != true)
resolvedSchema.Required = true;
return resolvedSchema;
}
}
// test for unresolved circular reference
if (_stack.Any(tc => tc.Type == type))
{
throw new Exception("Unresolved circular reference for type '{0}'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.".FormatWith(CultureInfo.InvariantCulture, type));
}
JsonContract contract = ContractResolver.ResolveContract(type);
JsonConverter converter;
if ((converter = contract.Converter) != null || (converter = contract.InternalConverter) != null)
{
JsonSchema converterSchema = converter.GetSchema();
if (converterSchema != null)
return converterSchema;
}
Push(new TypeSchema(type, new JsonSchema()));
if (explicitId != null)
CurrentSchema.Id = explicitId;
if (required)
CurrentSchema.Required = true;
CurrentSchema.Title = GetTitle(type);
CurrentSchema.Description = GetDescription(type);
if (converter != null)
{
// todo: Add GetSchema to JsonConverter and use here?
CurrentSchema.Type = JsonSchemaType.Any;
}
else if (contract is JsonDictionaryContract)
{
CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired);
Type keyType;
Type valueType;
ReflectionUtils.GetDictionaryKeyValueTypes(type, out keyType, out valueType);
if (keyType != null)
{
// can be converted to a string
if (typeof (IConvertible).IsAssignableFrom(keyType))
{
CurrentSchema.AdditionalProperties = GenerateInternal(valueType, Required.Default, false);
}
}
}
else if (contract is JsonArrayContract)
{
CurrentSchema.Type = AddNullType(JsonSchemaType.Array, valueRequired);
CurrentSchema.Id = GetTypeId(type, false);
JsonArrayAttribute arrayAttribute = JsonTypeReflector.GetJsonContainerAttribute(type) as JsonArrayAttribute;
bool allowNullItem = (arrayAttribute != null) ? arrayAttribute.AllowNullItems : true;
Type collectionItemType = ReflectionUtils.GetCollectionItemType(type);
if (collectionItemType != null)
{
CurrentSchema.Items = new List<JsonSchema>();
CurrentSchema.Items.Add(GenerateInternal(collectionItemType, (!allowNullItem) ? Required.Always : Required.Default, false));
}
}
else if (contract is JsonPrimitiveContract)
{
CurrentSchema.Type = GetJsonSchemaType(type, valueRequired);
if (CurrentSchema.Type == JsonSchemaType.Integer && type.IsEnum && !type.IsDefined(typeof(FlagsAttribute), true))
{
CurrentSchema.Enum = new List<JToken>();
CurrentSchema.Options = new Dictionary<JToken, string>();
EnumValues<long> enumValues = EnumUtils.GetNamesAndValues<long>(type);
foreach (EnumValue<long> enumValue in enumValues)
{
JToken value = JToken.FromObject(enumValue.Value);
CurrentSchema.Enum.Add(value);
CurrentSchema.Options.Add(value, enumValue.Name);
}
}
}
else if (contract is JsonObjectContract)
{
CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired);
CurrentSchema.Id = GetTypeId(type, false);
GenerateObjectSchema(type, (JsonObjectContract)contract);
}
#if !SILVERLIGHT && !PocketPC
else if (contract is JsonISerializableContract)
{
CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired);
CurrentSchema.Id = GetTypeId(type, false);
GenerateISerializableContract(type, (JsonISerializableContract) contract);
}
#endif
else if (contract is JsonStringContract)
{
JsonSchemaType schemaType = (!ReflectionUtils.IsNullable(contract.UnderlyingType))
? JsonSchemaType.String
: AddNullType(JsonSchemaType.String, valueRequired);
CurrentSchema.Type = schemaType;
}
else if (contract is JsonLinqContract)
{
CurrentSchema.Type = JsonSchemaType.Any;
}
else
{
throw new Exception("Unexpected contract type: {0}".FormatWith(CultureInfo.InvariantCulture, contract));
}
return Pop().Schema;
}
private JsonSchemaType AddNullType(JsonSchemaType type, Required valueRequired)
{
if (valueRequired != Required.Always)
return type | JsonSchemaType.Null;
return type;
}
private bool HasFlag(DefaultValueHandling value, DefaultValueHandling flag)
{
return ((value & flag) == flag);
}
private void GenerateObjectSchema(Type type, JsonObjectContract contract)
{
CurrentSchema.Properties = new Dictionary<string, JsonSchema>();
foreach (JsonProperty property in contract.Properties)
{
if (!property.Ignored)
{
bool optional = property.NullValueHandling == NullValueHandling.Ignore ||
HasFlag(property.DefaultValueHandling.GetValueOrDefault(), DefaultValueHandling.Ignore) ||
property.ShouldSerialize != null ||
property.GetIsSpecified != null;
JsonSchema propertySchema = GenerateInternal(property.PropertyType, property.Required, !optional);
if (property.DefaultValue != null)
propertySchema.Default = JToken.FromObject(property.DefaultValue);
CurrentSchema.Properties.Add(property.PropertyName, propertySchema);
}
}
if (type.IsSealed)
CurrentSchema.AllowAdditionalProperties = false;
}
#if !SILVERLIGHT && !PocketPC
private void GenerateISerializableContract(Type type, JsonISerializableContract contract)
{
CurrentSchema.AllowAdditionalProperties = true;
}
#endif
internal static bool HasFlag(JsonSchemaType? value, JsonSchemaType flag)
{
// default value is Any
if (value == null)
return true;
bool match = ((value & flag) == flag);
if (match)
return true;
// integer is a subset of float
if (value == JsonSchemaType.Float && flag == JsonSchemaType.Integer)
return true;
return false;
}
private JsonSchemaType GetJsonSchemaType(Type type, Required valueRequired)
{
JsonSchemaType schemaType = JsonSchemaType.None;
if (valueRequired != Required.Always && ReflectionUtils.IsNullable(type))
{
schemaType = JsonSchemaType.Null;
if (ReflectionUtils.IsNullableType(type))
type = Nullable.GetUnderlyingType(type);
}
TypeCode typeCode = Type.GetTypeCode(type);
switch (typeCode)
{
case TypeCode.Empty:
case TypeCode.Object:
return schemaType | JsonSchemaType.String;
case TypeCode.DBNull:
return schemaType | JsonSchemaType.Null;
case TypeCode.Boolean:
return schemaType | JsonSchemaType.Boolean;
case TypeCode.Char:
return schemaType | JsonSchemaType.String;
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
return schemaType | JsonSchemaType.Integer;
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return schemaType | JsonSchemaType.Float;
// convert to string?
case TypeCode.DateTime:
return schemaType | JsonSchemaType.String;
case TypeCode.String:
return schemaType | JsonSchemaType.String;
default:
throw new Exception("Unexpected type code '{0}' for type '{1}'.".FormatWith(CultureInfo.InvariantCulture, typeCode, type));
}
}
}
}
| |
using System.Diagnostics;
using System;
using System.Management;
using System.Collections;
using Microsoft.VisualBasic;
using System.Data.SqlClient;
using System.Web.UI.Design;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
namespace ACSGhana.Web.Framework
{
namespace Enumerations
{
public enum BehaviorType
{
BrowsingCategory = 1,
BrowsingProduct = 2,
ClickingOnAd = 3,
ClickingOnPromo = 4,
ClickingOnUpsell = 5,
ClickingOnCrosssell = 6,
ClickingOnBundle = 7,
RunningSearch = 8,
AddingItemToBasket = 9,
CheckingOut = 10,
Paying = 11,
ViewingReceipt = 12,
RemovingItemFromBasket = 13,
AdjustingQuantity = 14,
LoggingIn = 15,
LoggingOut = 16
}
public enum AttributeType
{
SingleSelection,
MultipleSelection,
UserInput
}
public enum AdBoxPlacement
{
Right,
Center,
Left
}
public enum ProductType
{
DownloadableSoftware = 1,
Books = 2,
ElectronicGoods = 3,
SoftwareShipOnly = 4
}
public enum ProductStatus
{
Active = 1,
@New = 2,
OnBackorder = 3,
TopSeller = 4,
Featured = 5,
Discontinued = 6,
NoLongerAvailable = 7,
FutureRelease = 8,
Inactive = 99
}
/// <summary>
/// The Order Status
/// </summary>
public enum OrderStatus
{
NotProcessed = 9999,
ReceivedPaymentAgreement = 1,
VerifiedPaymentEligibility = 10,
RecievedDepositPayment = 20
}
public enum USState
{
/// AK
/// AL
[Description("AK")]AK = 1,
/// AR
[Description("AL")]AL = 2,
/// AZ
[Description("AR")]AR = 3,
/// CA
[Description("AZ")]AZ = 4,
/// CO
[Description("CA")]CA = 5,
/// CT
[Description("CO")]CO = 6,
/// DC
[Description("CT")]CT = 7,
/// DE
[Description("DC")]DC = 8,
/// FL
[Description("DE")]DE = 9,
/// GA
[Description("FL")]FL = 10,
/// HI
[Description("GA")]GA = 11,
/// IA
[Description("HI")]HI = 12,
/// ID
[Description("IA")]IA = 13,
/// IL
[Description("ID")]ID = 14,
/// IN
[Description("IL")]IL = 15,
/// KS
[Description("IN")]@IN = 16,
/// KY
[Description("KS")]KS = 17,
/// LA
[Description("KY")]KY = 18,
/// MA
[Description("LA")]LA = 19,
/// MD
[Description("MA")]MA = 20,
/// ME
[Description("MD")]MD = 21,
/// MI
[Description("ME")]@ME = 22,
/// MN
[Description("MI")]MI = 23,
/// MO
[Description("MN")]MN = 24,
/// MS
[Description("MO")]MO = 25,
/// MT
[Description("MS")]MS = 26,
/// NC
[Description("MT")]MT = 27,
/// ND
[Description("NC")]NC = 28,
/// NE
[Description("ND")]ND = 29,
/// NH
[Description("NE")]NE = 30,
/// NJ
[Description("NH")]NH = 31,
/// NM
[Description("NJ")]NJ = 32,
/// NV
[Description("NM")]NM = 33,
/// NY
[Description("NV")]NV = 34,
/// OH
[Description("NY")]NY = 35,
/// OK
[Description("OH")]OH = 36,
/// OR
[Description("OK")]OK = 37,
/// PA
[Description("OR")]@OR = 38,
/// RI
[Description("PA")]PA = 39,
/// SC
[Description("RI")]RI = 40,
/// SD
[Description("SC")]SC = 41,
/// TN
[Description("SD")]SD = 42,
/// TX
[Description("TN")]TN = 43,
/// UT
[Description("TX")]TX = 44,
/// VA
[Description("UT")]UT = 45,
/// VT
[Description("VA")]VA = 46,
/// WA
[Description("VT")]VT = 47,
/// WI
[Description("WA")]WA = 48,
/// WV
[Description("WI")]WI = 49,
/// WY
[Description("WV")]WV = 50,
[Description("WY")]WY = 51
}
public enum CurrencyCode
{
[Description("Afghanistan afghani")]AFA = 1,
[Description("Albanian lek")]ALL = 2,
[Description("Algerian dinar")]DZD = 3,
[Description("Angolan kwanza reajustado")]AOR = 4,
[Description("Argentine peso")]ARS = 5,
[Description("Armenian dram")]AMD = 6,
[Description("Aruban guilder")]AWG = 7,
[Description("Australian dollar")]AUD = 8,
[Description("Azerbaijanian new manat")]AZN = 9,
[Description("Bahamian dollar")]BSD = 10,
[Description("Bahraini dinar")]BHD = 11,
[Description("Bangladeshi taka")]BDT = 12,
[Description("Barbados dollar")]BBD = 13,
[Description("Belarusian ruble")]BYR = 14,
[Description("Belize dollar")]BZD = 15,
[Description("Bermudian dollar")]BMD = 16,
[Description("Bhutan ngultrum")]BTN = 17,
[Description("Bolivian boliviano")]BOB = 18,
[Description("Botswana pula")]BWP = 19,
[Description("Brazilian real")]BRL = 20,
[Description("British pound")]GBP = 21,
[Description("Brunei dollar")]BND = 22,
[Description("Bulgarian lev")]BGN = 23,
[Description("Burundi franc")]BIF = 24,
[Description("Cambodian riel")]KHR = 25,
[Description("Canadian dollar")]CAD = 26,
[Description("Cape Verde escudo")]CVE = 27,
[Description("Cayman Islands dollar")]KYD = 28,
[Description("CFA franc BCEAO")]XOF = 29,
[Description("CFA franc BEAC")]XAF = 30,
[Description("CFP franc")]XPF = 31,
[Description("Chilean peso")]CLP = 32,
[Description("Chinese yuan renminbi")]CNY = 33,
[Description("Colombian peso")]COP = 34,
[Description("Comoros franc")]KMF = 35,
[Description("Congolese franc")]CDF = 36,
[Description("Costa Rican colon")]CRC = 37,
[Description("Croatian kuna")]HRK = 38,
[Description("Cuban peso")]CUP = 39,
[Description("Cypriot pound")]CYP = 40,
[Description("Czech koruna")]CZK = 41,
[Description("Danish krone")]DKK = 42,
[Description("Djibouti franc")]DJF = 43,
[Description("Dominican peso")]DOP = 44,
[Description("East Caribbean dollar")]XCD = 45,
[Description("Egyptian pound")]EGP = 46,
[Description("El Salvador colon")]SVC = 47,
[Description("Eritrean nakfa")]ERN = 48,
[Description("Estonian kroon")]EEK = 49,
[Description("Ethiopian birr")]ETB = 50,
[Description("EU euro")]EUR = 51,
[Description("Falkland Islands pound")]FKP = 52,
[Description("Fiji dollar")]FJD = 53,
[Description("Gambian dalasi")]GMD = 54,
[Description("Georgian lari")]GEL = 55,
[Description("Ghanaian cedi")]GHC = 56,
[Description("Gibraltar pound")]GIP = 57,
[Description("Gold (ounce)")]XAU = 58,
[Description("Gold franc")]XFO = 59,
[Description("Guatemalan quetzal")]GTQ = 60,
[Description("Guinean franc")]GNF = 61,
[Description("Guyana dollar")]GYD = 62,
[Description("Haitian gourde")]HTG = 63,
[Description("Honduran lempira")]HNL = 64,
[Description("Hong Kong SAR dollar")]HKD = 65,
[Description("Hungarian forint")]HUF = 66,
[Description("Icelandic krona")]ISK = 67,
[Description("IMF special drawing right")]XDR = 68,
[Description("Indian rupee")]INR = 69,
[Description("Indonesian rupiah")]IDR = 70,
[Description("Iranian rial")]IRR = 71,
[Description("Iraqi dinar")]IQD = 72,
[Description("Israeli new shekel")]ILS = 73,
[Description("Jamaican dollar")]JMD = 74,
[Description("Japanese yen")]JPY = 75,
[Description("Jordanian dinar")]JOD = 76,
[Description("Kazakh tenge")]KZT = 77,
[Description("Kenyan shilling")]KES = 78,
[Description("Kuwaiti dinar")]KWD = 79,
[Description("Kyrgyz som")]KGS = 80,
[Description("Lao kip")]LAK = 81,
[Description("Latvian lats")]LVL = 82,
[Description("Lebanese pound")]LBP = 83,
[Description("Lesotho loti")]LSL = 84,
[Description("Liberian dollar")]LRD = 85,
[Description("Libyan dinar")]LYD = 86,
[Description("Lithuanian litas")]LTL = 87,
[Description("Macao SAR pataca")]MOP = 88,
[Description("Macedonian denar")]MKD = 89,
[Description("Malagasy ariary")]MGA = 90,
[Description("Malawi kwacha")]MWK = 91,
[Description("Malaysian ringgit")]MYR = 92,
[Description("Maldivian rufiyaa")]MVR = 93,
[Description("Maltese lira")]MTL = 94,
[Description("Mauritanian ouguiya")]MRO = 95,
[Description("Mauritius rupee")]MUR = 96,
[Description("Mexican peso")]MXN = 97,
[Description("Moldovan leu")]MDL = 98,
[Description("Mongolian tugrik")]MNT = 99,
[Description("Moroccan dirham")]MAD = 100,
[Description("Mozambique new metical")]MZN = 101,
[Description("Myanmar kyat")]MMK = 102,
[Description("Namibian dollar")]NAD = 103,
[Description("Nepalese rupee")]NPR = 104,
[Description("Netherlands Antillian guilder")]ANG = 105,
[Description("New Zealand dollar")]NZD = 106,
[Description("Nicaraguan cordoba oro")]NIO = 107,
[Description("Nigerian naira")]NGN = 108,
[Description("North Korean won")]KPW = 109,
[Description("Norwegian krone")]NOK = 110,
[Description("Omani rial")]OMR = 111,
[Description("Pakistani rupee")]PKR = 112,
[Description("Palladium (ounce)")]XPD = 113,
[Description("Panamanian balboa")]PAB = 114,
[Description("Papua New Guinea kina")]PGK = 115,
[Description("Paraguayan guarani")]PYG = 116,
[Description("Peruvian nuevo sol")]PEN = 117,
[Description("Philippine peso")]PHP = 118,
[Description("Platinum (ounce)")]XPT = 119,
[Description("Polish zloty")]PLN = 120,
[Description("Qatari rial")]QAR = 121,
[Description("Romanian new leu")]RON = 122,
[Description("Russian ruble")]RUB = 123,
[Description("Rwandan franc")]RWF = 124,
[Description("Saint Helena pound")]SHP = 125,
[Description("Samoan tala")]WST = 126,
[Description("Sao Tome and Principe dobra")]STD = 127,
[Description("Saudi riyal")]SAR = 128,
[Description("Serbian dinar")]CSD = 129,
[Description("Seychelles rupee")]SCR = 130,
[Description("Sierra Leone leone")]SLL = 131,
[Description("Silver (ounce)")]XAG = 132,
[Description("Singapore dollar")]SGD = 133,
[Description("Slovak koruna")]SKK = 134,
[Description("Slovenian tolar")]SIT = 135,
[Description("Solomon Islands dollar")]SBD = 136,
[Description("Somali shilling")]SOS = 137,
[Description("South African rand")]ZAR = 138,
[Description("South Korean won")]KRW = 139,
[Description("Sri Lanka rupee")]LKR = 140,
[Description("Sudanese dinar")]SDD = 141,
[Description("Suriname dollar")]SRD = 142,
[Description("Swaziland lilangeni")]SZL = 143,
[Description("Swedish krona")]SEK = 144,
[Description("Swiss franc")]CHF = 145,
[Description("Syrian pound")]SYP = 146,
[Description("Taiwan New dollar")]TWD = 147,
[Description("Tajik somoni")]TJS = 148,
[Description("Tanzanian shilling")]TZS = 149,
[Description("Thai baht")]THB = 150,
[Description("Tongan pa\'anga")]TOP = 151,
[Description("Trinidad and Tobago dollar")]TTD = 152,
[Description("Tunisian dinar")]TND = 153,
[Description("Turkish lira")]@TRY = 154,
[Description("Turkmen manat")]TMM = 155,
[Description("UAE dirham")]AED = 156,
[Description("Uganda new shilling")]UGX = 157,
[Description("UIC franc")]XFU = 158,
[Description("Ukrainian hryvnia")]UAH = 159,
[Description("Uruguayan peso uruguayo")]UYU = 160,
[Description("US dollar")]USD = 161,
[Description("Uzbekistani sum")]UZS = 162,
[Description("Vanuatu vatu")]VUV = 163,
[Description("Venezuelan bolivar")]VEB = 164,
[Description("Vietnamese dong")]VND = 165,
[Description("Yemeni rial")]YER = 166,
[Description("Zambian kwacha")]ZMK = 167,
[Description("Zimbabwe dollar")]ZWD = 168
}
public enum Country
{
[Description("Afghanistan")]AF = 1,
[Description("Albania")]AL = 2,
[Description("Algeria")]DZ = 3,
[Description("American Samoa")]@AS = 4,
[Description("Andorra")]AD = 5,
[Description("Angola")]AO = 6,
[Description("Anguilla")]AI = 7,
[Description("Antarctica")]AQ = 8,
[Description("Antigua and Barbuda")]AG = 9,
[Description("Argentina")]AR = 10,
[Description("Armenia")]AM = 11,
[Description("Aruba")]AW = 12,
[Description("Australia")]AU = 13,
[Description("Austria")]AT = 14,
[Description("Azerbaijan")]AZ = 15,
[Description("Bahamas")]BS = 16,
[Description("Bahrain")]BH = 17,
[Description("Bangladesh")]BD = 18,
[Description("Barbados")]BB = 19,
[Description("Belarus")]BY = 20,
[Description("Belgium")]BE = 21,
[Description("Belize")]BZ = 22,
[Description("Benin")]BJ = 23,
[Description("Bermuda")]BM = 24,
[Description("Bhutan")]BT = 25,
[Description("Bolivia")]BO = 26,
[Description("Bosnia and Herzegovina")]BA = 27,
[Description("Botswana")]BW = 28,
[Description("Bouvet Island")]BV = 29,
[Description("Brazil")]BR = 30,
[Description("British Indian Ocean Territory")]IO = 31,
[Description("British Virgin Islands")]VG = 32,
[Description("Brunei Darussalam")]BN = 33,
[Description("Bulgaria")]BG = 34,
[Description("Burkina Faso")]BF = 35,
[Description("Burundi")]BI = 36,
[Description("Cambodia")]KH = 37,
[Description("Cameroon")]CM = 38,
[Description("Canada")]CA = 39,
[Description("Cape Verde")]CV = 40,
[Description("Cayman Islands")]KY = 41,
[Description("Central African Republic")]CF = 42,
[Description("Chad")]TD = 43,
[Description("Chile")]CL = 44,
[Description("China")]CN = 45,
[Description("Christmas Island")]CX = 46,
[Description("Cocos")]CC = 47,
[Description("Colombia")]CO = 48,
[Description("Comoros")]KM = 49,
[Description("Congo")]CG = 50,
[Description("Cook Islands")]CK = 51,
[Description("Costa Rica")]CR = 52,
[Description("Croatia")]HR = 53,
[Description("Cuba")]CU = 54,
[Description("Cyprus")]CY = 55,
[Description("Czech Republic")]CZ = 56,
[Description("Denmark")]DK = 57,
[Description("Djibouti")]DJ = 58,
[Description("Dominica")]DM = 59,
[Description("Dominican Republic")]@DO = 60,
[Description("East Timor")]TP = 61,
[Description("Ecuador")]EC = 62,
[Description("Egypt")]EG = 63,
[Description("El Salvador")]SV = 64,
[Description("Equatorial Guinea")]GQ = 65,
[Description("Eritrea")]ER = 66,
[Description("Estonia")]EE = 67,
[Description("Ethiopia")]ET = 68,
[Description("Falkland Islands")]FK = 69,
[Description("Faroe Islands")]FO = 70,
[Description("Fiji")]FJ = 71,
[Description("Finland")]FI = 72,
[Description("France")]FR = 73,
[Description("French Guiana")]GF = 74,
[Description("French Polynesia")]PF = 75,
[Description("French Southern Territories")]TF = 76,
[Description("Gabon")]GA = 77,
[Description("Gambia")]GM = 78,
[Description("Georgia")]GE = 79,
[Description("Germany")]DE = 80,
[Description("Ghana")]GH = 81,
[Description("Gibraltar")]GI = 82,
[Description("Greece")]GR = 83,
[Description("Greenland")]GL = 84,
[Description("Grenada")]GD = 85,
[Description("Guadeloupe")]GP = 86,
[Description("Guam")]GU = 87,
[Description("Guatemala")]GT = 88,
[Description("Guinea")]GN = 89,
[Description("Guinea-Bissau")]GW = 90,
[Description("Guyana")]GY = 91,
[Description("Haiti")]HT = 92,
[Description("Heard and McDonald Islands")]HM = 93,
[Description("Honduras")]HN = 94,
[Description("Hong Kong")]HK = 95,
[Description("Hungary")]HU = 96,
[Description("Iceland")]@IS = 97,
[Description("India")]@IN = 98,
[Description("Indonesia")]ID = 99,
[Description("Iran")]IR = 100,
[Description("Iraq")]IQ = 101,
[Description("Ireland")]IE = 102,
[Description("Israel")]IL = 103,
[Description("Italy")]IT = 104,
[Description("Ivory Coast")]CI = 105,
[Description("Jamaica")]JM = 106,
[Description("Japan")]JP = 107,
[Description("Jordan")]JO = 108,
[Description("Kazakhstan")]KZ = 109,
[Description("Kenya")]KE = 110,
[Description("Kiribati")]KI = 111,
[Description("Kuwait")]KW = 112,
[Description("Kyrgyzstan")]KG = 113,
[Description("Laos")]LA = 114,
[Description("Latvia")]LV = 115,
[Description("Lebanon")]LB = 116,
[Description("Lesotho")]LS = 117,
[Description("Liberia")]LR = 118,
[Description("Libya")]LY = 119,
[Description("Liechtenstein")]LI = 120,
[Description("Lithuania")]LT = 121,
[Description("Luxembourg")]LU = 122,
[Description("Macau")]MO = 123,
[Description("Macedonia")]MK = 124,
[Description("Madagascar")]MG = 125,
[Description("Malawi")]MW = 126,
[Description("Malaysia")]MY = 127,
[Description("Maldives")]MV = 128,
[Description("Mali")]ML = 129,
[Description("Malta")]MT = 130,
[Description("Marshall Islands")]MH = 131,
[Description("Martinique")]MQ = 132,
[Description("Mauritania")]MR = 133,
[Description("Mauritius")]MU = 134,
[Description("Mayotte")]YT = 135,
[Description("Mexico")]MX = 136,
[Description("Micronesia")]FM = 137,
[Description("Moldova")]MD = 138,
[Description("Monaco")]MC = 139,
[Description("Mongolia")]MN = 140,
[Description("Montserrat")]MS = 141,
[Description("Morocco")]MA = 142,
[Description("Mozambique")]MZ = 143,
[Description("Myanmar")]MM = 144,
[Description("Namibia")]NA = 145,
[Description("Nauru")]NR = 146,
[Description("Nepal")]NP = 147,
[Description("Netherlands")]NL = 148,
[Description("Netherlands Antilles")]AN = 149,
[Description("New Caledonia")]NC = 150,
[Description("New Zealand")]NZ = 151,
[Description("Nicaragua")]NI = 152,
[Description("Niger")]NE = 153,
[Description("Nigeria")]NG = 154,
[Description("Niue")]NU = 155,
[Description("Norfolk Island")]NF = 156,
[Description("North Korea")]KP = 157,
[Description("Northern Mariana Islands")]MP = 158,
[Description("Norway")]NO = 159,
[Description("Oman")]OM = 160,
[Description("Pakistan")]PK = 161,
[Description("Palau")]PW = 162,
[Description("Panama")]PA = 163,
[Description("Papua New Guinea")]PG = 164,
[Description("Paraguay")]PY = 165,
[Description("Peru")]PE = 166,
[Description("Philippines")]PH = 167,
[Description("Pitcairn")]PN = 168,
[Description("Poland")]PL = 169,
[Description("Portugal")]PT = 170,
[Description("Puerto Rico")]PR = 171,
[Description("Qatar")]QA = 172,
[Description("Reunion")]RE = 173,
[Description("Romania")]RO = 174,
[Description("Russian Federation")]RU = 175,
[Description("Rwanda")]RW = 176,
[Description("S. Georgia and S. Sandwich Islands")]GS = 177,
[Description("Saint Kitts and Nevis")]KN = 178,
[Description("Saint Lucia")]LC = 179,
[Description("Saint Vincent and The Grenadines")]VC = 180,
[Description("Samoa")]WS = 181,
[Description("San Marino")]SM = 182,
[Description("Sao Tome and Principe")]ST = 183,
[Description("Saudi Arabia")]SA = 184,
[Description("Senegal")]SN = 185,
[Description("Seychelles")]SC = 186,
[Description("Sierra Leone")]SL = 187,
[Description("Singapore")]SG = 188,
[Description("Slovakia")]SK = 189,
[Description("Slovenia")]SI = 190,
[Description("Solomon Islands")]SB = 191,
[Description("Somalia")]SO = 192,
[Description("South Africa")]ZA = 193,
[Description("South Korea")]KR = 194,
[Description("Soviet Union")]SU = 195,
[Description("Spain")]ES = 196,
[Description("Sri Lanka")]LK = 197,
[Description("St. Helena")]SH = 198,
[Description("St. Pierre and Miquelon")]PM = 199,
[Description("Sudan")]SD = 200,
[Description("Suriname")]SR = 201,
[Description("Svalbard and Jan Mayen Islands")]SJ = 202,
[Description("Swaziland")]SZ = 203,
[Description("Sweden")]SE = 204,
[Description("Switzerland")]CH = 205,
[Description("Syria")]SY = 206,
[Description("Taiwan")]TW = 207,
[Description("Tajikistan")]TJ = 208,
[Description("Tanzania")]TZ = 209,
[Description("Thailand")]TH = 210,
[Description("Togo")]TG = 211,
[Description("Tokelau")]TK = 212,
[Description("Tonga")]@TO = 213,
[Description("Trinidad and Tobago")]TT = 214,
[Description("Tunisia")]TN = 215,
[Description("Turkey")]TR = 216,
[Description("Turkmenistan")]TM = 217,
[Description("Turks and Caicos Islands")]TC = 218,
[Description("Tuvalu")]TV = 219,
[Description("Uganda")]UG = 220,
[Description("Ukraine")]UA = 221,
[Description("United Arab Emirates")]AE = 222,
[Description("United Kingdom")]GB = 223,
[Description("United States")]US = 224,
[Description("Uruguay")]UY = 225,
[Description("US Minor Outlying Islands")]UM = 226,
[Description("US Virgin Islands")]VI = 227,
[Description("Uzbekistan")]UZ = 228,
[Description("Vanuatu")]VU = 229,
[Description("Venezuela")]VE = 230,
[Description("Viet Nam")]VN = 231,
[Description("Wallis and Futuna Islands")]WF = 232,
[Description("Western Sahara")]EH = 233,
[Description("Yemen")]YE = 234,
[Description("Yugoslavia")]YU = 235,
[Description("Zaire")]ZR = 236,
[Description("Zambia")]ZM = 237,
[Description("Zimbabwe")]ZW = 238
}
}
}
| |
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEditorInternal;
using Object = UnityEngine.Object;
namespace UnityEditor.UI.Windows.Extensions.Utilities {
public class NewScriptWindow : EditorWindow {
private const int kButtonWidth = 120;
private const int kLabelWidth = 85;
private const string kLanguageEditorPrefName = "NewScriptLanguage";
private const string kTemplatePath = "CreateScriptDialog/SmartScriptTemplates";
private const string kResourcesTemplatePath = "Resources/SmartScriptTemplates";
private const string kMonoBehaviourName = "MonoBehaviour";
private const string kPlainClassName = "Empty Class";
private const string kCustomEditorClassName = "Editor";
private const string kTempEditorClassPrefix = "E:";
private const string kNoTemplateString = "No Template Found";
// char array can't be const for compiler reasons but this should still be treated as such.
private char[] kInvalidPathChars = new char[] { '<', '>', ':', '"', '|', '?', '*', (char)0 };
private char[] kPathSepChars = new char[] { '/', '\\' };
private ScriptPrescription m_ScriptPrescription;
private string m_BaseClass;
private string m_CustomEditorTargetClassName = string.Empty;
private bool m_IsEditorClass = false;
private bool m_IsCustomEditor = false;
private bool m_FocusTextFieldNow = true;
private GameObject m_GameObjectToAddTo;
private string m_Directory = string.Empty;
private Vector2 m_PreviewScroll;
private Vector2 m_OptionsScroll;
private bool m_ClearKeyboardControl = false;
private int m_TemplateIndex;
private string[] m_TemplateNames;
class Styles {
public GUIContent m_WarningContent = new GUIContent(string.Empty,
EditorGUIUtility.LoadRequired("Builtin Skins/Icons/console.warnicon.sml.png") as Texture2D);
public GUIStyle m_PreviewBox = new GUIStyle("OL Box");
public GUIStyle m_PreviewTitle = new GUIStyle("OL Title");
public GUIStyle m_LoweredBox = new GUIStyle("TextField");
public GUIStyle m_HelpBox = new GUIStyle("helpbox");
public Styles() {
m_LoweredBox.padding = new RectOffset(1, 1, 1, 1);
}
}
private static Styles m_Styles;
private string GetAbsoluteBuiltinTemplatePath() {
return Path.Combine(EditorApplication.applicationContentsPath, kResourcesTemplatePath);
}
private string GetAbsoluteCustomTemplatePath() {
return Path.Combine(Application.dataPath, kTemplatePath);
}
private void FillTemplates(List<string> templates) {
var assets = AssetDatabase.FindAssets("t:TextAsset");
foreach (var asset in assets) {
var path = AssetDatabase.GUIDToAssetPath(asset);
var locs = Path.GetDirectoryName(path).Split('/');
if (locs.Length > 0) {
var loc = locs[locs.Length - 1];
if (loc.ToLower() == "smartscripttemplates") {
templates.Add(path);
}
}
}
}
public string GetTemplateText(string nameWithoutExtension) {
var assets = AssetDatabase.FindAssets("t:TextAsset");
foreach (var asset in assets) {
var path = AssetDatabase.GUIDToAssetPath(asset);
if (Path.GetFileNameWithoutExtension(path) == nameWithoutExtension + "." + extension) {
var locs = Path.GetDirectoryName(path).Split('/');
if (locs.Length > 0) {
var loc = locs[locs.Length - 1];
if (loc.ToLower() == "smartscripttemplates") {
return File.ReadAllText(path);
}
}
}
}
return string.Empty;
}
public string GetFunctionsPath(string baseClassName) {
var assets = AssetDatabase.FindAssets("t:TextAsset");
foreach (var asset in assets) {
var path = AssetDatabase.GUIDToAssetPath(asset);
if (Path.GetFileNameWithoutExtension(path) == baseClassName + ".functions") {
var locs = Path.GetDirectoryName(path).Split('/');
if (locs.Length > 0) {
var loc = locs[locs.Length - 1];
if (loc.ToLower() == "smartscripttemplates") {
return path;
}
}
}
}
return string.Empty;
}
private void UpdateTemplateNamesAndTemplate() {
// Remember old selected template name
string oldSelectedTemplateName = null;
if (m_TemplateNames != null && m_TemplateNames.Length > 0) oldSelectedTemplateName = m_TemplateNames[m_TemplateIndex];
// Get new template names
m_TemplateNames = GetTemplateNames();
// Select template
if (m_TemplateNames.Length == 0) {
m_ScriptPrescription.m_Template = kNoTemplateString;
m_BaseClass = null;
} else {
if (oldSelectedTemplateName != null && m_TemplateNames.Contains(oldSelectedTemplateName)) m_TemplateIndex = m_TemplateNames.ToList().IndexOf(oldSelectedTemplateName);
else m_TemplateIndex = 0;
m_ScriptPrescription.m_Template = GetTemplate(m_TemplateNames[m_TemplateIndex]);
}
HandleBaseClass();
}
private void AutomaticHandlingOnChangeTemplate() {
// Add or remove "Editor" from directory path
if (m_IsEditorClass) {
if (InvalidTargetPathForEditorScript()) m_Directory = Path.Combine(m_Directory, "Editor");
} else if (m_Directory.EndsWith("Editor")) {
m_Directory = m_Directory.Substring(0, m_Directory.Length - 6).TrimEnd(kPathSepChars);
}
// Move keyboard focus to relevant field
if (m_IsCustomEditor) m_FocusTextFieldNow = true;
}
private string GetBaseClass(string templateContent) {
string firstLine = templateContent.Substring(0, templateContent.IndexOf("\n"));
if (firstLine.Contains("BASECLASS")) {
string baseClass = firstLine.Substring(10).Trim();
if (baseClass != string.Empty) return baseClass;
}
return null;
}
private bool GetFunctionIsIncluded(string baseClassName, string functionName, bool includeByDefault) {
string prefName = "FunctionData_" + (baseClassName != null ? baseClassName + "_" : string.Empty) + functionName;
return EditorPrefs.GetBool(prefName, includeByDefault);
}
private void SetFunctionIsIncluded(string baseClassName, string functionName, bool include) {
string prefName = "FunctionData_" + (baseClassName != null ? baseClassName + "_" : string.Empty) + functionName;
EditorPrefs.SetBool(prefName, include);
}
private void HandleBaseClass() {
if (m_TemplateNames.Length == 0) {
m_BaseClass = null;
return;
}
// Get base class
m_BaseClass = GetBaseClass(m_ScriptPrescription.m_Template);
// If base class was found, strip first line from template
if (m_BaseClass != null) m_ScriptPrescription.m_Template =
m_ScriptPrescription.m_Template.Substring(m_ScriptPrescription.m_Template.IndexOf("\n") + 1);
m_IsEditorClass = IsEditorClass(m_BaseClass);
m_IsCustomEditor = (m_BaseClass == kCustomEditorClassName);
m_ScriptPrescription.m_StringReplacements.Clear();
// Try to find function file first in custom templates folder and then in built-in
//string functionDataFilePath = Path.Combine(GetAbsoluteCustomTemplatePath(), m_BaseClass + ".functions.txt");
//if (!File.Exists(functionDataFilePath)) functionDataFilePath = Path.Combine(GetAbsoluteBuiltinTemplatePath(), m_BaseClass + ".functions.txt");
var functionDataFilePath = GetFunctionsPath(m_BaseClass);
if (!File.Exists(functionDataFilePath)) {
m_ScriptPrescription.m_Functions = null;
} else {
StreamReader reader = new StreamReader(functionDataFilePath);
List<FunctionData> functionList = new List<FunctionData>();
int lineNr = 1;
while (!reader.EndOfStream) {
string functionLine = reader.ReadLine();
string functionLineWhole = functionLine;
try {
if (functionLine.Substring(0, 7).ToLower() == "header ") {
functionList.Add(new FunctionData(functionLine.Substring(7)));
continue;
}
FunctionData function = new FunctionData();
bool defaultInclude = false;
if (functionLine.Substring(0, 8) == "DEFAULT ") {
defaultInclude = true;
functionLine = functionLine.Substring(8);
}
if (functionLine.Substring(0, 9) == "override ") {
function.isVirtual = true;
functionLine = functionLine.Substring(9);
}
string returnTypeString = GetStringUntilSeperator(ref functionLine, " ");
function.returnType = (returnTypeString == "void" ? null : returnTypeString);
function.name = GetStringUntilSeperator(ref functionLine, "(");
string parameterString = GetStringUntilSeperator(ref functionLine, ")");
if (function.returnType != null) function.returnDefault = GetStringUntilSeperator(ref functionLine, ";");
function.comment = functionLine;
string[] parameterStrings = parameterString.Split(new char[]{ ',' }, StringSplitOptions.RemoveEmptyEntries);
List<ParameterData> parameterList = new List<ParameterData>();
for (int i = 0; i < parameterStrings.Length; i++) {
string[] paramSplit = parameterStrings[i].Trim().Split(' ');
parameterList.Add(new ParameterData(paramSplit[1], paramSplit[0]));
}
function.parameters = parameterList.ToArray();
function.include = GetFunctionIsIncluded(m_BaseClass, function.name, defaultInclude);
functionList.Add(function);
} catch (Exception e) {
Debug.LogWarning("Malformed function line: \"" + functionLineWhole + "\"\n at " + functionDataFilePath + ":" + lineNr + "\n" + e);
}
lineNr++;
}
m_ScriptPrescription.m_Functions = functionList.ToArray();
}
}
private string GetStringUntilSeperator(ref string source, string sep) {
int index = source.IndexOf(sep);
string result = source.Substring(0, index).Trim();
source = source.Substring(index + sep.Length).Trim(' ');
return result;
}
private string GetTemplate(string nameWithoutExtension) {
/*string path = Path.Combine(GetAbsoluteCustomTemplatePath(), nameWithoutExtension + "." + extension + ".txt");
if (File.Exists(path)) return File.ReadAllText(path);
path = Path.Combine(GetAbsoluteBuiltinTemplatePath(), nameWithoutExtension + "." + extension + ".txt");
if (File.Exists(path)) return File.ReadAllText(path);
*/
var txt = GetTemplateText(nameWithoutExtension);
if (string.IsNullOrEmpty(txt) == false) {
return txt;
}
return kNoTemplateString;
}
private string GetTemplateName() {
if (m_TemplateNames.Length == 0) return kNoTemplateString;
return m_TemplateNames[m_TemplateIndex];
}
// Custom comparer to sort templates alphabetically,
// but put MonoBehaviour and Plain Class as the first two
private class TemplateNameComparer : IComparer<string> {
private int GetRank(string s) {
if (s == kMonoBehaviourName) return 0;
if (s == kPlainClassName) return 1;
if (s.StartsWith(kTempEditorClassPrefix)) return 100;
return 2;
}
public int Compare(string x, string y) {
int rankX = GetRank(x);
int rankY = GetRank(y);
if (rankX == rankY) return x.CompareTo(y);
else return rankX.CompareTo(rankY);
}
}
private string[] GetTemplateNames() {
List<string> templates = new List<string>();
// Get all file names of custom templates
//if (Directory.Exists(GetAbsoluteCustomTemplatePath())) templates.AddRange(Directory.GetFiles(GetAbsoluteCustomTemplatePath()));
// Get all file names of built-in templates
//if (Directory.Exists(GetAbsoluteBuiltinTemplatePath())) templates.AddRange(Directory.GetFiles(GetAbsoluteBuiltinTemplatePath()));
FillTemplates(templates);
if (templates.Count == 0) return new string[0];
// Filter and clean up list
templates = templates
.Distinct()
.Where(f => (f.EndsWith("." + extension + ".txt")))
.Select(f => Path.GetFileNameWithoutExtension(f.Substring(0, f.Length - 4)))
.ToList();
// Determine which scripts have editor class base class
for (int i = 0; i < templates.Count; i++) {
string templateContent = GetTemplate(templates[i]);
if (IsEditorClass(GetBaseClass(templateContent))) templates[i] = kTempEditorClassPrefix + templates[i];
}
// Order list
templates = templates
.OrderBy(f => f, new TemplateNameComparer())
.ToList();
// Insert separator before first editor script template
bool inserted = false;
for (int i = 0; i < templates.Count; i++) {
if (templates[i].StartsWith(kTempEditorClassPrefix)) {
templates[i] = templates[i].Substring(kTempEditorClassPrefix.Length);
if (!inserted) {
templates.Insert(i, string.Empty);
inserted = true;
}
}
}
// Return list
return templates.ToArray();
}
private string extension {
get {
switch (m_ScriptPrescription.m_Lang) {
case Language.CSharp:
return "cs";
/*case Language.JavaScript:
return "js";
case Language.Boo:
return "boo";*/
default:
throw new ArgumentOutOfRangeException();
}
}
}
[MenuItem("Component/Scripts/New Script...", false, 0)]
private static void OpenFromComponentMenu() {
Init();
}
[MenuItem("Component/Scripts/New Script...", true, 0)]
private static bool OpenFromComponentMenuValidation() {
return (Selection.activeObject is GameObject);
}
[MenuItem("Assets/Create/Script...", false, 100)]
private static void OpenFromAssetsMenu() {
Init();
}
private static void Init() {
GetWindow<NewScriptWindow>(true, "Create Script");
}
public NewScriptWindow() {
// Large initial size
position = new Rect(50, 50, 770, 500);
// But allow to scale down to smaller size
minSize = new Vector2(550, 400);
m_ScriptPrescription = new ScriptPrescription();
}
private void OnEnable() {
//m_ScriptPrescription.m_Lang = (Language)EditorPrefs.GetInt (kLanguageEditorPrefName, 0);
UpdateTemplateNamesAndTemplate();
OnSelectionChange();
}
private void OnGUI() {
if (m_Styles == null) m_Styles = new Styles();
EditorGUIUtility.LookLikeControls(85, 0f);
if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Return && CanCreate()) Create();
EditorGUILayout.BeginHorizontal();
{
GUILayout.Space(10);
PreviewGUI();
GUILayout.Space(10);
EditorGUILayout.BeginVertical();
{
OptionsGUI();
GUILayout.Space(10);
//GUILayout.FlexibleSpace ();
CreateAndCancelButtonsGUI();
}
EditorGUILayout.EndVertical();
GUILayout.Space(10);
}
EditorGUILayout.EndHorizontal();
GUILayout.Space(10);
// Clear keyboard focus if clicking a random place inside the dialog,
// or if ClearKeyboardControl flag is set.
if (m_ClearKeyboardControl || (Event.current.type == EventType.MouseDown && Event.current.button == 0)) {
GUIUtility.keyboardControl = 0;
m_ClearKeyboardControl = false;
Repaint();
}
}
private bool CanCreate() {
return m_ScriptPrescription.m_ClassName.Length > 0 &&
!File.Exists(TargetPath()) &&
!ClassAlreadyExists() &&
!ClassNameIsInvalid() &&
!TargetClassDoesNotExist() &&
!TargetClassIsNotValidType() &&
!InvalidTargetPath() &&
!InvalidTargetPathForEditorScript();
}
private void Create() {
CreateScript();
if (CanAddComponent()) InternalEditorUtility.AddScriptComponentUnchecked(m_GameObjectToAddTo,
AssetDatabase.LoadAssetAtPath(TargetPath(), typeof(MonoScript)) as MonoScript);
Close();
GUIUtility.ExitGUI();
}
private void CreateAndCancelButtonsGUI() {
bool canCreate = CanCreate();
// Create string to tell the user what the problem is
string blockReason = string.Empty;
if (!canCreate && m_ScriptPrescription.m_ClassName != string.Empty) {
if (File.Exists(TargetPath())) blockReason = "A script called \"" + m_ScriptPrescription.m_ClassName + "\" already exists at that path.";
else if (ClassAlreadyExists()) blockReason = "A class called \"" + m_ScriptPrescription.m_ClassName + "\" already exists.";
else if (ClassNameIsInvalid()) blockReason = "The script name may only consist of a-z, A-Z, 0-9, _.";
else if (TargetClassDoesNotExist()) if (m_CustomEditorTargetClassName == string.Empty) blockReason = "Fill in the script component to make an editor for.";
else blockReason = "A class called \"" + m_CustomEditorTargetClassName + "\" could not be found.";
else if (TargetClassIsNotValidType()) blockReason = "The class \"" + m_CustomEditorTargetClassName + "\" is not of type UnityEngine.Object.";
else if (InvalidTargetPath()) blockReason = "The folder path contains invalid characters.";
else if (InvalidTargetPathForEditorScript()) blockReason = "Editor scripts should be stored in a folder called Editor.";
}
// Warning about why the script can't be created
if (blockReason != string.Empty) {
m_Styles.m_WarningContent.text = blockReason;
GUILayout.BeginHorizontal(m_Styles.m_HelpBox);
{
GUILayout.Label(m_Styles.m_WarningContent, EditorStyles.wordWrappedMiniLabel);
}
GUILayout.EndHorizontal();
}
// Cancel and create buttons
GUILayout.BeginHorizontal();
{
GUILayout.FlexibleSpace();
if (GUILayout.Button("Cancel", GUILayout.Width(kButtonWidth))) {
Close();
GUIUtility.ExitGUI();
}
bool guiEnabledTemp = GUI.enabled;
GUI.enabled = canCreate;
if (GUILayout.Button(GetCreateButtonText(), GUILayout.Width(kButtonWidth))) {
Create();
}
GUI.enabled = guiEnabledTemp;
}
GUILayout.EndHorizontal();
}
private bool CanAddComponent() {
return (m_GameObjectToAddTo != null && m_BaseClass == kMonoBehaviourName);
}
private void OptionsGUI() {
EditorGUILayout.BeginVertical(GUILayout.ExpandWidth(true));
{
GUILayout.BeginHorizontal();
{
NameGUI();
LanguageGUI();
}
GUILayout.EndHorizontal();
GUILayout.Space(10);
TargetPathGUI();
GUILayout.Space(20);
TemplateSelectionGUI();
if (GetTemplateName() == kMonoBehaviourName) {
GUILayout.Space(10);
AttachToGUI();
}
if (m_IsCustomEditor) {
GUILayout.Space(10);
CustomEditorTargetClassNameGUI();
}
GUILayout.Space(10);
FunctionsGUI();
}
EditorGUILayout.EndVertical();
}
private bool FunctionHeader(string header, bool expandedByDefault) {
GUILayout.Space(5);
bool expanded = GetFunctionIsIncluded(m_BaseClass, header, expandedByDefault);
bool expandedNew = GUILayout.Toggle(expanded, header, EditorStyles.foldout);
if (expandedNew != expanded) SetFunctionIsIncluded(m_BaseClass, header, expandedNew);
return expandedNew;
}
private void FunctionsGUI() {
if (m_ScriptPrescription.m_Functions == null) {
GUILayout.FlexibleSpace();
return;
}
EditorGUILayout.BeginHorizontal();
{
GUILayout.Label("Functions", GUILayout.Width(kLabelWidth - 4));
EditorGUILayout.BeginVertical(m_Styles.m_LoweredBox);
m_OptionsScroll = EditorGUILayout.BeginScrollView(m_OptionsScroll);
{
bool expanded = FunctionHeader("General", true);
for (int i = 0; i < m_ScriptPrescription.m_Functions.Length; i++) {
FunctionData func = m_ScriptPrescription.m_Functions[i];
if (func.name == null) {
expanded = FunctionHeader(func.comment, false);
} else if (expanded) {
Rect toggleRect = GUILayoutUtility.GetRect(GUIContent.none, EditorStyles.toggle);
toggleRect.x += 15;
toggleRect.width -= 15;
bool include = GUI.Toggle(toggleRect, func.include, new GUIContent(func.name, func.comment));
if (include != func.include) {
m_ScriptPrescription.m_Functions[i].include = include;
SetFunctionIsIncluded(m_BaseClass, func.name, include);
}
}
}
}
EditorGUILayout.EndScrollView();
EditorGUILayout.EndVertical();
}
EditorGUILayout.EndHorizontal();
}
private void AttachToGUI() {
GUILayout.BeginHorizontal();
{
m_GameObjectToAddTo = EditorGUILayout.ObjectField("Attach to", m_GameObjectToAddTo, typeof(GameObject), true) as GameObject;
if (ClearButton()) m_GameObjectToAddTo = null;
}
GUILayout.EndHorizontal();
HelpField("Click a GameObject or Prefab to select.");
}
private void SetClassNameBasedOnTargetClassName() {
if (m_CustomEditorTargetClassName == string.Empty) m_ScriptPrescription.m_ClassName = string.Empty;
else m_ScriptPrescription.m_ClassName = m_CustomEditorTargetClassName + "Editor";
}
private void CustomEditorTargetClassNameGUI() {
GUI.SetNextControlName("CustomEditorTargetClassNameField");
string newName = EditorGUILayout.TextField("Editor for", m_CustomEditorTargetClassName);
m_ScriptPrescription.m_StringReplacements["$TargetClassName"] = newName;
if (newName != m_CustomEditorTargetClassName) {
m_CustomEditorTargetClassName = newName;
SetClassNameBasedOnTargetClassName();
}
if (m_FocusTextFieldNow && Event.current.type == EventType.repaint) {
GUI.FocusControl("CustomEditorTargetClassNameField");
m_FocusTextFieldNow = false;
Repaint();
}
HelpField("Script component to make an editor for.");
}
private void TargetPathGUI() {
var changedDir = false;
GUI.enabled = false;
var m_Directory = EditorGUILayout.TextField("Save in", this.m_Directory, GUILayout.ExpandWidth(true));
if (m_Directory != this.m_Directory) {
changedDir = true;
}
GUI.enabled = true;
HelpField("Click a folder in the Project view to select.");
EditorGUILayout.Space();
m_ScriptPrescription.m_NameSpace = EditorGUILayout.TextField("Namespace", m_ScriptPrescription.m_NameSpace, GUILayout.ExpandWidth(true));
var targetNamespace = m_ScriptPrescription.m_NameSpace;
if (string.IsNullOrEmpty(m_ScriptPrescription.m_NameSpace) == true || changedDir == true) {
var project = UnityEditor.UI.Windows.Plugins.Flow.Flow.FindProjectForPath("Assets", m_Directory);
if (project != null) {
var dir = Path.GetDirectoryName(AssetDatabase.GetAssetPath(project)).Replace("Assets/", string.Empty).Replace("Assets\\", string.Empty);
targetNamespace = m_Directory
.Replace(dir + "/", string.Empty)
.Replace(dir + "\\", string.Empty)
.Replace("/", ".")
.Replace("\\", ".");
} else {
targetNamespace = "Namespace";
}
}
m_ScriptPrescription.m_StringReplacements["$Namespace"] = targetNamespace;
m_ScriptPrescription.m_NameSpace = targetNamespace;
}
private bool ClearButton() {
return GUILayout.Button("Clear", EditorStyles.miniButton, GUILayout.Width(40));
}
private void TemplateSelectionGUI() {
m_TemplateIndex = Mathf.Clamp(m_TemplateIndex, 0, m_TemplateNames.Length - 1);
var names = (string[])m_TemplateNames.Clone();
for (int i = 0; i < names.Length; ++i) names[i] = names[i].Replace(" ", "/");
int templateIndexNew = EditorGUILayout.Popup("Template", m_TemplateIndex, names);
if (templateIndexNew != m_TemplateIndex) {
m_TemplateIndex = templateIndexNew;
UpdateTemplateNamesAndTemplate();
AutomaticHandlingOnChangeTemplate();
}
}
private void NameGUI() {
GUI.SetNextControlName("ScriptNameField");
m_ScriptPrescription.m_ClassName = EditorGUILayout.TextField("Name", m_ScriptPrescription.m_ClassName);
if (m_FocusTextFieldNow && !m_IsCustomEditor && Event.current.type == EventType.repaint) {
GUI.FocusControl("ScriptNameField");
m_FocusTextFieldNow = false;
}
}
private void LanguageGUI() {
var langNew = (Language)EditorGUILayout.EnumPopup(m_ScriptPrescription.m_Lang, GUILayout.Width(80));
if (langNew != m_ScriptPrescription.m_Lang) {
m_ScriptPrescription.m_Lang = langNew;
EditorPrefs.SetInt(kLanguageEditorPrefName, (int)langNew);
UpdateTemplateNamesAndTemplate();
AutomaticHandlingOnChangeTemplate();
}
}
private void PreviewGUI() {
EditorGUILayout.BeginVertical(GUILayout.Width(Mathf.Max(position.width * 0.4f, position.width - 380f)));
{
// Reserve room for preview title
Rect previewHeaderRect = GUILayoutUtility.GetRect(new GUIContent("Preview"), m_Styles.m_PreviewTitle);
// Secret! Toggle curly braces on new line when double clicking the script preview title
Event evt = Event.current;
if (evt.type == EventType.MouseDown && evt.clickCount == 2 && previewHeaderRect.Contains(evt.mousePosition)) {
EditorPrefs.SetBool("CurlyBracesOnNewLine", !EditorPrefs.GetBool("CurlyBracesOnNewLine"));
Repaint();
}
// Preview scroll view
m_PreviewScroll = EditorGUILayout.BeginScrollView(m_PreviewScroll, m_Styles.m_PreviewBox);
{
EditorGUILayout.BeginHorizontal();
{
// Tiny space since style has no padding in right side
GUILayout.Space(5);
// Preview text itself
string previewStr = new NewScriptGenerator(m_ScriptPrescription).ToString();
Rect r = GUILayoutUtility.GetRect(
new GUIContent(previewStr),
EditorStyles.miniLabel,
GUILayout.ExpandWidth(true),
GUILayout.ExpandHeight(true));
EditorGUI.SelectableLabel(r, previewStr, EditorStyles.miniLabel);
}
EditorGUILayout.EndHorizontal();
}
EditorGUILayout.EndScrollView();
// Draw preview title after box itself because otherwise the top row
// of pixels of the slider will overlap with the title
GUI.Label(previewHeaderRect, new GUIContent("Preview"), m_Styles.m_PreviewTitle);
GUILayout.Space(4);
}
EditorGUILayout.EndVertical();
}
private bool InvalidTargetPath() {
if (m_Directory.IndexOfAny(kInvalidPathChars) >= 0) return true;
if (TargetDir().Split(kPathSepChars, StringSplitOptions.None).Contains(string.Empty)) return true;
return false;
}
private bool InvalidTargetPathForEditorScript() {
return m_IsEditorClass && !m_Directory.ToLower().Split(kPathSepChars).Contains("editor");
}
private bool IsFolder(Object obj) {
return Directory.Exists(AssetDatabase.GetAssetPath(obj));
}
private void HelpField(string helpText) {
GUILayout.BeginHorizontal();
GUILayout.Label(string.Empty, GUILayout.Width(kLabelWidth - 4));
GUILayout.Label(helpText, m_Styles.m_HelpBox);
GUILayout.EndHorizontal();
}
private string TargetPath() {
return Path.Combine(TargetDir(), m_ScriptPrescription.m_ClassName + "." + extension);
}
private string TargetDir() {
return Path.Combine("Assets", m_Directory.Trim(kPathSepChars));
}
private bool ClassNameIsInvalid() {
return !System.CodeDom.Compiler.CodeGenerator.IsValidLanguageIndependentIdentifier(
m_ScriptPrescription.m_ClassName);
}
private bool ClassExists(string className) {
return AppDomain.CurrentDomain.GetAssemblies()
.Any(a => a.GetType(className, false) != null);
}
private bool ClassAlreadyExists() {
if (m_ScriptPrescription.m_ClassName == string.Empty) return false;
return ClassExists(m_ScriptPrescription.m_ClassName);
}
private bool TargetClassDoesNotExist() {
if (!m_IsCustomEditor) return false;
if (m_CustomEditorTargetClassName == string.Empty) return true;
return !ClassExists(m_CustomEditorTargetClassName);
}
private bool TargetClassIsNotValidType() {
if (!m_IsCustomEditor) return false;
if (m_CustomEditorTargetClassName == string.Empty) return true;
return AppDomain.CurrentDomain.GetAssemblies()
.All(a => !typeof(UnityEngine.Object).IsAssignableFrom(a.GetType(m_CustomEditorTargetClassName, false)));
}
private string GetCreateButtonText() {
return CanAddComponent() ? "Create and Attach" : "Create";
}
private void CreateScript() {
if (!Directory.Exists(TargetDir())) Directory.CreateDirectory(TargetDir());
var writer = new StreamWriter(TargetPath());
writer.Write(new NewScriptGenerator(m_ScriptPrescription).ToString());
writer.Close();
writer.Dispose();
AssetDatabase.Refresh();
}
private void OnSelectionChange() {
m_ClearKeyboardControl = true;
if (Selection.activeObject == null) return;
if (IsFolder(Selection.activeObject)) {
m_Directory = AssetPathWithoutAssetPrefix(Selection.activeObject);
if (m_IsEditorClass && InvalidTargetPathForEditorScript()) {
m_Directory = Path.Combine(m_Directory, "Editor");
}
} else if (Selection.activeGameObject != null) {
m_GameObjectToAddTo = Selection.activeGameObject;
} else if (m_IsCustomEditor && Selection.activeObject is MonoScript) {
m_CustomEditorTargetClassName = Selection.activeObject.name;
SetClassNameBasedOnTargetClassName();
}
Repaint();
}
private string AssetPathWithoutAssetPrefix(Object obj) {
return AssetDatabase.GetAssetPath(obj).Substring(7);
}
private bool IsEditorClass(string className) {
if (className == null) return false;
return GetAllClasses("UnityEditor").Contains(className);
}
/// Method to populate a list with all the class in the namespace provided by the user
static List<string> GetAllClasses(string nameSpace) {
// Get the UnityEditor assembly
Assembly asm = Assembly.GetAssembly(typeof(Editor));
// Create a list for the namespaces
List<string> namespaceList = new List<string>();
// Create a list that will hold all the classes the suplied namespace is executing
List<string> returnList = new List<string>();
foreach (Type type in asm.GetTypes ()) {
if (type.Namespace == nameSpace) namespaceList.Add(type.Name);
}
// Now loop through all the classes returned above and add them to our classesName list
foreach (String className in namespaceList) returnList.Add(className);
return returnList;
}
}
}
| |
// Copyright (c) 2013 SIL International
// This software is licensed under the MIT License (http://opensource.org/licenses/MIT)
#if !__MonoCS__
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using SIL.Keyboarding;
namespace SIL.Windows.Forms.Keyboarding.Windows
{
/// <summary>
/// Class for handling Windows system keyboards
/// </summary>
internal class WinKeyboardAdaptor : IKeyboardRetrievingAdaptor, IKeyboardSwitchingAdaptor
{
internal class LayoutName
{
public LayoutName()
{
Name = string.Empty;
LocalizedName = string.Empty;
}
public LayoutName(string layout): this(layout, layout)
{
}
public LayoutName(string layout, string localizedLayout)
{
Name = layout;
LocalizedName = localizedLayout;
}
public string Name;
public string LocalizedName;
}
/// <summary>
/// This class receives notifications from TSF when the input method changes.
/// It also implements a fallback to Windows messages if TSF isn't available,
/// e.g. on Windows XP.
/// </summary>
private class TfLanguageProfileNotifySink : ITfLanguageProfileNotifySink
{
private readonly WinKeyboardAdaptor _keyboardAdaptor;
private readonly List<Form> _toplevelForms = new List<Form>();
public TfLanguageProfileNotifySink(WinKeyboardAdaptor keyboardAdaptor)
{
_keyboardAdaptor = keyboardAdaptor;
}
#region ITfLanguageProfileNotifySink Members
public bool OnLanguageChange(ushort langid)
{
// In my tests we never hit this method (Windows 8.1). I don't know if the
// method signature is wrong or why that is.
// Return true to allow the language profile change
return true;
}
public void OnLanguageChanged()
{
IKeyboardDefinition winKeyboard = _keyboardAdaptor.ActiveKeyboard;
Debug.WriteLine("Language changed from {0} to {1}",
Keyboard.Controller.ActiveKeyboard != null ? Keyboard.Controller.ActiveKeyboard.Layout : "<null>",
winKeyboard != null ? winKeyboard.Layout : "<null>");
_keyboardAdaptor._windowsLanguageProfileSinks.ForEach(
sink => sink.OnInputLanguageChanged(Keyboard.Controller.ActiveKeyboard, winKeyboard));
}
#endregion
#region Fallback if TSF isn't available
// The WinKeyboardAdaptor will subscribe to the Form's InputLanguageChanged event
// only if TSF is not available. Otherwise this code won't be executed.
private void OnWindowsMessageInputLanguageChanged(object sender,
InputLanguageChangedEventArgs inputLanguageChangedEventArgs)
{
Debug.Assert(_keyboardAdaptor._profileNotifySinkCookie == 0);
KeyboardDescription winKeyboard = _keyboardAdaptor.GetKeyboardForInputLanguage(
inputLanguageChangedEventArgs.InputLanguage.Interface());
_keyboardAdaptor._windowsLanguageProfileSinks.ForEach(
sink => sink.OnInputLanguageChanged(Keyboard.Controller.ActiveKeyboard, winKeyboard));
}
public void RegisterWindowsMessageHandler(Control control)
{
Debug.Assert(_keyboardAdaptor._profileNotifySinkCookie == 0);
var topForm = control.FindForm();
if (topForm == null || _toplevelForms.Contains(topForm))
return;
_toplevelForms.Add(topForm);
topForm.InputLanguageChanged += OnWindowsMessageInputLanguageChanged;
}
public void UnregisterWindowsMessageHandler(Control control)
{
var topForm = control.FindForm();
if (topForm == null || !_toplevelForms.Contains(topForm))
return;
topForm.InputLanguageChanged -= OnWindowsMessageInputLanguageChanged;
_toplevelForms.Remove(topForm);
}
#endregion
}
private Timer _timer;
private WinKeyboardDescription _expectedKeyboard;
private bool _fSwitchedLanguages;
/// <summary>Used to prevent re-entrancy. <c>true</c> while we're in the middle of switching keyboards.</summary>
private bool _fSwitchingKeyboards;
private ushort _profileNotifySinkCookie;
private readonly TfLanguageProfileNotifySink _tfLanguageProfileNotifySink;
private readonly List<IWindowsLanguageProfileSink> _windowsLanguageProfileSinks = new List<IWindowsLanguageProfileSink>();
internal ITfInputProcessorProfiles ProcessorProfiles { get; private set; }
internal ITfInputProcessorProfileMgr ProfileMgr { get; private set; }
internal ITfSource TfSource { get; private set; }
public WinKeyboardAdaptor()
{
try
{
ProcessorProfiles = new TfInputProcessorProfilesClass();
}
catch (InvalidCastException)
{
ProcessorProfiles = null;
return;
}
// ProfileMgr will be null on Windows XP - the interface got introduced in Vista
ProfileMgr = ProcessorProfiles as ITfInputProcessorProfileMgr;
_tfLanguageProfileNotifySink = new TfLanguageProfileNotifySink(this);
TfSource = ProcessorProfiles as ITfSource;
if (TfSource != null)
{
_profileNotifySinkCookie = TfSource.AdviseSink(Guids.ITfLanguageProfileNotifySink,
_tfLanguageProfileNotifySink);
}
if (KeyboardController.Instance != null)
{
KeyboardController.Instance.ControlAdded += OnControlRegistered;
KeyboardController.Instance.ControlRemoving += OnControlRemoving;
}
}
private void OnControlRegistered(object sender, RegisterEventArgs e)
{
var windowsLanguageProfileSink = e.EventHandler as IWindowsLanguageProfileSink;
if (windowsLanguageProfileSink != null && !_windowsLanguageProfileSinks.Contains(windowsLanguageProfileSink))
_windowsLanguageProfileSinks.Add(windowsLanguageProfileSink);
if (_profileNotifySinkCookie != 0)
return;
// TSF disabled, so we have to fall back to Windows messages
_tfLanguageProfileNotifySink.RegisterWindowsMessageHandler(e.Control);
}
private void OnControlRemoving(object sender, ControlEventArgs e)
{
if (_profileNotifySinkCookie != 0)
return;
// TSF disabled, so we have to fall back to Windows messages
_tfLanguageProfileNotifySink.UnregisterWindowsMessageHandler(e.Control);
}
protected short[] Languages
{
get
{
if (ProcessorProfiles == null)
return new short[0];
var ptr = IntPtr.Zero;
try
{
var count = ProcessorProfiles.GetLanguageList(out ptr);
if (count <= 0)
return new short[0];
var langIds = new short[count];
Marshal.Copy(ptr, langIds, 0, count);
return langIds;
}
catch (InvalidCastException)
{
// For strange reasons tests on TeamCity failed with InvalidCastException: Unable
// to cast COM object of type TfInputProcessorProfilesClass to interface type
// ITfInputProcessorProfiles when trying to call GetLanguageList. Don't know why
// it wouldn't fail when we create the object. Since it's theoretically possible
// that this also happens on a users machine we catch the exception here - maybe
// TSF is not enabled?
ProcessorProfiles = null;
return new short[0];
}
finally
{
if (ptr != IntPtr.Zero)
Marshal.FreeCoTaskMem(ptr);
}
}
}
private IEnumerable<Tuple<TfInputProcessorProfile, ushort, IntPtr>> GetInputMethodsThroughTsf()
{
foreach (short langId in Languages)
{
IEnumTfInputProcessorProfiles profilesEnumerator = ProfileMgr.EnumProfiles(langId);
TfInputProcessorProfile profile;
while (profilesEnumerator.Next(1, out profile) == 1)
{
// We only deal with keyboards; skip other input methods
if (profile.CatId != Guids.TfcatTipKeyboard)
continue;
if ((profile.Flags & TfIppFlags.Enabled) == 0)
continue;
yield return Tuple.Create(profile, profile.LangId, profile.Hkl);
}
}
}
private IEnumerable<Tuple<TfInputProcessorProfile, ushort, IntPtr>> GetInputMethodsThroughWinApi()
{
int countKeyboardLayouts = Win32.GetKeyboardLayoutList(0, IntPtr.Zero);
if (countKeyboardLayouts == 0)
yield break;
IntPtr keyboardLayouts = Marshal.AllocCoTaskMem(countKeyboardLayouts * IntPtr.Size);
try
{
Win32.GetKeyboardLayoutList(countKeyboardLayouts, keyboardLayouts);
IntPtr current = keyboardLayouts;
var elemSize = (ulong) IntPtr.Size;
for (int i = 0; i < countKeyboardLayouts; i++)
{
var hkl = (IntPtr) Marshal.ReadInt32(current);
yield return Tuple.Create(new TfInputProcessorProfile(), HklToLangId(hkl), hkl);
current = (IntPtr) ((ulong)current + elemSize);
}
}
finally
{
Marshal.FreeCoTaskMem(keyboardLayouts);
}
}
private static ushort HklToLangId(IntPtr hkl)
{
return (ushort)((uint)hkl & 0xffff);
}
private static string GetId(string layout, string locale)
{
return String.Format("{0}_{1}", locale, layout);
}
private static string GetDisplayName(string layout, string locale)
{
return string.Format("{0} - {1}", layout, locale);
}
private void GetInputMethods()
{
IEnumerable<Tuple<TfInputProcessorProfile, ushort, IntPtr>> imes;
if (ProfileMgr != null)
// Windows >= Vista
imes = GetInputMethodsThroughTsf();
else
// Windows XP
imes = GetInputMethodsThroughWinApi();
var allKeyboards = KeyboardController.Instance.Keyboards;
Dictionary<string, WinKeyboardDescription> curKeyboards = allKeyboards.OfType<WinKeyboardDescription>().ToDictionary(kd => kd.Id);
foreach (Tuple<TfInputProcessorProfile, ushort, IntPtr> ime in imes)
{
TfInputProcessorProfile profile = ime.Item1;
ushort langId = ime.Item2;
IntPtr hkl = ime.Item3;
CultureInfo culture;
string locale;
string cultureName;
try
{
culture = new CultureInfo(langId);
cultureName = culture.DisplayName;
locale = culture.Name;
}
catch (CultureNotFoundException)
{
// This can happen for old versions of Keyman that created a custom culture that is invalid to .Net.
// Also see http://stackoverflow.com/a/24820530/4953232
culture = new CultureInfo("en-US");
cultureName = "[Unknown Language]";
locale = "en-US";
}
try
{
LayoutName layoutName;
if (profile.Hkl == IntPtr.Zero && profile.ProfileType != TfProfileType.Illegal)
{
layoutName = new LayoutName(ProcessorProfiles.GetLanguageProfileDescription(
ref profile.ClsId, profile.LangId, ref profile.GuidProfile));
}
else
{
layoutName = GetLayoutNameEx(hkl);
}
string id = GetId(layoutName.Name, locale);
WinKeyboardDescription existingKeyboard;
if (curKeyboards.TryGetValue(id, out existingKeyboard))
{
if (!existingKeyboard.IsAvailable)
{
existingKeyboard.SetIsAvailable(true);
existingKeyboard.InputProcessorProfile = profile;
existingKeyboard.SetLocalizedName(GetDisplayName(layoutName.LocalizedName, cultureName));
}
curKeyboards.Remove(id);
}
else
{
// Prevent a keyboard with this id from being registered again.
// Potentially, id's are duplicated. e.g. A Keyman keyboard linked to a windows one.
// For now we simply ignore this second registration.
// A future enhancement would be to include knowledge of the driver in the Keyboard definition so
// we could choose the best one to register.
KeyboardDescription keyboard;
if (!allKeyboards.TryGet(id, out keyboard))
{
KeyboardController.Instance.Keyboards.Add(
new WinKeyboardDescription(id, GetDisplayName(layoutName.Name, cultureName),
layoutName.Name, locale, true, new InputLanguageWrapper(culture, hkl, layoutName.Name), this,
GetDisplayName(layoutName.LocalizedName, cultureName), profile));
}
}
}
catch (COMException)
{
// this can happen when the user changes the language associated with a
// Keyman keyboard (LT-16172)
}
}
foreach (WinKeyboardDescription existingKeyboard in curKeyboards.Values)
existingKeyboard.SetIsAvailable(false);
}
internal static LayoutName GetLayoutNameEx(IntPtr handle)
{
// InputLanguage.LayoutName is not to be trusted, especially where there are mutiple
// layouts (input methods) associated with a language. This function also provides
// the additional benefit that it does not matter whether a user switches from using
// InKey in Portable mode to using it in Installed mode (perhaps as the project is
// moved from one computer to another), as this function will identify the correct
// input language regardless, rather than (unhelpfully ) calling an InKey layout in
// portable mode the "US" layout. The layout is identified soley by the high-word of
// the HKL (a.k.a. InputLanguage.Handle). (The low word of the HKL identifies the
// language.)
// This function determines an HKL's LayoutName based on the following order of
// precedence:
// - Look up HKL in HKCU\\Software\\InKey\\SubstituteLayoutNames
// - Look up extended layout in HKLM\\SYSTEM\\CurrentControlSet\\Control\\Keyboard Layouts
// - Look up basic (non-extended) layout in HKLM\\SYSTEM\\CurrentControlSet\\Control\\Keyboard Layouts
// -Scan for ID of extended layout in HKLM\\SYSTEM\\CurrentControlSet\\Control\\Keyboard Layouts
var hkl = string.Format("{0:X8}", (int)handle);
// Get substitute first
var substituteHkl = (string)Registry.GetValue(@"HKEY_CURRENT_USER\Keyboard Layout\Substitutes", hkl, null);
if (!string.IsNullOrEmpty(substituteHkl))
hkl = substituteHkl;
// Check InKey
var substituteLayoutName = (string)Registry.GetValue(@"HKEY_CURRENT_USER\Software\InKey\SubstituteLayoutNames", hkl, null);
if (!string.IsNullOrEmpty(substituteLayoutName))
return new LayoutName(substituteLayoutName);
var layoutName = GetLayoutNameFromKey(string.Concat(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layouts\", hkl));
if (layoutName != null)
return layoutName;
layoutName = GetLayoutNameFromKey(string.Concat(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layouts\0000",
hkl.Substring(0, 4)));
if (layoutName != null)
return layoutName;
using (var regKey = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Keyboard Layouts"))
{
if (regKey == null)
return new LayoutName();
string layoutId = "0" + hkl.Substring(1, 3);
foreach (string subKeyName in regKey.GetSubKeyNames().Reverse())
// Scan in reverse order for efficiency, as the extended layouts are at the end.
{
using (var klid = regKey.OpenSubKey(subKeyName))
{
if (klid == null)
continue;
var layoutIdSk = ((string) klid.GetValue("Layout ID"));
if (layoutIdSk != null &&
layoutIdSk.Equals(layoutId, StringComparison.InvariantCultureIgnoreCase))
{
return GetLayoutNameFromKey(klid.Name);
}
}
}
}
return new LayoutName();
}
private static LayoutName GetLayoutNameFromKey(string key)
{
var layoutText = (string)Registry.GetValue(key, "Layout Text", null);
var displayName = (string)Registry.GetValue(key, "Layout Display Name", null);
if (string.IsNullOrEmpty(layoutText) && string.IsNullOrEmpty(displayName))
return null;
if (string.IsNullOrEmpty(displayName))
return new LayoutName(layoutText);
var bldr = new StringBuilder(100);
Win32.SHLoadIndirectString(displayName, bldr, 100, IntPtr.Zero);
return string.IsNullOrEmpty(layoutText) ? new LayoutName(bldr.ToString()) :
new LayoutName(layoutText, bldr.ToString());
}
/// <summary>
/// Gets the InputLanguage that has the same layout as <paramref name="keyboardDescription"/>.
/// </summary>
internal static InputLanguage GetInputLanguage(WinKeyboardDescription keyboardDescription)
{
InputLanguage sameLayout = null;
InputLanguage sameCulture = null;
foreach (InputLanguage lang in InputLanguage.InstalledInputLanguages)
{
// TODO: write some tests
try
{
if (GetLayoutNameEx(lang.Handle).Name == keyboardDescription.Name)
{
if (keyboardDescription.Locale == lang.Culture.Name)
return lang;
if (sameLayout == null)
sameLayout = lang;
}
else if (keyboardDescription.Locale == lang.Culture.Name && sameCulture == null)
sameCulture = lang;
}
catch (CultureNotFoundException)
{
// we get an exception for non-supported cultures, probably because of a
// badly applied .NET patch.
// http://www.ironspeed.com/Designer/3.2.4/WebHelp/Part_VI/Culture_ID__XXX__is_not_a_supported_culture.htm and others
}
}
return sameLayout ?? sameCulture;
}
/// <summary>
/// Gets the keyboard description for the layout of <paramref name="inputLanguage"/>.
/// </summary>
private static KeyboardDescription GetKeyboardDescription(IInputLanguage inputLanguage)
{
KeyboardDescription sameLayout = KeyboardController.NullKeyboard;
KeyboardDescription sameCulture = KeyboardController.NullKeyboard;
// TODO: write some tests
string requestedLayout = GetLayoutNameEx(inputLanguage.Handle).Name;
foreach (WinKeyboardDescription keyboardDescription in KeyboardController.Instance.AvailableKeyboards.OfType<WinKeyboardDescription>())
{
try
{
if (requestedLayout == keyboardDescription.Layout)
{
if (keyboardDescription.Locale == inputLanguage.Culture.Name)
return keyboardDescription;
if (sameLayout == null)
sameLayout = keyboardDescription;
}
else if (keyboardDescription.Locale == inputLanguage.Culture.Name && sameCulture == null)
sameCulture = keyboardDescription;
}
catch (CultureNotFoundException)
{
// we get an exception for non-supported cultures, probably because of a
// badly applied .NET patch.
// http://www.ironspeed.com/Designer/3.2.4/WebHelp/Part_VI/Culture_ID__XXX__is_not_a_supported_culture.htm and others
}
}
return sameLayout ?? sameCulture;
}
private void OnTimerTick(object sender, EventArgs eventArgs)
{
if (_expectedKeyboard == null || !_fSwitchedLanguages)
return;
// This code gets only called if TSF is not available(e.g. Windows XP)
if (InputLanguage.CurrentInputLanguage.Culture.KeyboardLayoutId == _expectedKeyboard.InputLanguage.Culture.KeyboardLayoutId)
{
_expectedKeyboard = null;
_fSwitchedLanguages = false;
_timer.Enabled = false;
return;
}
SwitchKeyboard(_expectedKeyboard);
}
private bool UseWindowsApiForKeyboardSwitching(WinKeyboardDescription winKeyboard)
{
return ProcessorProfiles == null ||
(ProfileMgr == null && winKeyboard.InputProcessorProfile.Hkl == IntPtr.Zero);
}
private void SwitchKeyboard(WinKeyboardDescription winKeyboard)
{
if (_fSwitchingKeyboards)
return;
_fSwitchingKeyboards = true;
try
{
KeyboardController.Instance.ActiveKeyboard = ActivateKeyboard(winKeyboard);
if (Form.ActiveForm != null)
{
// If we activate a keyboard while a particular Form is active, we want to know about
// input language change calls for that form. The previous -= may help make sure we
// don't get multiple hookups.
Form.ActiveForm.InputLanguageChanged -= ActiveFormOnInputLanguageChanged;
Form.ActiveForm.InputLanguageChanged += ActiveFormOnInputLanguageChanged;
}
// If we have a TIP (TSF Input Processor) we don't have a handle. But we do the
// keyboard switching through TSF so we don't need the workaround below.
if (!UseWindowsApiForKeyboardSwitching(winKeyboard))
return;
_expectedKeyboard = winKeyboard;
// The following lines help to work around a Windows bug (happens at least on
// XP-SP3): When you set the current input language (by any method), if there is more
// than one loaded input language associated with that same culture, Windows may
// initially go along with your request, and even respond to an immediate query of
// the current input language with the answer you expect. However, within a fraction
// of a second, it often takes the initiative to again change the input language to
// the _other_ input language having that same culture. We check that the proper
// input language gets set by enabling a timer so that we can re-set the input
// language if necessary.
_fSwitchedLanguages = true;
// stop timer first so that the 0.5s interval restarts.
_timer.Stop();
_timer.Start();
}
finally
{
_fSwitchingKeyboards = false;
}
}
private WinKeyboardDescription ActivateKeyboard(WinKeyboardDescription winKeyboard)
{
try
{
if (UseWindowsApiForKeyboardSwitching(winKeyboard))
{
// Win XP with regular keyboard, or TSF disabled
Win32.ActivateKeyboardLayout(new HandleRef(this, winKeyboard.InputLanguage.Handle), 0);
return winKeyboard;
}
var profile = winKeyboard.InputProcessorProfile;
if ((profile.Flags & TfIppFlags.Enabled) == 0)
return winKeyboard;
ProcessorProfiles.ChangeCurrentLanguage(profile.LangId);
if (ProfileMgr == null)
{
// Win XP with TIP (TSF Input Processor)
ProcessorProfiles.ActivateLanguageProfile(ref profile.ClsId, profile.LangId,
ref profile.GuidProfile);
}
else
{
// Windows >= Vista with either TIP or regular keyboard
ProfileMgr.ActivateProfile(profile.ProfileType, profile.LangId,
ref profile.ClsId, ref profile.GuidProfile, profile.Hkl,
TfIppMf.DontCareCurrentInputLanguage);
}
}
catch (ArgumentException)
{
// throws exception for non-supported culture, though seems to set it OK.
}
catch (COMException e)
{
var profile = winKeyboard.InputProcessorProfile;
var msg = string.Format("Got COM exception trying to activate IM:" + Environment.NewLine +
"LangId={0}, clsId={1}, hkl={2}, guidProfile={3}, flags={4}, type={5}, catId={6}",
profile.LangId, profile.ClsId, profile.Hkl, profile.GuidProfile, profile.Flags, profile.ProfileType, profile.CatId);
throw new ApplicationException(msg, e);
}
return winKeyboard;
}
/// <summary>
/// Save the state of the conversion and sentence mode for the current IME
/// so that we can restore it later.
/// </summary>
private void SaveImeConversionStatus(WinKeyboardDescription winKeyboard)
{
if (winKeyboard == null)
return;
var windowHandle = new HandleRef(this,
winKeyboard.WindowHandle != IntPtr.Zero ? winKeyboard.WindowHandle : Win32.GetFocus());
var contextPtr = Win32.ImmGetContext(windowHandle);
if (contextPtr == IntPtr.Zero)
return;
var contextHandle = new HandleRef(this, contextPtr);
int conversionMode;
int sentenceMode;
Win32.ImmGetConversionStatus(contextHandle, out conversionMode, out sentenceMode);
winKeyboard.ConversionMode = conversionMode;
winKeyboard.SentenceMode = sentenceMode;
Win32.ImmReleaseContext(windowHandle, contextHandle);
}
/// <summary>
/// Restore the conversion and sentence mode to the states they had last time
/// we activated this keyboard (unless we never activated this keyboard since the app
/// got started, in which case we use sensible default values).
/// </summary>
private void RestoreImeConversionStatus(IKeyboardDefinition keyboard)
{
var winKeyboard = keyboard as WinKeyboardDescription;
if (winKeyboard == null)
return;
// Restore the state of the new keyboard to the previous value. If we don't do
// that e.g. in Chinese IME the input mode will toggle between English and
// Chinese (LT-7487 et al).
var windowPtr = winKeyboard.WindowHandle != IntPtr.Zero ? winKeyboard.WindowHandle : Win32.GetFocus();
var windowHandle = new HandleRef(this, windowPtr);
// NOTE: Windows uses the same context for all windows of the current thread, so it
// doesn't really matter which window handle we pass.
var contextPtr = Win32.ImmGetContext(windowHandle);
if (contextPtr == IntPtr.Zero)
return;
// NOTE: Chinese Pinyin IME allows to switch between Chinese and Western punctuation.
// This can be selected in both Native and Alphanumeric conversion mode. However,
// when setting the value the punctuation setting doesn't get restored in Alphanumeric
// conversion mode, not matter what I try. I guess that is because Chinese punctuation
// doesn't really make sense with Latin characters.
var contextHandle = new HandleRef(this, contextPtr);
Win32.ImmSetConversionStatus(contextHandle, winKeyboard.ConversionMode, winKeyboard.SentenceMode);
Win32.ImmReleaseContext(windowHandle, contextHandle);
winKeyboard.WindowHandle = windowPtr;
}
private void ActiveFormOnInputLanguageChanged(object sender, InputLanguageChangedEventArgs inputLanguageChangedEventArgs)
{
RestoreImeConversionStatus(GetKeyboardDescription(inputLanguageChangedEventArgs.InputLanguage.Interface()));
}
private static bool InputProcessorProfilesEqual(TfInputProcessorProfile profile1, TfInputProcessorProfile profile2)
{
// Don't compare Flags - they can be different and it's still the same profile
return profile1.ProfileType == profile2.ProfileType &&
profile1.LangId == profile2.LangId &&
profile1.ClsId == profile2.ClsId &&
profile1.GuidProfile == profile2.GuidProfile &&
profile1.CatId == profile2.CatId &&
profile1.HklSubstitute == profile2.HklSubstitute &&
profile1.Caps == profile2.Caps &&
profile1.Hkl == profile2.Hkl;
}
#region IKeyboardRetrievingAdaptor Members
/// <summary>
/// The type of keyboards this adaptor handles: system or other (like Keyman, ibus...)
/// </summary>
public KeyboardAdaptorType Type
{
get
{
CheckDisposed();
return KeyboardAdaptorType.System;
}
}
public bool IsApplicable
{
get { return true; }
}
public IKeyboardSwitchingAdaptor SwitchingAdaptor
{
get { return this; }
}
[SuppressMessage("Gendarme.Rules.Correctness", "EnsureLocalDisposalRule",
Justification = "m_Timer gets disposed in Close() which gets called from KeyboardControllerImpl.Dispose")]
public void Initialize()
{
_timer = new Timer { Interval = 500 };
_timer.Tick += OnTimerTick;
GetInputMethods();
// Form.ActiveForm can be null when running unit tests
if (Form.ActiveForm != null)
Form.ActiveForm.InputLanguageChanged += ActiveFormOnInputLanguageChanged;
}
public void UpdateAvailableKeyboards()
{
GetInputMethods();
}
private KeyboardDescription GetKeyboardForInputLanguage(IInputLanguage inputLanguage)
{
return GetKeyboardDescription(inputLanguage);
}
/// <summary>
/// Creates and returns a keyboard definition object based on the ID.
/// Note that this method is used when we do NOT have a matching available keyboard.
/// Therefore we can presume that the created one is NOT available.
/// </summary>
public KeyboardDescription CreateKeyboardDefinition(string id)
{
CheckDisposed();
string[] parts = id.Split('_');
string locale = parts[0];
string layout = parts[1];
IInputLanguage inputLanguage;
string cultureName;
try
{
var ci = new CultureInfo(locale);
cultureName = ci.DisplayName;
inputLanguage = new InputLanguageWrapper(ci, IntPtr.Zero, layout);
}
catch (CultureNotFoundException)
{
// ignore if we can't find a culture (this can happen e.g. when a language gets
// removed that was previously assigned to a WS) - see LT-15333
inputLanguage = null;
cultureName = "[Unknown Language]";
}
return new WinKeyboardDescription(id, GetDisplayName(layout, cultureName), layout, locale, false, inputLanguage, this,
GetDisplayName(layout, cultureName), new TfInputProcessorProfile());
}
public bool CanHandleFormat(KeyboardFormat format)
{
CheckDisposed();
switch (format)
{
case KeyboardFormat.Msklc:
case KeyboardFormat.Unknown:
return true;
}
return false;
}
public string GetKeyboardSetupApplication(out string arguments)
{
arguments = @"input.dll";
return Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.System), @"control.exe");
}
public bool IsSecondaryKeyboardSetupApplication
{
get { return false; }
}
#endregion
#region IKeyboardSwitchingAdaptor Members
public bool ActivateKeyboard(KeyboardDescription keyboard)
{
CheckDisposed();
SwitchKeyboard((WinKeyboardDescription) keyboard);
return true;
}
public void DeactivateKeyboard(KeyboardDescription keyboard)
{
CheckDisposed();
SaveImeConversionStatus((WinKeyboardDescription) keyboard);
}
/// <summary>
/// Gets the default keyboard of the system.
/// </summary>
public KeyboardDescription DefaultKeyboard
{
get
{
CheckDisposed();
return GetKeyboardDescription(InputLanguage.DefaultInputLanguage.Interface());
}
}
/// <summary>
/// Gets the currently active keyboard.
/// </summary>
public KeyboardDescription ActiveKeyboard
{
get
{
if (ProfileMgr != null)
{
var profile = ProfileMgr.GetActiveProfile(Guids.TfcatTipKeyboard);
return Keyboard.Controller.AvailableKeyboards.OfType<WinKeyboardDescription>()
.FirstOrDefault(winKeybd => InputProcessorProfilesEqual(profile, winKeybd.InputProcessorProfile)) ??
KeyboardController.NullKeyboard;
}
// Probably Windows XP where we don't have ProfileMgr
var lang = ProcessorProfiles.GetCurrentLanguage();
return Keyboard.Controller.AvailableKeyboards.OfType<WinKeyboardDescription>()
.FirstOrDefault(winKeybd => winKeybd.InputProcessorProfile.LangId == lang) ??
KeyboardController.NullKeyboard;
}
}
#endregion
#region IDisposable & Co. implementation
// Region last reviewed: never
/// <summary>
/// Check to see if the object has been disposed.
/// All public Properties and Methods should call this
/// before doing anything else.
/// </summary>
public void CheckDisposed()
{
if (IsDisposed)
throw new ObjectDisposedException(String.Format("'{0}' in use after being disposed.", GetType().Name));
}
/// <summary>
/// See if the object has been disposed.
/// </summary>
public bool IsDisposed { get; private set; }
/// <summary>
/// Finalizer, in case client doesn't dispose it.
/// Force Dispose(false) if not already called (i.e. m_isDisposed is true)
/// </summary>
/// <remarks>
/// In case some clients forget to dispose it directly.
/// </remarks>
~WinKeyboardAdaptor()
{
Dispose(false);
// The base class finalizer is called automatically.
}
/// <summary>
///
/// </summary>
/// <remarks>Must not be virtual.</remarks>
public void Dispose()
{
Dispose(true);
// This object will be cleaned up by the Dispose method.
// Therefore, you should call GC.SupressFinalize to
// take this object off the finalization queue
// and prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}
/// <summary>
/// Executes in two distinct scenarios.
///
/// 1. If disposing is true, the method has been called directly
/// or indirectly by a user's code via the Dispose method.
/// Both managed and unmanaged resources can be disposed.
///
/// 2. If disposing is false, the method has been called by the
/// runtime from inside the finalizer and you should not reference (access)
/// other managed objects, as they already have been garbage collected.
/// Only unmanaged resources can be disposed.
/// </summary>
/// <param name="disposing"></param>
/// <remarks>
/// If any exceptions are thrown, that is fine.
/// If the method is being done in a finalizer, it will be ignored.
/// If it is thrown by client code calling Dispose,
/// it needs to be handled by fixing the bug.
///
/// If subclasses override this method, they should call the base implementation.
/// </remarks>
protected virtual void Dispose(bool disposing)
{
Debug.WriteLineIf(!disposing, "****************** " + GetType().Name + " 'disposing' is false. ******************");
// Must not be run more than once.
if (IsDisposed)
return;
if (disposing)
{
// Dispose managed resources here.
if (_timer != null)
{
_timer.Dispose();
_timer = null;
}
if (_profileNotifySinkCookie > 0)
{
if (TfSource != null)
TfSource.UnadviseSink(_profileNotifySinkCookie);
_profileNotifySinkCookie = 0;
}
}
// Dispose unmanaged resources here, whether disposing is true or false.
IsDisposed = true;
}
#endregion IDisposable & Co. implementation
}
}
#endif
| |
// Copyright 2020, Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Google.Apis.Http;
using Google.Apis.Json;
using Google.Apis.Requests;
using Google.Apis.Util;
using Newtonsoft.Json;
namespace FirebaseAdmin.IntegrationTests.Auth
{
internal class AuthIntegrationUtils
{
internal static readonly NewtonsoftJsonSerializer JsonParser =
NewtonsoftJsonSerializer.Instance;
private const string EmailLinkSignInUrl =
"https://www.googleapis.com/identitytoolkit/v3/relyingparty/emailLinkSignin";
private const string ResetPasswordUrl =
"https://www.googleapis.com/identitytoolkit/v3/relyingparty/resetPassword";
private const string VerifyCustomTokenUrl =
"https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyCustomToken";
private const string VerifyPasswordUrl =
"https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword";
internal static async Task<string> SignInWithCustomTokenAsync(
string customToken, string tenantId = null)
{
var rb = new RequestBuilder()
{
Method = HttpConsts.Post,
BaseUri = new Uri(VerifyCustomTokenUrl),
};
rb.AddParameter(RequestParameterType.Query, "key", IntegrationTestUtils.GetApiKey());
var request = rb.CreateRequest();
var payload = JsonParser.Serialize(new SignInRequest
{
CustomToken = customToken,
TenantId = tenantId,
ReturnSecureToken = true,
});
request.Content = new StringContent(payload, Encoding.UTF8, "application/json");
var response = await SendAndDeserialize<SignInResponse>(request);
return response.IdToken;
}
internal static async Task<string> ResetPasswordAsync(ResetPasswordRequest data)
{
var rb = new RequestBuilder()
{
Method = HttpConsts.Post,
BaseUri = new Uri(ResetPasswordUrl),
};
rb.AddParameter(RequestParameterType.Query, "key", IntegrationTestUtils.GetApiKey());
var payload = JsonParser.Serialize(data);
var request = rb.CreateRequest();
request.Content = new StringContent(payload, Encoding.UTF8, "application/json");
var response = await SendAndDeserialize<Dictionary<string, object>>(request);
return (string)response["email"];
}
internal static async Task<string> SignInWithEmailLinkAsync(
string email, string oobCode, string tenantId = null)
{
var rb = new RequestBuilder()
{
Method = HttpConsts.Post,
BaseUri = new Uri(EmailLinkSignInUrl),
};
rb.AddParameter(RequestParameterType.Query, "key", IntegrationTestUtils.GetApiKey());
var data = new Dictionary<string, object>()
{
{ "email", email },
{ "oobCode", oobCode },
};
if (tenantId != null)
{
data["tenantId"] = tenantId;
}
var payload = JsonParser.Serialize(data);
var request = rb.CreateRequest();
request.Content = new StringContent(payload, Encoding.UTF8, "application/json");
var response = await SendAndDeserialize<VerifyPasswordResponse>(request);
return response.IdToken;
}
internal static async Task<string> SignInWithPasswordAsync(
string email, string password, string tenantId = null)
{
var rb = new RequestBuilder()
{
Method = HttpConsts.Post,
BaseUri = new Uri(VerifyPasswordUrl),
};
rb.AddParameter(RequestParameterType.Query, "key", IntegrationTestUtils.GetApiKey());
var request = rb.CreateRequest();
var payload = JsonParser.Serialize(new VerifyPasswordRequest
{
Email = email,
Password = password,
TenantId = tenantId,
ReturnSecureToken = true,
});
request.Content = new StringContent(payload, Encoding.UTF8, "application/json");
var response = await SendAndDeserialize<VerifyPasswordResponse>(request);
return response.IdToken;
}
internal static string GetRandomIdentifier(int length = 10)
{
var random = new Random();
const string chars = "abcdefghijklmnopqrstuvwxyz0123456789";
var suffix = new string(Enumerable.Repeat(chars, length)
.Select(s => s[random.Next(s.Length)]).ToArray());
return $"id-{suffix}";
}
private static async Task<T> SendAndDeserialize<T>(HttpRequestMessage request)
{
using (var client = new HttpClient())
{
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync();
return JsonParser.Deserialize<T>(json);
}
}
internal class SignInRequest
{
[JsonProperty("token")]
public string CustomToken { get; set; }
[JsonProperty("tenantId")]
public string TenantId { get; set; }
[JsonProperty("returnSecureToken")]
public bool ReturnSecureToken { get; set; }
}
internal class SignInResponse
{
[JsonProperty("idToken")]
public string IdToken { get; set; }
}
internal class VerifyPasswordRequest
{
[JsonProperty("email")]
public string Email { get; set; }
[JsonProperty("password")]
public string Password { get; set; }
[JsonProperty("tenantId")]
public string TenantId { get; set; }
[JsonProperty("returnSecureToken")]
public bool ReturnSecureToken { get; set; }
}
internal class VerifyPasswordResponse
{
[JsonProperty("idToken")]
public string IdToken { get; set; }
}
}
internal class ResetPasswordRequest
{
[JsonProperty("email")]
public string Email { get; set; }
[JsonProperty("oldPassword")]
public string OldPassword { get; set; }
[JsonProperty("newPassword")]
public string NewPassword { get; set; }
[JsonProperty("oobCode")]
public string OobCode { get; set; }
[JsonProperty("tenantId")]
public string TenantId { get; set; }
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text.RegularExpressions;
using Palaso.Code;
using Palaso.WritingSystems.Collation;
namespace Palaso.WritingSystems
{
/// <summary>
/// This class stores the information used to define various writing system properties. The Language, Script, Region and Variant
/// properties conform to the subtags of the same name defined in BCP47 (Rfc5646) and are enforced by the Rfc5646Tag class. it is worth
/// noting that for historical reasons this class does not provide seperate fields for variant and private use components as
/// defined in BCP47. Instead the ConcatenateVariantAndPrivateUse and SplitVariantAndPrivateUse methods are provided for consumers
/// to generate a single variant subtag that contains both fields seperated by "-x-".
/// Furthermore the WritingSystemDefinition.WellknownSubtags class provides certain well defined Subtags that carry special meaning
/// apart from the IANA subtag registry. In particular this class defines "qaa" as the default "unlisted language" language subtag.
/// It should be used when there is no match for a language in the IANA subtag registry. Private use properties are "emic" and "etic"
/// which mark phonemic and phonetic writing systems respectively. These must always be used in conjunction with the "fonipa" variant.
/// Likewise "audio" marks a writing system as audio and must always be used in conjunction with script "Zxxx". Convenience methods
/// are provided for Ipa and Audio properties as IpaStatus and IsVoice respectively.
/// </summary>
public class WritingSystemDefinition : IClonableGeneric<WritingSystemDefinition>, IWritingSystemDefinition, ILegacyWritingSystemDefinition
{
public enum SortRulesType
{
/// <summary>
/// Default Unicode ordering rules (actually CustomICU without any rules)
/// </summary>
[Description("Default Ordering")]
DefaultOrdering,
/// <summary>
/// Custom Simple (Shoebox/Toolbox) style rules
/// </summary>
[Description("Custom Simple (Shoebox style) rules")]
CustomSimple,
/// <summary>
/// Custom ICU rules
/// </summary>
[Description("Custom ICU rules")]
CustomICU,
/// <summary>
/// Use the sort rules from another language. When this is set, the SortRules are interpreted as a cultureId for the language to sort like.
/// </summary>
[Description("Same as another language")]
OtherLanguage
}
//This is the version of our writingsystemDefinition implementation and is mostly used for migration purposes.
//This should not be confused with the version of the locale data contained in this writing system.
//That information is stored in the "VersionNumber" property.
public const int LatestWritingSystemDefinitionVersion = 2;
private RFC5646Tag _rfcTag;
private const int kMinimumFontSize=7;
private const int kDefaultSizeIfWeDontKnow = 10;
private string _languageName;
private string _abbreviation;
private bool _isUnicodeEncoded;
private string _versionNumber;
private string _versionDescription;
private DateTime _dateModified;
private string _defaultFontName;
private float _defaultFontSize;
private string _keyboard;
private SortRulesType _sortUsing;
private string _sortRules;
private string _spellCheckingId;
private string _nativeName;
private bool _rightToLeftScript;
private ICollator _collator;
private string _id;
/// <summary>
/// Creates a new WritingSystemDefinition with Language subtag set to "qaa"
/// </summary>
public WritingSystemDefinition()
{
_sortUsing = SortRulesType.DefaultOrdering;
_isUnicodeEncoded = true;
_rfcTag = new RFC5646Tag();
UpdateIdFromRfcTag();
}
/// <summary>
/// Creates a new WritingSystemDefinition by parsing a valid BCP47 tag
/// </summary>
/// <param name="bcp47Tag">A valid BCP47 tag</param>
public WritingSystemDefinition(string bcp47Tag)
: this()
{
_rfcTag = RFC5646Tag.Parse(bcp47Tag);
_abbreviation = _languageName = _nativeName = string.Empty;
UpdateIdFromRfcTag();
}
/// <summary>
/// True when the validity of the writing system defn's tag is being enforced. This is the normal and default state.
/// Setting this true will throw unless the tag has previously been put into a valid state.
/// Attempting to Save the writing system defn will set this true (and may throw).
/// </summary>
public bool RequiresValidTag
{
get { return _rfcTag.RequiresValidTag; }
set
{
_rfcTag.RequiresValidTag = value;
CheckVariantAndScriptRules();
}
}
/// <summary>
/// Creates a new WritingSystemDefinition
/// </summary>
/// <param name="language">A valid BCP47 language subtag</param>
/// <param name="script">A valid BCP47 script subtag</param>
/// <param name="region">A valid BCP47 region subtag</param>
/// <param name="variant">A valid BCP47 variant subtag</param>
/// <param name="abbreviation">The desired abbreviation for this writing system definition</param>
/// <param name="rightToLeftScript">Indicates whether this writing system uses a right to left script</param>
public WritingSystemDefinition(string language, string script, string region, string variant, string abbreviation, bool rightToLeftScript)
: this()
{
string variantPart;
string privateUsePart;
SplitVariantAndPrivateUse(variant, out variantPart, out privateUsePart);
_rfcTag = new RFC5646Tag(language, script, region, variantPart, privateUsePart);
_abbreviation = abbreviation;
_rightToLeftScript = rightToLeftScript;
UpdateIdFromRfcTag();
}
/// <summary>
/// Copy constructor from IWritingSystem: useable only if the interface is in fact implemented by this class.
/// </summary>
/// <param name="ws"></param>
internal WritingSystemDefinition(IWritingSystemDefinition ws) : this ((WritingSystemDefinition)ws)
{
}
/// <summary>
/// Copy constructor.
/// </summary>
/// <param name="ws">The ws.</param>
public WritingSystemDefinition(WritingSystemDefinition ws)
{
_abbreviation = ws._abbreviation;
_rightToLeftScript = ws._rightToLeftScript;
_defaultFontName = ws._defaultFontName;
_defaultFontSize = ws._defaultFontSize;
_keyboard = ws._keyboard;
_versionNumber = ws._versionNumber;
_versionDescription = ws._versionDescription;
_nativeName = ws._nativeName;
_sortUsing = ws._sortUsing;
_sortRules = ws._sortRules;
_spellCheckingId = ws._spellCheckingId;
_dateModified = ws._dateModified;
_isUnicodeEncoded = ws._isUnicodeEncoded;
_rfcTag = new RFC5646Tag(ws._rfcTag);
_languageName = ws._languageName;
if (ws._localKeyboard != null)
_localKeyboard = ws._localKeyboard.Clone();
WindowsLcid = ws.WindowsLcid;
foreach (var kbd in ws._knownKeyboards)
_knownKeyboards.Add(kbd.Clone());
_id = ws._id;
}
///<summary>
///This is the version of the locale data contained in this writing system.
///This should not be confused with the version of our writingsystemDefinition implementation which is mostly used for migration purposes.
///That information is stored in the "LatestWritingSystemDefinitionVersion" property.
///</summary>
virtual public string VersionNumber
{
get { return _versionNumber; }
set { UpdateString(ref _versionNumber, value); }
}
virtual public string VersionDescription
{
get { return _versionDescription; }
set { UpdateString(ref _versionDescription, value); }
}
virtual public DateTime DateModified
{
get { return _dateModified; }
set { _dateModified = value; }
}
public IEnumerable<Iso639LanguageCode> ValidLanguages
{
get
{
return StandardTags.ValidIso639LanguageCodes;
}
}
public IEnumerable<Iso15924Script> ValidScript
{
get
{
return StandardTags.ValidIso15924Scripts;
}
}
public IEnumerable<IanaSubtag> ValidRegions
{
get
{
return StandardTags.ValidIso3166Regions;
}
}
public IEnumerable<IanaSubtag> ValidVariants
{
get
{
foreach (var variant in StandardTags.ValidRegisteredVariants)
{
yield return variant;
}
}
}
/// <summary>
/// Adjusts the BCP47 tag to indicate the desired form of Ipa by inserting fonipa in the variant and emic or etic in private use where necessary.
/// </summary>
virtual public IpaStatusChoices IpaStatus
{
get
{
if (Rfc5646TagIsPhonemicConform)
{
return IpaStatusChoices.IpaPhonemic;
}
if (Rfc5646TagIsPhoneticConform)
{
return IpaStatusChoices.IpaPhonetic;
}
if (VariantSubTagIsIpaConform)
{
return IpaStatusChoices.Ipa;
}
return IpaStatusChoices.NotIpa;
}
set
{
if (IpaStatus == value)
{
return;
}
//We need this to make sure that our language tag won't start with the variant "fonipa"
if(_rfcTag.Language == "")
{
_rfcTag.Language = WellKnownSubTags.Unlisted.Language;
}
_rfcTag.RemoveFromPrivateUse(WellKnownSubTags.Audio.PrivateUseSubtag);
/* "There are some variant subtags that have no prefix field,
* eg. fonipa (International IpaPhonetic Alphabet). Such variants
* should appear after any other variant subtags with prefix information."
*/
_rfcTag.RemoveFromPrivateUse("x-etic");
_rfcTag.RemoveFromPrivateUse("x-emic");
_rfcTag.RemoveFromVariant("fonipa");
switch (value)
{
default:
break;
case IpaStatusChoices.Ipa:
_rfcTag.AddToVariant(WellKnownSubTags.Ipa.VariantSubtag);
break;
case IpaStatusChoices.IpaPhonemic:
_rfcTag.AddToVariant(WellKnownSubTags.Ipa.VariantSubtag);
_rfcTag.AddToPrivateUse(WellKnownSubTags.Ipa.PhonemicPrivateUseSubtag);
break;
case IpaStatusChoices.IpaPhonetic:
_rfcTag.AddToVariant(WellKnownSubTags.Ipa.VariantSubtag);
_rfcTag.AddToPrivateUse(WellKnownSubTags.Ipa.PhoneticPrivateUseSubtag);
break;
}
Modified = true;
UpdateIdFromRfcTag();
}
}
/// <summary>
/// Adjusts the BCP47 tag to indicate that this is an "audio writing system" by inserting "audio" in the private use and "Zxxx" in the script
/// </summary>
virtual public bool IsVoice
{
get
{
return ScriptSubTagIsAudio && VariantSubTagIsAudio;
}
set
{
if (IsVoice == value) { return; }
if (value)
{
IpaStatus = IpaStatusChoices.NotIpa;
Keyboard = string.Empty;
if(Language == "")
{
Language = WellKnownSubTags.Unlisted.Language;
}
Script = WellKnownSubTags.Audio.Script;
_rfcTag.AddToPrivateUse(WellKnownSubTags.Audio.PrivateUseSubtag);
}
else
{
_rfcTag.Script = String.Empty;
_rfcTag.RemoveFromPrivateUse(WellKnownSubTags.Audio.PrivateUseSubtag);
}
Modified = true;
UpdateIdFromRfcTag();
CheckVariantAndScriptRules();
}
}
private bool VariantSubTagIsAudio
{
get
{
return _rfcTag.PrivateUseContains(WellKnownSubTags.Audio.PrivateUseSubtag);
}
}
private bool ScriptSubTagIsAudio
{
get { return _rfcTag.Script.Equals(WellKnownSubTags.Audio.Script,StringComparison.OrdinalIgnoreCase); }
}
/// <summary>
/// A string representing the subtag of the same name as defined by BCP47.
/// Note that the variant also includes the private use subtags. These are appended to the variant subtags seperated by "-x-"
/// Also note the convenience methods "SplitVariantAndPrivateUse" and "ConcatenateVariantAndPrivateUse" for easier
/// variant/ private use handling
/// </summary>
// Todo: this could/should become an ordered list of variant tags
virtual public string Variant
{
get
{
string variantToReturn = ConcatenateVariantAndPrivateUse(_rfcTag.Variant, _rfcTag.PrivateUse);
return variantToReturn;
}
set
{
value = value ?? "";
if (value == Variant)
{
return;
}
// Note that the WritingSystemDefinition provides no direct support for private use except via Variant set.
string variant;
string privateUse;
SplitVariantAndPrivateUse(value, out variant, out privateUse);
_rfcTag.Variant = variant;
_rfcTag.PrivateUse = privateUse;
Modified = true;
UpdateIdFromRfcTag();
CheckVariantAndScriptRules();
}
}
/// <summary>
/// Adds a valid BCP47 registered variant subtag to the variant. Any other tag is inserted as private use.
/// </summary>
/// <param name="registeredVariantOrPrivateUseSubtag">A valid variant tag or another tag which will be inserted into private use.</param>
public void AddToVariant(string registeredVariantOrPrivateUseSubtag)
{
if (StandardTags.IsValidRegisteredVariant(registeredVariantOrPrivateUseSubtag))
{
_rfcTag.AddToVariant(registeredVariantOrPrivateUseSubtag);
}
else
{
_rfcTag.AddToPrivateUse(registeredVariantOrPrivateUseSubtag);
}
UpdateIdFromRfcTag();
CheckVariantAndScriptRules();
}
/// <summary>
/// A convenience method to help consumers deal with variant and private use subtags both being stored in the Variant property.
/// This method will search the Variant part of the BCP47 tag for an "x" extension marker and split the tag into variant and private use sections
/// Note the complementary method "ConcatenateVariantAndPrivateUse"
/// </summary>
/// <param name="variantAndPrivateUse">The string containing variant and private use sections seperated by an "x" private use subtag</param>
/// <param name="variant">The resulting variant section</param>
/// <param name="privateUse">The resulting private use section</param>
public static void SplitVariantAndPrivateUse(string variantAndPrivateUse, out string variant, out string privateUse)
{
if (variantAndPrivateUse.StartsWith("x-",StringComparison.OrdinalIgnoreCase)) // Private Use at the beginning
{
variantAndPrivateUse = variantAndPrivateUse.Substring(2); // Strip the leading x-
variant = "";
privateUse = variantAndPrivateUse;
}
else if (variantAndPrivateUse.Contains("-x-", StringComparison.OrdinalIgnoreCase)) // Private Use from the middle
{
string[] partsOfVariant = variantAndPrivateUse.Split(new[] { "-x-" }, StringSplitOptions.None);
if(partsOfVariant.Length == 1) //Must have been a capital X
{
partsOfVariant = variantAndPrivateUse.Split(new[] { "-X-" }, StringSplitOptions.None);
}
variant = partsOfVariant[0];
privateUse = partsOfVariant[1];
}
else // No Private Use, it's contains variants only
{
variant = variantAndPrivateUse;
privateUse = "";
}
}
/// <summary>
/// A convenience method to help consumers deal with registeredVariantSubtags and private use subtags both being stored in the Variant property.
/// This method will insert a "x" private use subtag between a set of registered BCP47 variants and a set of private use subtags
/// Note the complementary method "ConcatenateVariantAndPrivateUse"
/// </summary>
/// <param name="registeredVariantSubtags">A set of registered variant subtags</param>
/// <param name="privateUseSubtags">A set of private use subtags</param>
/// <returns>The resulting combination of registeredVariantSubtags and private use.</returns>
public static string ConcatenateVariantAndPrivateUse(string registeredVariantSubtags, string privateUseSubtags)
{
if(String.IsNullOrEmpty(privateUseSubtags))
{
return registeredVariantSubtags;
}
if(!privateUseSubtags.StartsWith("x-", StringComparison.OrdinalIgnoreCase))
{
privateUseSubtags = String.Concat("x-", privateUseSubtags);
}
string variantToReturn = registeredVariantSubtags;
if (!String.IsNullOrEmpty(privateUseSubtags))
{
if (!String.IsNullOrEmpty(variantToReturn))
{
variantToReturn += "-";
}
variantToReturn += privateUseSubtags;
}
return variantToReturn;
}
private void CheckVariantAndScriptRules()
{
if (!RequiresValidTag)
return;
if (VariantSubTagIsAudio && !ScriptSubTagIsAudio)
{
throw new ArgumentException("The script subtag must be set to " + WellKnownSubTags.Audio.Script + " when the variant tag indicates an audio writing system.");
}
bool rfcTagHasAnyIpa = VariantSubTagIsIpaConform ||
_rfcTag.PrivateUseContains(WellKnownSubTags.Ipa.PhonemicPrivateUseSubtag) ||
_rfcTag.PrivateUseContains(WellKnownSubTags.Ipa.PhoneticPrivateUseSubtag);
if (VariantSubTagIsAudio && rfcTagHasAnyIpa)
{
throw new ArgumentException("A writing system may not be marked as audio and ipa at the same time.");
}
if((_rfcTag.PrivateUseContains(WellKnownSubTags.Ipa.PhonemicPrivateUseSubtag) ||
_rfcTag.PrivateUseContains(WellKnownSubTags.Ipa.PhoneticPrivateUseSubtag)) &&
!VariantSubTagIsIpaConform)
{
throw new ArgumentException("A writing system may not be marked as phonetic (x-etic) or phonemic (x-emic) and lack the variant marker fonipa.");
}
}
private bool VariantSubTagIsIpaConform
{
get
{
return _rfcTag.VariantContains(WellKnownSubTags.Ipa.VariantSubtag);
}
}
private bool Rfc5646TagIsPhoneticConform
{
get
{
return _rfcTag.VariantContains(WellKnownSubTags.Ipa.VariantSubtag) &&
_rfcTag.PrivateUseContains(WellKnownSubTags.Ipa.PhoneticPrivateUseSubtag);
}
}
private bool Rfc5646TagIsPhonemicConform
{
get
{
return _rfcTag.VariantContains(WellKnownSubTags.Ipa.VariantSubtag) &&
_rfcTag.PrivateUseContains(WellKnownSubTags.Ipa.PhonemicPrivateUseSubtag);
}
}
/// <summary>
/// Sets all BCP47 language tag components at once.
/// This method is useful for avoiding invalid intermediate states when switching from one valid tag to another.
/// </summary>
/// <param name="language">A valid BCP47 language subtag.</param>
/// <param name="script">A valid BCP47 script subtag.</param>
/// <param name="region">A valid BCP47 region subtag.</param>
/// <param name="variant">A valid BCP47 variant subtag.</param>
public void SetAllComponents(string language, string script, string region, string variant)
{
string oldId = _rfcTag.CompleteTag;
string variantPart;
string privateUsePart;
SplitVariantAndPrivateUse(variant, out variantPart, out privateUsePart);
_rfcTag = new RFC5646Tag(language, script, region, variantPart, privateUsePart);
UpdateIdFromRfcTag();
if(oldId == _rfcTag.CompleteTag)
{
return;
}
Modified = true;
CheckVariantAndScriptRules();
}
/// <summary>
/// A string representing the subtag of the same name as defined by BCP47.
/// </summary>
virtual public string Region
{
get
{
return _rfcTag.Region;
}
set
{
value = value ?? "";
if (value == Region)
{
return;
}
_rfcTag.Region = value;
UpdateIdFromRfcTag();
Modified = true;
}
}
/// <summary>
/// A string representing the subtag of the same name as defined by BCP47.
/// </summary>
virtual public string Language
{
get
{
return _rfcTag.Language;
}
set
{
value = value ?? "";
if (value == Language)
{
return;
}
_rfcTag.Language = value;
UpdateIdFromRfcTag();
Modified = true;
}
}
/// <summary>
/// The desired abbreviation for the writing system
/// </summary>
virtual public string Abbreviation
{
get
{
if (String.IsNullOrEmpty(_abbreviation))
{
// Use the language subtag unless it's an unlisted language.
// If it's an unlisted language, use the private use area language subtag.
if (Language == "qaa")
{
int idx = Id.IndexOf("-x-");
if (idx > 0 && Id.Length > idx + 3)
{
var abbr = Id.Substring(idx + 3);
idx = abbr.IndexOf('-');
if (idx > 0)
abbr = abbr.Substring(0, idx);
return abbr;
}
}
return Language;
}
return _abbreviation;
}
set
{
UpdateString(ref _abbreviation, value);
}
}
/// <summary>
/// A string representing the subtag of the same name as defined by BCP47.
/// </summary>
virtual public string Script
{
get
{
return _rfcTag.Script;
}
set
{
value = value ?? "";
if (value == Script)
{
return;
}
_rfcTag.Script = value;
Modified = true;
UpdateIdFromRfcTag();
CheckVariantAndScriptRules();
}
}
/// <summary>
/// The language name to use. Typically this is the language name associated with the BCP47 language subtag as defined by the IANA subtag registry
/// </summary>
virtual public string LanguageName
{
get
{
if (!String.IsNullOrEmpty(_languageName))
{
return _languageName;
}
var code = StandardTags.ValidIso639LanguageCodes.FirstOrDefault(c => c.Code.Equals(Language));
if (code != null)
{
return code.Name;
}
return "Unknown Language";
// TODO Make the below work.
//return StandardTags.LanguageName(Language) ?? "Unknown Language";
}
set
{
value = value ?? "";
UpdateString(ref _languageName, value);
}
}
/// <summary>
/// This method will make a copy of the given writing system and
/// then make the Id unique compared to list of Ids passed in by
/// appending dupl# where # is a digit that increases with the
/// number of duplicates found.
/// </summary>
/// <param name="writingSystemToCopy"></param>
/// <param name="otherWritingsystemIds"></param>
/// <returns></returns>
public static WritingSystemDefinition CreateCopyWithUniqueId(
IWritingSystemDefinition writingSystemToCopy, IEnumerable<string> otherWritingsystemIds)
{
var newWs = writingSystemToCopy.Clone();
var lastAppended = String.Empty;
int duplicateNumber = 0;
while (otherWritingsystemIds.Any(id => id.Equals(newWs.Id, StringComparison.OrdinalIgnoreCase)))
{
newWs._rfcTag.RemoveFromPrivateUse(lastAppended);
var currentToAppend = String.Format("dupl{0}", duplicateNumber);
if (!newWs._rfcTag.PrivateUse.Contains(currentToAppend))
{
newWs._rfcTag.AddToPrivateUse(currentToAppend);
newWs.UpdateIdFromRfcTag();
lastAppended = currentToAppend;
}
duplicateNumber++;
}
return newWs;
}
protected void UpdateString(ref string field, string value)
{
if (field == value)
return;
//count null as same as ""
if (String.IsNullOrEmpty(field) && String.IsNullOrEmpty(value))
{
return;
}
Modified = true;
field = value;
}
/// <summary>
/// Used by IWritingSystemRepository to identify writing systems. Only change this if you would like to replace a writing system with the same StoreId
/// already contained in the repo. This is useful creating a temporary copy of a writing system that you may or may not care to persist to the
/// IWritingSystemRepository.
/// Typical use would therefor be:
/// ws.Clone(wsorig);
/// ws.StoreId=wsOrig.StoreId;
/// **make changes to ws**
/// repo.Set(ws);
/// </summary>
virtual public string StoreID { get; set; }
/// <summary>
/// A automatically generated descriptive label for the writing system definition.
/// </summary>
virtual public string DisplayLabel
{
get
{
//jh (Oct 2010) made it start with RFC5646 because all ws's in a lang start with the
//same abbreviation, making imppossible to see (in SOLID for example) which you chose.
bool languageIsUnknown = Bcp47Tag.Equals(WellKnownSubTags.Unlisted.Language, StringComparison.OrdinalIgnoreCase);
if (!String.IsNullOrEmpty(Bcp47Tag) && !languageIsUnknown)
{
return Bcp47Tag;
}
if (languageIsUnknown)
{
if (!String.IsNullOrEmpty(_abbreviation))
{
return _abbreviation;
}
if (!String.IsNullOrEmpty(_languageName))
{
string n = _languageName;
return n.Substring(0, n.Length > 4 ? 4 : n.Length);
}
}
return "???";
}
}
virtual public string ListLabel
{
get
{
//the idea here is to give writing systems a nice legible label for. For this reason subtags are replaced with nice labels
var wsToConstructLabelFrom = this.Clone();
string n = string.Empty;
n = !String.IsNullOrEmpty(wsToConstructLabelFrom.LanguageName) ? wsToConstructLabelFrom.LanguageName : wsToConstructLabelFrom.DisplayLabel;
string details = "";
if (wsToConstructLabelFrom.IpaStatus != IpaStatusChoices.NotIpa)
{
switch (IpaStatus)
{
case IpaStatusChoices.Ipa:
details += "IPA-";
break;
case IpaStatusChoices.IpaPhonetic:
details += "IPA-etic-";
break;
case IpaStatusChoices.IpaPhonemic:
details += "IPA-emic-";
break;
default:
throw new ArgumentOutOfRangeException();
}
wsToConstructLabelFrom.IpaStatus = IpaStatusChoices.NotIpa;
}
if (wsToConstructLabelFrom.IsVoice)
{
details += "Voice-";
wsToConstructLabelFrom.IsVoice = false;
}
if (wsToConstructLabelFrom.IsDuplicate)
{
var duplicateNumbers = new List<string>(wsToConstructLabelFrom.DuplicateNumbers);
foreach (var number in duplicateNumbers)
{
details += "Copy";
if (number != "0")
{
details += number;
}
details += "-";
wsToConstructLabelFrom._rfcTag.RemoveFromPrivateUse("dupl" + number);
}
}
if (!String.IsNullOrEmpty(wsToConstructLabelFrom.Script))
{
details += wsToConstructLabelFrom.Script+"-";
}
if (!String.IsNullOrEmpty(wsToConstructLabelFrom.Region))
{
details += wsToConstructLabelFrom.Region + "-";
}
if (!String.IsNullOrEmpty(wsToConstructLabelFrom.Variant))
{
details += wsToConstructLabelFrom.Variant + "-";
}
details = details.Trim(new[] { '-' });
if (details.Length > 0)
details = " ("+details + ")";
return n+details;
}
}
protected bool IsDuplicate
{
get { return _rfcTag.GetPrivateUseSubtagsMatchingRegEx(@"^dupl\d$").Count() != 0; }
}
protected IEnumerable<string> DuplicateNumbers
{
get
{
return _rfcTag.GetPrivateUseSubtagsMatchingRegEx(@"^dupl\d$").Select(subtag => Regex.Match(subtag, @"\d*$").Value);
}
}
/// <summary>
/// The current BCP47 tag which is a concatenation of the Language, Script, Region and Variant properties.
/// </summary>
public string Bcp47Tag
{
get
{
return _rfcTag.CompleteTag;
}
}
/// <summary>
/// The identifier for this writing syetm definition. Use this in files and as a key to the IWritingSystemRepository.
/// Note that this is usually identical to the Bcp47 tag and should rarely differ.
/// </summary>
public string Id
{
get
{
return _id;
}
internal set
{
value = value ?? "";
_id = value;
Modified = true;
}
}
/// <summary>
/// Indicates whether the writing system definition has been modified.
/// Note that this flag is automatically set by all methods that cause a modification and is reset by the IwritingSystemRepository.Save() method
/// </summary>
virtual public bool Modified { get; set; }
virtual public bool MarkedForDeletion { get; set; }
/// <summary>
/// The font used to display data encoded in this writing system
/// </summary>
virtual public string DefaultFontName
{
get
{
return _defaultFontName;
}
set
{
UpdateString(ref _defaultFontName, value);
}
}
/// <summary>
/// the preferred font size to use for data encoded in this writing system.
/// </summary>
virtual public float DefaultFontSize
{
get
{
return _defaultFontSize;
}
set
{
if (value == _defaultFontSize)
{
return;
}
if (value < 0 || float.IsNaN(value) || float.IsInfinity(value))
{
throw new ArgumentOutOfRangeException();
}
_defaultFontSize = value;
Modified = true;
}
}
/// <summary>
/// enforcing a minimum on _defaultFontSize, while reasonable, just messed up too many IO unit tests
/// </summary>
/// <returns></returns>
virtual public float GetDefaultFontSizeOrMinimum()
{
if (_defaultFontSize < kMinimumFontSize)
return kDefaultSizeIfWeDontKnow;
return _defaultFontSize;
}
/// <summary>
/// The preferred keyboard to use to generate data encoded in this writing system.
/// </summary>
virtual public string Keyboard
{
get
{
if(String.IsNullOrEmpty(_keyboard))
{
return "";
}
return _keyboard;
}
set
{
UpdateString(ref _keyboard, value);
}
}
private IKeyboardDefinition _localKeyboard;
public string WindowsLcid { get; set; }
public IKeyboardDefinition LocalKeyboard
{
get
{
if (_localKeyboard == null)
{
var available = new HashSet<IKeyboardDefinition>(WritingSystems.Keyboard.Controller.AllAvailableKeyboards);
_localKeyboard = (from k in KnownKeyboards where available.Contains(k) select k).FirstOrDefault();
}
if (_localKeyboard == null)
{
_localKeyboard = WritingSystems.Keyboard.Controller.DefaultForWritingSystem(this);
}
return _localKeyboard;
}
set
{
_localKeyboard = value;
AddKnownKeyboard(value);
Modified = true;
}
}
internal IKeyboardDefinition RawLocalKeyboard
{
get { return _localKeyboard; }
}
/// <summary>
/// Indicates whether this writing system is read and written from left to right or right to left
/// </summary>
virtual public bool RightToLeftScript
{
get
{
return _rightToLeftScript;
}
set
{
if(value != _rightToLeftScript)
{
Modified = true;
_rightToLeftScript = value;
}
}
}
/// <summary>
/// The windows "NativeName" from the Culture class
/// </summary>
virtual public string NativeName
{
get
{
return _nativeName;
}
set
{
UpdateString(ref _nativeName, value);
}
}
/// <summary>
/// Indicates the type of sort rules used to encode the sort order.
/// Note that the actual sort rules are contained in the SortRules property
/// </summary>
virtual public SortRulesType SortUsing
{
get { return _sortUsing; }
set
{
if (value != _sortUsing)
{
_sortUsing = value;
_collator = null;
Modified = true;
}
}
}
/// <summary>
/// The sort rules that efine the sort order.
/// Note that you must indicate the type of sort rules used by setting the "SortUsing" property
/// </summary>
virtual public string SortRules
{
get { return _sortRules ?? string.Empty; }
set
{
_collator = null;
UpdateString(ref _sortRules, value);
}
}
/// <summary>
/// A convenience method for sorting like anthoer language
/// </summary>
/// <param name="languageCode">A valid language code</param>
public void SortUsingOtherLanguage(string languageCode)
{
SortUsing = SortRulesType.OtherLanguage;
SortRules = languageCode;
}
/// <summary>
/// A convenience method for sorting with custom ICU rules
/// </summary>
/// <param name="sortRules">custom ICU sortrules</param>
public void SortUsingCustomICU(string sortRules)
{
SortUsing = SortRulesType.CustomICU;
SortRules = sortRules;
}
/// <summary>
/// A convenience method for sorting with "shoebox" style rules
/// </summary>
/// <param name="sortRules">"shoebox" style rules</param>
public void SortUsingCustomSimple(string sortRules)
{
SortUsing = SortRulesType.CustomSimple;
SortRules = sortRules;
}
/// <summary>
/// The id used to select the spell checker.
/// </summary>
virtual public string SpellCheckingId
{
get
{
return _spellCheckingId;
}
set { UpdateString(ref _spellCheckingId, value); }
}
/// <summary>
/// Returns an ICollator interface that can be used to sort strings based
/// on the custom collation rules.
/// </summary>
virtual public ICollator Collator
{
get
{
if (_collator == null)
{
switch (SortUsing)
{
case SortRulesType.DefaultOrdering:
_collator = new IcuRulesCollator(String.Empty); // was SystemCollator(null);
break;
case SortRulesType.CustomSimple:
_collator = new SimpleRulesCollator(SortRules);
break;
case SortRulesType.CustomICU:
_collator = new IcuRulesCollator(SortRules);
break;
case SortRulesType.OtherLanguage:
_collator = new SystemCollator(SortRules);
break;
}
}
return _collator;
}
}
/// <summary>
/// Tests whether the current custom collation rules are valid.
/// </summary>
/// <param name="message">Used for an error message if rules do not validate.</param>
/// <returns>True if rules are valid, false otherwise.</returns>
virtual public bool ValidateCollationRules(out string message)
{
message = null;
switch (SortUsing)
{
case SortRulesType.DefaultOrdering:
return String.IsNullOrEmpty(SortRules);
case SortRulesType.CustomICU:
return IcuRulesCollator.ValidateSortRules(SortRules, out message);
case SortRulesType.CustomSimple:
return SimpleRulesCollator.ValidateSimpleRules(SortRules, out message);
case SortRulesType.OtherLanguage:
try
{
new SystemCollator(SortRules);
}
catch (Exception e)
{
message = String.Format("Error while validating sorting rules: {0}", e.Message);
return false;
}
return true;
}
return false;
}
public override string ToString()
{
return _rfcTag.ToString();
}
/// <summary>
/// Creates a clone of the current writing system.
/// Note that this excludes the properties: Modified, MarkedForDeletion and StoreID
/// </summary>
/// <returns></returns>
virtual public WritingSystemDefinition Clone()
{
return new WritingSystemDefinition(this);
}
public override bool Equals(Object obj)
{
if (!(obj is WritingSystemDefinition)) return false;
return Equals((WritingSystemDefinition)obj);
}
public bool Equals(WritingSystemDefinition other)
{
if (other == null) return false;
if (!_rfcTag.Equals(other._rfcTag)) return false;
if ((_languageName != null && !_languageName.Equals(other._languageName)) || (other._languageName != null && !other._languageName.Equals(_languageName))) return false;
if ((_abbreviation != null && !_abbreviation.Equals(other._abbreviation)) || (other._abbreviation != null && !other._abbreviation.Equals(_abbreviation))) return false;
if ((_versionNumber != null && !_versionNumber.Equals(other._versionNumber)) || (other._versionNumber != null && !other._versionNumber.Equals(_versionNumber))) return false;
if ((_versionDescription != null && !_versionDescription.Equals(other._versionDescription)) || (other._versionDescription != null && !other._versionDescription.Equals(_versionDescription))) return false;
if ((_defaultFontName != null && !_defaultFontName.Equals(other._defaultFontName)) || (other._defaultFontName != null && !other._defaultFontName.Equals(_defaultFontName))) return false;
if ((_keyboard != null && !_keyboard.Equals(other._keyboard)) || (other._keyboard != null && !other._keyboard.Equals(_keyboard))) return false;
if ((_sortRules != null && !_sortRules.Equals(other._sortRules)) || (other._sortRules != null && !other._sortRules.Equals(_sortRules))) return false;
if ((_spellCheckingId != null && !_spellCheckingId.Equals(other._spellCheckingId)) || (other._spellCheckingId != null && !other._spellCheckingId.Equals(_spellCheckingId))) return false;
if ((_nativeName != null && !_nativeName.Equals(other._nativeName)) || (other._nativeName != null && !other._nativeName.Equals(_nativeName))) return false;
if ((_id != null && !_id.Equals(other._id)) || (other._id != null && !other._id.Equals(_id))) return false;
if (!_isUnicodeEncoded.Equals(other._isUnicodeEncoded)) return false;
if (!_dateModified.Equals(other._dateModified)) return false;
if (!_defaultFontSize.Equals(other._defaultFontSize)) return false;
if (!SortUsing.Equals(other.SortUsing)) return false;
if (!_rightToLeftScript.Equals(other._rightToLeftScript)) return false;
if ((_localKeyboard != null && !_localKeyboard.Equals(other._localKeyboard)) || (_localKeyboard == null && other._localKeyboard != null)) return false;
if (WindowsLcid != other.WindowsLcid) return false;
if (_knownKeyboards.Count != other._knownKeyboards.Count) return false;
for (int i = 0; i < _knownKeyboards.Count; i++)
{
if (!_knownKeyboards[i].Equals(other._knownKeyboards[i])) return false;
}
return true;
}
private void UpdateIdFromRfcTag()
{
_id = Bcp47Tag;
}
/// <summary>
/// Indicates whether this writing system is unicode encoded or legacy encoded
/// </summary>
public bool IsUnicodeEncoded
{
get
{
return _isUnicodeEncoded;
}
set
{
if (value != _isUnicodeEncoded)
{
Modified = true;
_isUnicodeEncoded = value;
}
}
}
/// <summary>
/// Parses the supplied BCP47 tag and sets the Language, Script, Region and Variant properties accordingly
/// </summary>
/// <param name="completeTag">A valid BCP47 tag</param>
public void SetTagFromString(string completeTag)
{
_rfcTag = RFC5646Tag.Parse(completeTag);
UpdateIdFromRfcTag();
Modified = true;
}
/// <summary>
/// Parses the supplied BCP47 tag and return a new writing system definition with the correspnding Language, Script, Region and Variant properties
/// </summary>
/// <param name="bcp47Tag">A valid BCP47 tag</param>
public static WritingSystemDefinition Parse(string bcp47Tag)
{
var writingSystemDefinition = new WritingSystemDefinition();
writingSystemDefinition.SetTagFromString(bcp47Tag);
return writingSystemDefinition;
}
/// <summary>
/// Returns a new writing system definition with the corresponding Language, Script, Region and Variant properties set
/// </summary>
public static WritingSystemDefinition FromSubtags(string language, string script, string region, string variantAndPrivateUse)
{
return new WritingSystemDefinition(language, script, region, variantAndPrivateUse, string.Empty, false);
}
/// <summary>
/// Filters out all "WellKnownSubTags" out of a list of subtags
/// </summary>
/// <param name="privateUseTokens"></param>
/// <returns></returns>
public static IEnumerable<string> FilterWellKnownPrivateUseTags(IEnumerable<string> privateUseTokens)
{
foreach (var privateUseToken in privateUseTokens)
{
string strippedToken = RFC5646Tag.StripLeadingPrivateUseMarker(privateUseToken);
if (strippedToken.Equals(RFC5646Tag.StripLeadingPrivateUseMarker(WellKnownSubTags.Audio.PrivateUseSubtag), StringComparison.OrdinalIgnoreCase) ||
strippedToken.Equals(RFC5646Tag.StripLeadingPrivateUseMarker(WellKnownSubTags.Ipa.PhonemicPrivateUseSubtag), StringComparison.OrdinalIgnoreCase) ||
strippedToken.Equals(RFC5646Tag.StripLeadingPrivateUseMarker(WellKnownSubTags.Ipa.PhoneticPrivateUseSubtag), StringComparison.OrdinalIgnoreCase))
continue;
yield return privateUseToken;
}
}
List<IKeyboardDefinition> _knownKeyboards = new List<IKeyboardDefinition>();
public IEnumerable<IKeyboardDefinition> KnownKeyboards
{
get { return _knownKeyboards; }
}
public void AddKnownKeyboard(IKeyboardDefinition newKeyboard)
{
if (newKeyboard == null)
return;
// Review JohnT: how should this affect order?
// e.g.: last added should be first?
// Current algorithm keeps them in the order added, hopefully meaning the most likely one, added first,
// remains the default.
if (KnownKeyboards.Contains(newKeyboard))
return;
_knownKeyboards.Add(newKeyboard);
Modified = true;
}
/// <summary>
/// Returns the available keyboards (known to Keyboard.Controller) that are not KnownKeyboards for this writing system.
/// </summary>
public IEnumerable<IKeyboardDefinition> OtherAvailableKeyboards
{
get
{
return WritingSystems.Keyboard.Controller.AllAvailableKeyboards.Except(KnownKeyboards);
}
}
public static System.Drawing.Font CreateFont(IWritingSystemDefinition writingSystem)
{
float size = writingSystem.DefaultFontSize > 0 ? writingSystem.DefaultFontSize : 12;
try
{
return new System.Drawing.Font(writingSystem.DefaultFontName, size);
}
catch (Exception e) //I could never get the above to fail, but a user did (WS-34091), so now we catch it here.
{
Palaso.Reporting.ErrorReport.NotifyUserOfProblem(new Palaso.Reporting.ShowOncePerSessionBasedOnExactMessagePolicy(),
e,
"There is something wrong with the font {0} on this computer. Try re-installing it. Meanwhile, the font {1} will be used instead.",
writingSystem.DefaultFontName, System.Drawing.SystemFonts.DefaultFont.Name);
return new System.Drawing.Font(System.Drawing.SystemFonts.DefaultFont.Name, size);
}
}
}
public enum IpaStatusChoices
{
NotIpa,
Ipa,
IpaPhonetic,
IpaPhonemic
}
public class WellKnownSubTags
{
public class Unlisted
{
public const string Language = "qaa";
}
public class Unwritten
{
public const string Script = "Zxxx";
}
//The "x-" is required before each of the strings below, since WritingSystemDefinition needs "x-" to distinguish BCP47 private use from variant
//Without the "x-" a consumer who wanted to set a writing ystem as audio would have to write: ws.Variant = "x-" + WellKnownSubtags.Audio.PrivateUseSubtag
public class Audio
{
public const string PrivateUseSubtag = "x-audio";
public const string Script= Unwritten.Script;
}
public class Ipa
{
public const string VariantSubtag = "fonipa";
public const string PhonemicPrivateUseSubtag = "x-emic";
public const string PhoneticPrivateUseSubtag = "x-etic";
}
}
}
| |
/* 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 ClusterMembersDecoder
{
public const ushort BLOCK_LENGTH = 8;
public const ushort TEMPLATE_ID = 106;
public const ushort SCHEMA_ID = 111;
public const ushort SCHEMA_VERSION = 7;
private ClusterMembersDecoder _parentMessage;
private IDirectBuffer _buffer;
protected int _offset;
protected int _limit;
protected int _actingBlockLength;
protected int _actingVersion;
public ClusterMembersDecoder()
{
_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 ClusterMembersDecoder 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 MemberIdId()
{
return 1;
}
public static int MemberIdSinceVersion()
{
return 0;
}
public static int MemberIdEncodingOffset()
{
return 0;
}
public static int MemberIdEncodingLength()
{
return 4;
}
public static string MemberIdMetaAttribute(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 MemberIdNullValue()
{
return -2147483648;
}
public static int MemberIdMinValue()
{
return -2147483647;
}
public static int MemberIdMaxValue()
{
return 2147483647;
}
public int MemberId()
{
return _buffer.GetInt(_offset + 0, ByteOrder.LittleEndian);
}
public static int HighMemberIdId()
{
return 2;
}
public static int HighMemberIdSinceVersion()
{
return 0;
}
public static int HighMemberIdEncodingOffset()
{
return 4;
}
public static int HighMemberIdEncodingLength()
{
return 4;
}
public static string HighMemberIdMetaAttribute(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 HighMemberIdNullValue()
{
return -2147483648;
}
public static int HighMemberIdMinValue()
{
return -2147483647;
}
public static int HighMemberIdMaxValue()
{
return 2147483647;
}
public int HighMemberId()
{
return _buffer.GetInt(_offset + 4, ByteOrder.LittleEndian);
}
public static int ClusterMembersId()
{
return 3;
}
public static int ClusterMembersSinceVersion()
{
return 0;
}
public static string ClusterMembersCharacterEncoding()
{
return "US-ASCII";
}
public static string ClusterMembersMetaAttribute(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 ClusterMembersHeaderLength()
{
return 4;
}
public int ClusterMembersLength()
{
int limit = _parentMessage.Limit();
return (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
}
public int GetClusterMembers(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 GetClusterMembers(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 ClusterMembers()
{
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 override string ToString()
{
return AppendTo(new StringBuilder(100)).ToString();
}
public StringBuilder AppendTo(StringBuilder builder)
{
int originalLimit = Limit();
Limit(_offset + _actingBlockLength);
builder.Append("[ClusterMembers](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='memberId', 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='int32', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=4, offset=0, 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("MemberId=");
builder.Append(MemberId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='highMemberId', referencedName='null', description='null', id=2, version=0, deprecated=0, encodedLength=0, offset=4, 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=4, 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("HighMemberId=");
builder.Append(HighMemberId());
builder.Append('|');
//Token{signal=BEGIN_VAR_DATA, name='clusterMembers', referencedName='null', description='null', id=3, version=0, deprecated=0, encodedLength=0, offset=8, 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("ClusterMembers=");
builder.Append(ClusterMembers());
Limit(originalLimit);
return builder;
}
}
}
| |
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour
{
public float oxygen = 1f; // Between 0 and 1;
public float oxygenDecPerSec = 0.01f;
public float oxygenDecPerSecBoost = 0.02f;
public float oxygenGainedPerCapsule = 0.3f;
public bool isBoosted = false;
public float horsePowerBoostMultiply = 4f;
public WheelCollider WheelLF;
public WheelCollider WheelLB;
public WheelCollider WheelRF;
public WheelCollider WheelRB;
public Transform WheelLFTransform;
public Transform WheelLBTransform;
public Transform WheelRFTransform;
public Transform WheelRBTransform;
public float brakeSmogFactor;
bool isbraking = false;
public Transform AxleBack;
public Transform AxleFront;
public float currentSpeed;
public float horsePower = 120;
private float HorsePowerApplied;
public float brakeFriction = 10;
public float frictionCoeff = 0;
public float lowSpeedSteerAngle;
public float highSpeedSteerAngle;
private int horseToWatt = 1356;
private float ElevationLF = 0;
private float ElevationLB = 0;
private float ElevationRF = 0;
private float ElevationRB = 0;
private Vector3 offsetAxleB;
private Vector3 offsetAxleF;
public float BackAltitudeDifference;
public float BackLatitudeDifference;
public float FrontAltitudeDifference;
public float FrontLatitudeDifference;
public float BackAngle;
public float FrontAngle;
float dv = 1f;
float dh = 1f;
public ParticleRenderer prLF;
public ParticleRenderer prLB;
public ParticleRenderer prRF;
public ParticleRenderer prRB;
public ParticleEmitter peLF;
public ParticleEmitter peRF;
public float particleSize;
public Material skidMaterial;
ArrowManager arrowManager;
EndUIScript endUIScript;
TimerManager timerScript;
SoundScript soundScript;
bool endLevel = false;
/*void Update()
{
}*/
void Start()
{
// Destroy (GameObject.Find ( "Main Camera Menu"));
arrowManager = GetComponentInChildren<ArrowManager>();
endUIScript = GetComponentInChildren<EndUIScript>();
timerScript = GetComponentInChildren<TimerManager>();
soundScript = GetComponent<SoundScript>();
HorsePowerApplied = horsePower;
GetComponent<Rigidbody>().centerOfMass = Vector3.down * 1.5f;
currentSpeed = 0.0f;
//Compute the vertical and horizontal distance between the wheels in order to make some trigonometry for
//wheels steer angles
dv = Mathf.Abs(WheelLF.transform.position.x - WheelRB.transform.position.x);
dh = Mathf.Abs (WheelLF.transform.position.z - WheelRB.transform.position.z);
//Save the base position of both axle in order to modifiy it according to the suspension
offsetAxleB = AxleBack.localPosition;
offsetAxleF = AxleFront.localPosition;
GameObject respawn = (GameObject)GameObject.FindGameObjectsWithTag("Respawn").GetValue(0);
transform.position = respawn.transform.position;
transform.rotation = respawn.transform.rotation;
GetComponent<Rigidbody>().angularVelocity = Vector3.zero;
timerScript.LaunchTimer();
endUIScript.ResetTime();
}
void OnTriggerEnter(Collider other)
{
switch (other.gameObject.tag)
{
case "Finish":
if (endUIScript.Activate())
this.endLevel = true;
break;
case "capsule":
this.ModifyOxygenByDelta(oxygenGainedPerCapsule);
other.gameObject.SetActive (false);
this.soundScript.PlayBonus();
break;
case "checkpoint":
this.arrowManager.RemoveCheckPoint(other);
break;
}
}
void ModifyOxygenByDelta(float d)
{
this.oxygen += d;
if (this.oxygen > 1f)
this.oxygen = 1f;
else if (this.oxygen < 0f)
this.oxygen = 0f;
}
void FixedUpdate()
{
GetComponent<Rigidbody>().velocity = Vector3.zero;
GetComponent<Rigidbody>().angularVelocity = Vector3.zero;
if (endLevel)
{
return;
}
//Compute the vehicle speed according to the front wheel rotation
currentSpeed = 2*Mathf.PI*WheelLF.radius*Mathf.Abs(WheelLF.rpm*60/1000);
//Apply the torque according to the Power of vehicle and the speed (Use a min speed to limit the torque)
WheelLF.motorTorque = horseToWatt * HorsePowerApplied / Mathf.Max(currentSpeed, 10f) * Input.GetAxis ("Vertical");
WheelRF.motorTorque = horseToWatt * HorsePowerApplied / Mathf.Max(currentSpeed, 10f) * Input.GetAxis ("Vertical");
Debug.Log(WheelLF.motorTorque);
//Play sound of the motor according to the motor speed
this.soundScript.PlayMotor(currentSpeed);
//If the user brake
if (Input.GetAxis ("Vertical") == -1 && currentSpeed > 10 && WheelLF.rpm > 0 ||
Input.GetAxis ("Vertical") == 1 && currentSpeed > 10 && WheelLF.rpm < 0) {
//And the front wheels touch the ground
if (Physics.Raycast (WheelLF.transform.position, -WheelLF.transform.up, WheelLF.radius + WheelLF.suspensionDistance) ||
Physics.Raycast (WheelRF.transform.position, -WheelRF.transform.up, WheelRF.radius + WheelRF.suspensionDistance)) {
//Produce a brake sound
isbraking = true;
this.soundScript.PlayBrake(currentSpeed);
}
else
{
isbraking = false;
}
}
else
{
this.soundScript.StopBrake();
isbraking = false;
}
if (Input.GetButton("Jump"))
{
this.isBoosted = true;
this.ModifyOxygenByDelta (-this.oxygenDecPerSecBoost * Time.deltaTime);
HorsePowerApplied = horsePower * this.horsePowerBoostMultiply;
}
else
{
this.isBoosted = false;
HorsePowerApplied = horsePower;
}
//Compute brake torque according to the speed of the vehicle, and friction coefficient
float brake = currentSpeed * brakeFriction + frictionCoeff;
WheelLF.brakeTorque = brake;
WheelRF.brakeTorque = brake;
//Calculate steer angle of interior wheels according to the speed and the pression on the keyboard
float speedFactor = Mathf.Min(GetComponent<Rigidbody>().velocity.magnitude / 50);
float currentSteerAngle = Mathf.Lerp(lowSpeedSteerAngle, highSpeedSteerAngle, speedFactor);
currentSteerAngle *= Input.GetAxis("Horizontal");
//Calculate steer angle of external wheel according to the dimensions and the internal angle
if (currentSteerAngle > 0)
{
WheelRF.steerAngle = currentSteerAngle;
WheelLF.steerAngle = getExternalWheelAngle(currentSteerAngle, dv, dh);
}
else if(currentSteerAngle < 0)
{
WheelLF.steerAngle = currentSteerAngle;
WheelRF.steerAngle = getExternalWheelAngle(currentSteerAngle, dv, dh);
}
else
{
WheelLF.steerAngle = currentSteerAngle;
WheelRF.steerAngle = currentSteerAngle;
}
if(Input.GetButtonDown("LastCheckpoint"))
{
transform.position = arrowManager.getLastCheckpoint().position;
transform.rotation = arrowManager.getLastCheckpoint().rotation;
GetComponent<Rigidbody>().velocity = Vector3.zero;
GetComponent<Rigidbody>().angularVelocity = Vector3.zero;
}
}
void Update()
{
// woot
this.ModifyOxygenByDelta (-this.oxygenDecPerSec * Time.deltaTime);
//Rotate the Wheel mesh according to the Wheelcollider speed
WheelLFTransform.Rotate (0,0,WheelLF.rpm / 60 * -360 * Time.deltaTime);
WheelRFTransform.Rotate (0,0,WheelRF.rpm / 60 * -360 * Time.deltaTime);
WheelLBTransform.Rotate (0,0,WheelLB.rpm / 60 * -360 * Time.deltaTime);
WheelRBTransform.Rotate (0,0,WheelRB.rpm / 60 * -360 * Time.deltaTime);
//Apply the computed steer angle for front wheels
float newLFYAngle = WheelLF.steerAngle;
float newRFYAngle = WheelRF.steerAngle;
WheelLFTransform.localEulerAngles = new Vector3(WheelLFTransform.localEulerAngles.x, newLFYAngle, WheelLFTransform.localEulerAngles.z);
WheelRFTransform.localEulerAngles = new Vector3(WheelRFTransform.localEulerAngles.x, newRFYAngle, WheelRFTransform.localEulerAngles.z);
//Calculate and apply the position of wheel mesh
WheelPosition ();
//Calculate and apply the position and angle of the axles
AxlePosition ();
//If player ran out of oxygen, the game is over
if(this.oxygen<=0f)
{
endLevel=true;
endUIScript.Oxygenfail();
}
}
void WheelPosition()
{
RaycastHit hit;
Vector3 wheelPos = new Vector3();
//Calculate if the wheels touche the floor.
if (Physics.Raycast(WheelLF.transform.position, -WheelLF.transform.up, out hit, WheelLF.radius+WheelLF.suspensionDistance) )
{
//The wheel touches the floor, hit correspond to the contact point
//Calculate the position of the Wheel to display properly
wheelPos = hit.point+WheelLF.transform.up * WheelLF.radius;
ElevationLF = hit.distance;
prLF.maxParticleSize = currentSpeed/100*particleSize;
//If the vehicle is braking and the wheel touches the floor, the smog becomes heavier
if(isbraking)
{
prLF.maxParticleSize *= brakeSmogFactor;
peLF.maxSize = 6;
}
//If the vehicle is not braking, the particule have a normal size
else
{
peLF.maxSize = 3;
}
prLF.GetComponent<ParticleEmitter>().emit = true;
}
//If the Wheel does not touch the floor, the wheel is placed at the maximum suspension distance, and does not emit smog
else
{
wheelPos = WheelLF.transform.position -WheelLF.transform.up* WheelLF.suspensionDistance;
ElevationLF = WheelLF.suspensionDistance+WheelLF.radius;
prLF.GetComponent<ParticleEmitter>().emit = false;
}
WheelLFTransform.position = wheelPos;
if (Physics.Raycast(WheelRF.transform.position, -WheelRF.transform.up, out hit, WheelRF.radius+WheelRF.suspensionDistance) )
{
wheelPos = hit.point+WheelRF.transform.up * WheelRF.radius;
ElevationRF = hit.distance;
prRF.maxParticleSize = currentSpeed/100*particleSize;
if(isbraking)
{
prRF.maxParticleSize *= brakeSmogFactor;
peRF.maxSize = 6;
}
else
{
peRF.maxSize = 3;
}
prRF.GetComponent<ParticleEmitter>().emit = true;
}
else
{
wheelPos = WheelRF.transform.position -WheelRF.transform.up* WheelRF.suspensionDistance;
ElevationRF = WheelRF.suspensionDistance+WheelRF.radius;
prRF.GetComponent<ParticleEmitter>().emit = false;
}
WheelRFTransform.position = wheelPos;
if (Physics.Raycast(WheelLB.transform.position, -WheelLB.transform.up, out hit, WheelLB.radius+WheelLB.suspensionDistance) )
{
wheelPos = hit.point+WheelLB.transform.up * WheelLB.radius;
ElevationLB = hit.distance;
prLB.maxParticleSize = currentSpeed/100*particleSize;
prLB.GetComponent<ParticleEmitter>().emit = true;
}
else
{
wheelPos = WheelLB.transform.position -WheelLB.transform.up* WheelLB.suspensionDistance;
ElevationLB = WheelLB.suspensionDistance+WheelLB.radius;
prLB.GetComponent<ParticleEmitter>().emit = false;
}
WheelLBTransform.position = wheelPos;
if (Physics.Raycast(WheelRB.transform.position, -WheelRB.transform.up, out hit, WheelRB.radius+WheelRB.suspensionDistance) )
{
wheelPos = hit.point+WheelRB.transform.up * WheelRB.radius;
ElevationRB = hit.distance;
prRB.maxParticleSize = currentSpeed/100*particleSize;
prRB.GetComponent<ParticleEmitter>().emit = true;
}
else
{
wheelPos = WheelRB.transform.position -WheelRB.transform.up* WheelRB.suspensionDistance;
ElevationRB = WheelRB.suspensionDistance+WheelRB.radius;
prRB.GetComponent<ParticleEmitter>().emit = false;
}
WheelRBTransform.position = wheelPos;
}
//Put the axle with the correct angle, following the wheels
void AxlePosition()
{
//Back Axle - Compute angle and position of back axle to join the two wheels according to the suspensions
BackAltitudeDifference = ElevationLB-ElevationRB;
BackLatitudeDifference = Mathf.Abs(WheelRBTransform.transform.localPosition.z-WheelLBTransform.transform.localPosition.z);
BackAngle = Mathf.Atan (BackAltitudeDifference / BackLatitudeDifference) * Mathf.Rad2Deg;
AxleBack.localEulerAngles = new Vector3(0,0,BackAngle);
AxleBack.localPosition = new Vector3 (offsetAxleB.x, offsetAxleB.y - ElevationLB + WheelLB.radius, offsetAxleB.z);
//Front Axle - Compute angle and position of back axle to join the two wheels according to the suspensions
FrontAltitudeDifference = ElevationLF-ElevationRF;
FrontLatitudeDifference = Mathf.Abs(WheelRFTransform.transform.localPosition.z-WheelLFTransform.transform.localPosition.z);
FrontAngle = Mathf.Atan (FrontAltitudeDifference / FrontLatitudeDifference) * Mathf.Rad2Deg;
AxleFront.localEulerAngles = new Vector3(0,0,FrontAngle);
AxleFront.localPosition = new Vector3 (offsetAxleF.x, offsetAxleF.y - ElevationLF + WheelLF.radius, offsetAxleF.z);
}
//Calculate the external wheel angle corresponding to the internal in order to get a perfect direction for a vehicle
//(Epure d'Ackermann)
float getExternalWheelAngle(float internalAngle, float verticalWheelBase, float horizontalWheelBase)
{
return Mathf.Rad2Deg*Mathf.Atan(verticalWheelBase/((verticalWheelBase/Mathf.Tan(Mathf.Deg2Rad*internalAngle))+horizontalWheelBase));
}
}
| |
using System;
using AppUtil;
using Vim25Api;
using System.Web.Services.Protocols;
namespace WeeklyRecurrenceScheduledTask
{
public class WeeklyRecurrenceScheduledTask
{
private static AppUtil.AppUtil cb = null;
private VimService _service; // All webservice methods
// ServiceContent contains References to commonly used
// Managed Objects like PropertyCollector, SearchIndex, EventManager, etc.
private ServiceContent _sic;
private ManagedObjectReference _searchIndex;
private ManagedObjectReference _scheduleManager;
/**
* Initialize the necessary Managed Object References needed here
*/
private void initialize()
{
_sic = cb.getConnection()._sic;
_service = cb.getConnection()._service;
// Get the SearchIndex and ScheduleManager references from ServiceContent
_searchIndex = _sic.searchIndex;
_scheduleManager = _sic.scheduledTaskManager;
}
private ManagedObjectReference _virtualMachine;
/**
* Use the SearchIndex to find a VirtualMachine by Inventory Path
*
* @
*/
private void findVirtualMachine()
{
String vmPath = cb.get_option("vmpath");
_virtualMachine = _service.FindByInventoryPath(_searchIndex, vmPath);
}
/**
* Create method action to reboot the guest in a vm
*
* @return the action to run when the schedule runs
*/
private Vim25Api.Action createTaskAction()
{
MethodAction action = new MethodAction();
// Method Name is the WSDL name of the
// ManagedObject's method to be run, in this Case,
// the rebootGuest method for the VM
action.name = "RebootGuest";
// There are no arguments to this method
// so we pass in an empty MethodActionArgument
action.argument = new MethodActionArgument[] { };
return action;
}
/**
* Create a Weekly task scheduler to run
* at 11:59 pm every Saturday
*
* @return weekly task scheduler
*/
private TaskScheduler createTaskScheduler()
{
WeeklyTaskScheduler scheduler = new WeeklyTaskScheduler();
// Set the Day of the Week to be Saturday
scheduler.saturday = true;
// Set the Time to be 23:59 hours or 11:59 pm
scheduler.hour = 23;
scheduler.minute = 59;
// set the interval to 1 to run the task only
// Once every Week at the specified time
scheduler.interval = 1;
return scheduler;
}
/**
* Create a Scheduled Task using the reboot method action and
* the weekly scheduler, for the VM found.
*
* @param taskAction action to be performed when schedule executes
* @param scheduler the scheduler used to execute the action
* @
*/
private void createScheduledTask(Vim25Api.Action taskAction,
TaskScheduler scheduler)
{
try
{
// Create the Scheduled Task Spec and set a unique task name
// and description, and enable the task as soon as it is created
String taskName = cb.get_option("taskname");
ScheduledTaskSpec scheduleSpec = new ScheduledTaskSpec();
scheduleSpec.name = taskName;
scheduleSpec.description = "Reboot VM's Guest at 11.59pm every Saturday";
scheduleSpec.enabled = true;
// Set the RebootGuest Method Task action and
// the Weekly scheduler in the spec
scheduleSpec.action = taskAction;
scheduleSpec.scheduler = scheduler;
// Create the ScheduledTask for the VirtualMachine we found earlier
ManagedObjectReference task =
_service.CreateScheduledTask(
_scheduleManager, _virtualMachine, scheduleSpec);
// printout the MoRef id of the Scheduled Task
Console.WriteLine("Successfully created Weekly Task: " +
taskName);
}
catch (SoapException e)
{
if (e.Detail.FirstChild.LocalName.Equals("InvalidRequestFault"))
{
Console.WriteLine(" InvalidRequest: vmPath may be wrong");
}
else if (e.Detail.FirstChild.LocalName.Equals("DuplicateNameFault"))
{
Console.WriteLine("Task Name already Exists");
}
}
catch (Exception e)
{
Console.WriteLine("Error");
e.StackTrace.ToString();
}
}
private static OptionSpec[] constructOptions()
{
OptionSpec[] useroptions = new OptionSpec[2];
useroptions[0] = new OptionSpec("vmpath", "String", 1
, "VM Inventory Path"
, null);
useroptions[1] = new OptionSpec("taskname", "String", 1,
"Name of the task to be scheduled",
null);
return useroptions;
}
/**
* The main entry point for the application.
* @param args Arguments: <url> <user> <password> <A VM Inventory Path>
*/
public static void Main(String[] args)
{
try
{
WeeklyRecurrenceScheduledTask schedTask = new WeeklyRecurrenceScheduledTask();
cb = AppUtil.AppUtil.initialize("WeeklyRecurrenceScheduledTask"
, WeeklyRecurrenceScheduledTask.constructOptions()
, args);
// Connect to the Service and initialize
// any required ManagedObjectReferences
cb.connect();
schedTask.initialize();
// find the VM by dns name to create a scheduled task for
schedTask.findVirtualMachine();
// create the power Off action to be scheduled
Vim25Api.Action taskAction = schedTask.createTaskAction();
// create a One time scheduler to run
TaskScheduler taskScheduler = schedTask.createTaskScheduler();
// Create Scheduled Task
schedTask.createScheduledTask(taskAction,
taskScheduler);
// Disconnect from the WebService
cb.disConnect();
Console.WriteLine("Press any key to exit: ");
Console.Read();
}
catch (Exception e)
{
Console.WriteLine("Caught Exception : " +
" Name : " + e.Data.ToString() +
" Message : " + e.Message.ToString() +
" Trace : ");
e.StackTrace.ToString();
}
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.IO;
using System.Net.Mail;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.Win32;
using WebsitePanel.Server.Utils;
namespace WebsitePanel.Providers.Mail
{
public class IceWarp : HostingServiceProviderBase, IMailServer, IDisposable
{
protected const string API_PROGID = "IceWarpServer.APIObject";
protected const string DOMAIN_PROGID = "IceWarpServer.DomainObject";
protected const string ACCOUNT_PROGID = "IceWarpServer.AccountObject";
private dynamic _currentApiObject = null;
#region Protected Enums
protected enum IceWarpErrorCode
{
S_OK = 0,
E_FAILURE = -1, // Function failure
E_LICENSE = -2, // Insufficient license
E_PARAMS = -3, // Size of parameters too short
E_PATH = -4, // Settings file does not exist
E_CONFIG = -5, // Configuration not found
E_PASSWORD = -6, // Password policy
E_CONFLICT = -7, // Item already exists
E_INVALID = -8, // Invalid mailbox / alias characters
E_PASSWORDCHARS = -9, // Invalid password characters
E_MIGRATION_IN_PROGRESS = -10 // User migration in progress
}
protected enum IceWarpAccountType
{
User = 0,
MailingList = 1,
Executable = 2,
Notification = 3,
StaticRoute = 4,
Catalog = 5,
ListServer = 6,
UserGroup = 7
}
protected enum IceWarpUnknownUsersType
{
Reject = 0,
ForwardToAddress = 1,
Delete = 2
}
#endregion
#region Protected Properties
protected string MailPath
{
get
{
var apiObject = GetApiObject();
return apiObject.GetProperty("C_System_Storage_Dir_MailPath");
}
}
protected string Version
{
get
{
var apiObject = GetApiObject();
return apiObject.GetProperty("C_Version");
}
}
protected string BindIpAddress
{
get
{
var apiObject = GetApiObject();
var adresses = ((object)apiObject.GetProperty("C_System_Services_BindIPAddress"));
return adresses == null ? "" : adresses.ToString().Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
}
}
protected bool UseDomainDiskQuota
{
get
{
var apiObject = GetApiObject();
return Convert.ToBoolean((object)apiObject.GetProperty("C_Accounts_Global_Domains_UseDiskQuota"));
}
}
protected bool UseDomainLimits
{
get
{
var apiObject = GetApiObject();
return Convert.ToBoolean((object)apiObject.GetProperty("C_Accounts_Global_Domains_UseDomainLimits"));
}
}
protected bool UseUserLimits
{
get
{
var apiObject = GetApiObject();
return Convert.ToBoolean((object)apiObject.GetProperty("C_Accounts_Global_Domains_UseUserLimits"));
}
}
protected bool OverrideGlobal
{
get
{
var apiObject = GetApiObject();
return Convert.ToBoolean((object)apiObject.GetProperty("C_Accounts_Global_Domains_OverrideGlobal"));
}
}
protected int MaxMessageSizeInMB
{
get
{
var apiObject = GetApiObject();
return Convert.ToInt32((object)apiObject.GetProperty("C_Mail_SMTP_Delivery_MaxMsgSize")) / 1024 / 1024;
}
}
protected int WarnMailboxUsage
{
get
{
var apiObject = GetApiObject();
return Convert.ToInt32((object)apiObject.GetProperty("C_Accounts_Global_Domains_WarnMailboxUsage"));
}
}
protected int WarnDomainSize
{
get
{
var apiObject = GetApiObject();
return Convert.ToInt32((object)apiObject.GetProperty("C_Accounts_Global_Domains_WarnDomainSize"));
}
}
private void SaveApiSetting(dynamic apiObject)
{
if (!apiObject.Save())
{
var ex = new Exception("Cannot save Api Object: " + GetErrorMessage(apiObject.LastErr));
Log.WriteError(ex);
throw ex;
}
}
#endregion
#region Protected Methods
protected static string GetErrorMessage(int errorCode)
{
switch ((IceWarpErrorCode)errorCode)
{
case IceWarpErrorCode.S_OK:
return "OK";
case IceWarpErrorCode.E_FAILURE:
return "Function failure";
case IceWarpErrorCode.E_LICENSE:
return "Insufficient license";
case IceWarpErrorCode.E_PARAMS:
return "Size of parameters too short";
case IceWarpErrorCode.E_PATH:
return "Settings file does not exist";
case IceWarpErrorCode.E_CONFIG:
return "Configuration not found";
case IceWarpErrorCode.E_PASSWORD:
return "IceWarp password policy denies use of this account";
case IceWarpErrorCode.E_CONFLICT:
return "Item already exists";
case IceWarpErrorCode.E_INVALID:
return "Invalid characters in mailbox or alias";
case IceWarpErrorCode.E_PASSWORDCHARS:
return "Invalid characters in password";
case IceWarpErrorCode.E_MIGRATION_IN_PROGRESS:
return "User migration in progress";
default:
return "";
}
}
protected object CreateObject(string progId)
{
var associatedType = Type.GetTypeFromProgID(progId);
if (associatedType == null)
{
throw new Exception("Cannot get type of " + progId);
}
try
{
var obj = Activator.CreateInstance(associatedType);
if (obj == null)
{
throw new Exception("Unable to create COM interface");
}
return obj;
}
catch (Exception ex)
{
throw new Exception("Unable to create COM interface", ex);
}
}
protected void DisposeObject(object obj)
{
Marshal.FinalReleaseComObject(obj);
}
protected dynamic GetApiObject()
{
if (_currentApiObject != null) return _currentApiObject;
_currentApiObject = CreateObject(API_PROGID);
if (_currentApiObject == null)
{
throw new Exception("Returned COM is not of appropriate type");
}
return _currentApiObject;
}
protected dynamic GetDomainObject()
{
var obj = CreateObject(DOMAIN_PROGID);
if (obj == null)
{
throw new Exception("Returned COM is not of appropriate type");
}
return obj;
}
protected dynamic GetDomainObject(string domainName)
{
var obj = GetDomainObject();
if (!obj.Open(domainName))
{
throw new Exception("Cannot open domain " + domainName + ": " + GetErrorMessage(obj.LastErr));
}
return obj;
}
protected dynamic GetAccountObject()
{
var obj = CreateObject(ACCOUNT_PROGID);
if (obj == null)
{
throw new Exception("Returned COM is not of appropriate type");
}
return obj;
}
protected dynamic GetAccountObject(string accountName)
{
var obj = GetAccountObject();
if (!obj.Open(accountName))
{
Log.WriteWarning(string.Format("Cannot open account {0}: {1}", accountName, GetErrorMessage(obj.LastErr)));
}
return obj;
}
protected void SaveDomain(dynamic domain)
{
if (!domain.Save())
{
var ex = new Exception("Could not save domain:" + GetErrorMessage(domain.LastErr));
Log.WriteError(ex);
throw ex;
}
}
protected void SaveAccount(dynamic account, string accountTypeName = "account")
{
if (!account.Save())
{
var ex = new Exception(string.Format("Could not save {0}: {1}", accountTypeName, GetErrorMessage(account.LastErr)));
Log.WriteError(ex);
throw ex;
}
}
protected string GetEmailUser(string email)
{
if (string.IsNullOrWhiteSpace(email))
{
return string.Empty;
}
try
{
return new MailAddress(email).User;
}
catch
{
return email.Contains('@') ? email.Substring(0, email.IndexOf('@')) : string.Empty;
}
}
protected string GetEmailDomain(string email)
{
if (string.IsNullOrWhiteSpace(email))
{
return string.Empty;
}
try
{
return new MailAddress(email).Host;
}
catch
{
return email.Contains('@') ? email.Substring(email.IndexOf('@') + 1) : string.Empty;
}
}
protected void CheckIfDomainExists(string domainName)
{
if (string.IsNullOrWhiteSpace(domainName) || !DomainExists(domainName))
{
throw new ArgumentException("Specified domain does not exist!");
}
}
protected int GetDomainCount()
{
var apiObject = GetApiObject();
return apiObject.GetDomainCount();
}
protected T[] GetItems<T>(string domainName, IceWarpAccountType itemType, Func<dynamic, T> mailAccountCreator)
{
var mailAccounts = new List<T>();
var accountObject = GetAccountObject();
if (accountObject.FindInitQuery(domainName, "(U_Type = " + (int)itemType + ")"))
{
while (accountObject.FindNext())
{
mailAccounts.Add(mailAccountCreator(accountObject));
}
}
DisposeObject(accountObject);
return mailAccounts.ToArray();
}
protected void SaveProviderSettingsToService()
{
var apiObject = GetApiObject();
apiObject.SetProperty("C_Accounts_Global_Domains_UseDiskQuota", ProviderSettings["UseDomainDiskQuota"]);
apiObject.SetProperty("C_Accounts_Global_Domains_UseDomainLimits", ProviderSettings["UseDomainLimits"]);
apiObject.SetProperty("C_Accounts_Global_Domains_UseUserLimits", ProviderSettings["UseUserLimits"]);
apiObject.SetProperty("C_Accounts_Global_Domains_OverrideGlobal", ProviderSettings["OverrideGlobal"]);
apiObject.SetProperty("C_Accounts_Global_Domains_WarnMailboxUsage", ProviderSettings["WarnMailboxUsage"]);
apiObject.SetProperty("C_Accounts_Global_Domains_WarnDomainSize", ProviderSettings["WarnDomainSize"]);
apiObject.SetProperty("C_Mail_SMTP_Delivery_MaxMsgSize", Convert.ToInt32(ProviderSettings["MaxMessageSize"]) * 1024 * 1024);
apiObject.SetProperty("C_Mail_SMTP_Delivery_LimitMsgSize", Convert.ToInt32(ProviderSettings["MaxMessageSize"]) > 0);
SaveApiSetting(apiObject);
}
#endregion
#region IHostingServiceProvier methods
public override SettingPair[] GetProviderDefaultSettings()
{
var settings = new[]
{
new SettingPair("UseDomainDiskQuota", UseDomainDiskQuota.ToString()),
new SettingPair("UseDomainLimits", UseDomainLimits.ToString()),
new SettingPair("UseUserLimits", UseUserLimits.ToString()),
new SettingPair("OverrideGlobal", OverrideGlobal.ToString()),
new SettingPair("WarnMailboxUsage", WarnMailboxUsage.ToString()),
new SettingPair("WarnDomainSize", WarnDomainSize.ToString()),
new SettingPair("MaxMessageSize", MaxMessageSizeInMB.ToString()),
new SettingPair("ServerIpAddress", BindIpAddress)
};
return settings;
}
public override string[] Install()
{
SaveProviderSettingsToService();
return base.Install();
}
public override void ChangeServiceItemsState(ServiceProviderItem[] items, bool enabled)
{
foreach (var item in items.OfType<MailDomain>())
{
try
{
// enable/disable mail domain
if (DomainExists(item.Name))
{
var mailDomain = GetDomain(item.Name);
mailDomain.Enabled = enabled;
UpdateDomain(mailDomain);
}
}
catch (Exception ex)
{
Log.WriteError(String.Format("Error switching '{0}' IceWarp domain", item.Name), ex);
}
}
}
public override void DeleteServiceItems(ServiceProviderItem[] items)
{
foreach (var item in items.OfType<MailDomain>())
{
try
{
// delete mail domain
DeleteDomain(item.Name);
}
catch (Exception ex)
{
Log.WriteError(String.Format("Error deleting '{0}' IceWarp domain", item.Name), ex);
}
}
}
public override ServiceProviderItemDiskSpace[] GetServiceItemsDiskSpace(ServiceProviderItem[] items)
{
var itemsDiskspace = new List<ServiceProviderItemDiskSpace>();
var accountObject = GetAccountObject();
// update items with diskspace
foreach (var item in items.OfType<MailAccount>())
{
try
{
Log.WriteStart(String.Format("Calculating mail account '{0}' size", item.Name));
// calculate disk space
accountObject.Open(item.Name);
var size = Convert.ToInt64((object)accountObject.GetProperty("U_MailboxSize")) * 1024;
var diskspace = new ServiceProviderItemDiskSpace { ItemId = item.Id, DiskSpace = size };
itemsDiskspace.Add(diskspace);
Log.WriteEnd(String.Format("Calculating mail account '{0}' size", item.Name));
}
catch (Exception ex)
{
Log.WriteError(ex);
}
}
DisposeObject(accountObject);
return itemsDiskspace.ToArray();
}
public override ServiceProviderItemBandwidth[] GetServiceItemsBandwidth(ServiceProviderItem[] items, DateTime since)
{
var itemsBandwidth = new ServiceProviderItemBandwidth[items.Length];
// update items with bandwidth
for (var i = 0; i < items.Length; i++)
{
var item = items[i];
// create new bandwidth object
itemsBandwidth[i] = new ServiceProviderItemBandwidth
{
ItemId = item.Id,
Days = new DailyStatistics[0]
};
if (!(item is MailDomain)) continue;
try
{
// get daily statistics
itemsBandwidth[i].Days = GetDailyStatistics(since, item.Name);
}
catch (Exception ex)
{
Log.WriteError(ex);
System.Diagnostics.Debug.WriteLine(ex);
}
}
return itemsBandwidth;
}
public DailyStatistics[] GetDailyStatistics(DateTime since, string maildomainName)
{
var days = new List<DailyStatistics>();
var today = DateTime.Today;
try
{
var api = GetApiObject();
for (var date = since; date < today; date = date.AddDays(1))
{
var stats = api.GetUserStatistics(date.ToString("yyyy\"/\"MM\"/\"dd"), date.ToString("yyyy\"/\"MM\"/\"dd"), maildomainName);
var statsBuffer = Encoding.ASCII.GetBytes(stats);
var mailSentField = 0;
var mailReceivedField = 0;
var ms = new MemoryStream(statsBuffer);
var reader = new StreamReader(ms);
while (reader.Peek() > -1)
{
var line = reader.ReadLine();
var fields = line.Split(',');
switch (line[0])
{
case '[':
for (var j = 1; j < fields.Length; j++)
{
if (fields[j] == "[Received Amount]") mailReceivedField = j;
if (fields[j] == "[Sent Amount]") mailSentField = j;
}
break;
case '*':
var dailyStats = new DailyStatistics
{
Year = date.Year,
Month = date.Month,
Day = date.Day,
BytesSent = Convert.ToInt64(fields[mailSentField]) * 1024,
BytesReceived = Convert.ToInt64(fields[mailReceivedField]) * 1024
};
days.Add(dailyStats);
continue;
}
}
reader.Close();
ms.Close();
}
}
catch (Exception ex)
{
Log.WriteError("Could not get IceWarp domain statistics", ex);
}
return days.ToArray();
}
#endregion
public override bool IsInstalled()
{
string version;
var key32Bit = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\IceWarp\IceWarp Server");
if (key32Bit != null)
{
version = key32Bit.GetValue("Version").ToString();
}
else
{
var key64Bit = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Wow6432Node\IceWarp\IceWarp Server");
if (key64Bit != null)
{
version = key64Bit.GetValue("Version").ToString();
}
else
{
return false;
}
}
if (string.IsNullOrEmpty(version))
{
return false;
}
// Checking for version 10.4.0 (released 2012-03-21) or newer
// This version introduced L_ListFile_Contents, G_ListFile_Contents and M_ListFileContents that is the latest API variable used by this provider
var split = version.Split(new[] { '.' });
var majorVersion = Convert.ToInt32(split[0]);
var minVersion = Convert.ToInt32(split[1]);
return majorVersion >= 11 || majorVersion >= 10 && minVersion >= 4;
}
#region Domains
public bool DomainExists(string domainName)
{
var api = GetApiObject();
return api.GetDomainIndex(domainName) >= 0;
}
public string[] GetDomains()
{
var api = GetApiObject();
return api.GetDomainList().Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
}
public MailDomain GetDomain(string domainName)
{
var domainObject = GetDomainObject(domainName);
var mailDomain = new MailDomain
{
Name = domainObject.Name,
PostmasterAccount = domainObject.GetProperty("D_AdminEmail"),
CatchAllAccount = domainObject.GetProperty("D_UnknownForwardTo"),
Enabled = Convert.ToBoolean((object)domainObject.GetProperty("D_DisableLogin")),
MaxDomainSizeInMB = Convert.ToInt32((object)domainObject.GetProperty("D_DiskQuota")) / 1024,
MaxDomainUsers = Convert.ToInt32((object)domainObject.GetProperty("D_AccountNumber")),
MegaByteSendLimit = Convert.ToInt32((object)domainObject.GetProperty("D_VolumeLimit")) / 1024,
NumberSendLimit = Convert.ToInt32((object)domainObject.GetProperty("D_NumberLimit")),
DefaultUserQuotaInMB = Convert.ToInt32((object)domainObject.GetProperty("D_UserMailbox")) / 1024,
DefaultUserMaxMessageSizeMegaByte = Convert.ToInt32((object)domainObject.GetProperty("D_UserMsg")) / 1024,
DefaultUserMegaByteSendLimit = Convert.ToInt32((object)domainObject.GetProperty("D_UserMB")),
DefaultUserNumberSendLimit = Convert.ToInt32((object)domainObject.GetProperty("D_UserNumber")),
UseDomainDiskQuota = Convert.ToBoolean(ProviderSettings["UseDomainDiskQuota"]),
UseDomainLimits = Convert.ToBoolean(ProviderSettings["UseDomainLimits"]),
UseUserLimits = Convert.ToBoolean(ProviderSettings["UseUserLimits"])
};
DisposeObject(domainObject);
return mailDomain;
}
public void CreateDomain(MailDomain domain)
{
if (string.IsNullOrWhiteSpace(domain.Name))
{
var ex = new Exception("Cannot create domain with empty domain name", new ArgumentNullException("domain.Name"));
Log.WriteError(ex);
throw ex;
}
var domainObject = GetDomainObject();
if (!domainObject.New(domain.Name))
{
var ex = new Exception("Failed to create domain: " + GetErrorMessage(domainObject.LastErr));
Log.WriteError(ex);
throw ex;
}
SaveDomain(domainObject);
DisposeObject(domainObject);
UpdateDomain(domain);
}
public void UpdateDomain(MailDomain domain)
{
var domainObject = GetDomainObject(domain.Name);
domainObject.SetProperty("D_AdminEmail", string.IsNullOrEmpty(domain.PostmasterAccount) ? "" : domain.PostmasterAccount);
if (string.IsNullOrEmpty(domain.CatchAllAccount))
{
domainObject.SetProperty("D_UnknownForwardTo", "");
domainObject.SetProperty("D_UnknownUsersType", IceWarpUnknownUsersType.Reject);
}
else
{
domainObject.SetProperty("D_UnknownForwardTo", domain.CatchAllAccount);
domainObject.SetProperty("D_UnknownUsersType", IceWarpUnknownUsersType.ForwardToAddress);
}
domainObject.SetProperty("D_DisableLogin", !domain.Enabled);
domainObject.SetProperty("D_DiskQuota", domain.MaxDomainSizeInMB * 1024);
domainObject.SetProperty("D_AccountNumber", domain.MaxDomainUsers);
domainObject.SetProperty("D_VolumeLimit", domain.MegaByteSendLimit * 1024);
domainObject.SetProperty("D_NumberLimit", domain.NumberSendLimit);
domainObject.SetProperty("D_UserMailbox", domain.DefaultUserQuotaInMB * 1024);
domainObject.SetProperty("D_UserMsg", domain.DefaultUserMaxMessageSizeMegaByte * 1024);
domainObject.SetProperty("D_UserMB", domain.DefaultUserMegaByteSendLimit);
domainObject.SetProperty("D_UserNumber", domain.DefaultUserNumberSendLimit);
SaveDomain(domainObject);
DisposeObject(domainObject);
}
public void DeleteDomain(string domainName)
{
if (!DomainExists(domainName))
{
return;
}
var domainObject = GetDomainObject(domainName);
if (!domainObject.Delete())
{
Log.WriteError("Could not delete domain" + GetErrorMessage(domainObject.LastErr), null);
}
DisposeObject(domainObject);
}
#endregion
#region Domain aliases
public bool DomainAliasExists(string domainName, string aliasName)
{
if (!DomainExists(aliasName))
{
return false;
}
var domainObject = GetDomainObject(aliasName);
var result = Convert.ToInt32((object)domainObject.GetProperty("D_Type")) == 2 && string.Compare(domainObject.GetProperty("D_DomainValue").ToString(), domainName, true) == 0;
DisposeObject(domainObject);
return result;
}
public string[] GetDomainAliases(string domainName)
{
var aliasList = new List<string>();
var apiObject = GetApiObject();
var domainCount = apiObject.GetDomainCount();
for (var i = 0; i < domainCount; i++)
{
var aliasName = apiObject.GetDomain(i);
if (DomainAliasExists(domainName, aliasName))
{
aliasList.Add(aliasName);
}
}
return aliasList.ToArray();
}
public void AddDomainAlias(string domainName, string aliasName)
{
var mailDomain = new MailDomain { Name = aliasName };
CreateDomain(mailDomain);
var domainObject = GetDomainObject(aliasName);
domainObject.SetProperty("D_Type", 2);
domainObject.SetProperty("D_DomainValue", domainName);
SaveDomain(domainObject);
DisposeObject(domainObject);
}
public void DeleteDomainAlias(string domainName, string aliasName)
{
DeleteDomain(aliasName);
}
#endregion
#region Accounts
public bool AccountExists(string mailboxName)
{
var accountObject = GetAccountObject();
var result = accountObject.Open(mailboxName) && Convert.ToInt32((object)accountObject.GetProperty("U_Type")) == (int)IceWarpAccountType.User;
DisposeObject(accountObject);
return result;
}
protected class IceWarpResponderContent
{
public string From { get; set; }
public string To { get; set; }
public string Subject { get; set; }
public string Content { get; set; }
}
private static IceWarpResponderContent ParseResponderContent(string responderContent)
{
var result = new IceWarpResponderContent();
if (string.IsNullOrWhiteSpace(responderContent))
{
return result;
}
var re = new Regex(@"\$\$(set\w*) (.*)\$\$\n");
var matches = re.Matches(responderContent);
foreach (Match match in matches)
{
if (match.Groups[1].Value == "setsubject")
{
result.Subject = match.Groups[2].Value;
}
if (match.Groups[1].Value == "setactualto")
{
result.To = match.Groups[2].Value;
}
if (match.Groups[1].Value == "setactualfrom")
{
result.From = match.Groups[2].Value;
}
}
result.Content = re.Replace(responderContent, "");
return result;
}
protected MailAccount CreateMailAccountFromAccountObject(dynamic accountObject)
{
var mailAccount = new MailAccount
{
Name = accountObject.EmailAddress,
FullName = accountObject.GetProperty("U_Name"),
Enabled = Convert.ToInt32((object)accountObject.GetProperty("U_AccountDisabled")) == 0,
ForwardingEnabled = !string.IsNullOrWhiteSpace(accountObject.GetProperty("U_ForwardTo")) || string.IsNullOrWhiteSpace(accountObject.GetProperty("U_RemoteAddress")) && Convert.ToBoolean((object)accountObject.GetProperty("U_UseRemoteAddress")),
IsDomainAdmin = Convert.ToBoolean((object)accountObject.GetProperty("U_DomainAdmin")),
MaxMailboxSize = Convert.ToBoolean((object)accountObject.GetProperty("U_MaxBox")) ? Convert.ToInt32((object)accountObject.GetProperty("U_MaxBoxSize")) / 1024 : 0,
Password = accountObject.GetProperty("U_Password"),
ResponderEnabled = Convert.ToInt32((object)accountObject.GetProperty("U_Respond")) > 0,
QuotaUsed = Convert.ToInt64((object)accountObject.GetProperty("U_MailBoxSize")),
MaxMessageSizeMegaByte = Convert.ToInt32((object)accountObject.GetProperty("U_MaxMessageSize")) / 1024,
MegaByteSendLimit = Convert.ToInt32((object)accountObject.GetProperty("U_MegabyteSendLimit")),
NumberSendLimit = Convert.ToInt32((object)accountObject.GetProperty("U_NumberSendLimit")),
DeleteOlder = Convert.ToBoolean((object)accountObject.GetProperty("U_DeleteOlder")),
DeleteOlderDays = Convert.ToInt32((object)accountObject.GetProperty("U_DeleteOlderDays")),
ForwardOlder = Convert.ToBoolean((object)accountObject.GetProperty("U_ForwardOlder")),
ForwardOlderDays = Convert.ToInt32((object)accountObject.GetProperty("U_ForwardOlderDays")),
ForwardOlderTo = accountObject.GetProperty("U_ForwardOlderTo"),
IceWarpAccountState = Convert.ToInt32((object)accountObject.GetProperty("U_AccountDisabled")),
IceWarpAccountType = Convert.ToInt32((object)accountObject.GetProperty("U_AccountType")),
IceWarpRespondType = Convert.ToInt32((object)accountObject.GetProperty("U_Respond"))
};
if (mailAccount.ForwardingEnabled)
{
mailAccount.ForwardingAddresses = new string[] { accountObject.GetProperty("U_ForwardTo") + accountObject.GetProperty("U_RemoteAddress") };
mailAccount.DeleteOnForward = Convert.ToInt32(accountObject.GetProperty("U_UseRemoteAddress")) == 1;
mailAccount.RetainLocalCopy = !mailAccount.DeleteOnForward;
}
if (mailAccount.ResponderEnabled)
{
var respondFromValue = accountObject.GetProperty("U_RespondBetweenFrom");
var respondToValue = accountObject.GetProperty("U_RespondBetweenTo");
DateTime respondFrom;
DateTime respondTo;
mailAccount.RespondOnlyBetweenDates = false;
var fromDateParsed = DateTime.TryParse(respondFromValue, out respondFrom);
if (DateTime.TryParse(respondToValue, out respondTo) && fromDateParsed)
{
mailAccount.RespondOnlyBetweenDates = true;
mailAccount.RespondFrom = respondFrom;
mailAccount.RespondTo = respondTo;
}
mailAccount.RespondPeriodInDays = Convert.ToInt32((object)accountObject.GetProperty("U_RespondPeriod"));
var responderContent = ParseResponderContent(accountObject.GetProperty("U_ResponderContent"));
mailAccount.ResponderMessage = responderContent.Content;
mailAccount.ResponderSubject = responderContent.Subject;
mailAccount.RespondWithReplyFrom = responderContent.From;
}
return mailAccount;
}
public MailAccount[] GetAccounts(string domainName)
{
return GetItems(domainName, IceWarpAccountType.User, CreateMailAccountFromAccountObject);
}
public MailAccount GetAccount(string mailboxName)
{
var accountObject = GetAccountObject(mailboxName);
var account = CreateMailAccountFromAccountObject(accountObject);
DisposeObject(accountObject);
return account;
}
public void CreateAccount(MailAccount mailbox)
{
if (mailbox.MaxMailboxSize == -1)
{
mailbox.MaxMailboxSize = 0;
}
if (mailbox.MaxMessageSizeMegaByte == -1)
{
mailbox.MaxMessageSizeMegaByte = 0;
}
var accountObject = GetAccountObject();
var emailParts = new MailAddress(mailbox.Name);
if (!accountObject.CanCreateMailbox(emailParts.User, emailParts.User, mailbox.Password, emailParts.Host))
{
var ex = new Exception("Cannot create account because of password policy in IceWarp server, invalid username, alias or domain. Check if the password policy is different in IceWarp and WebsitePanel. Also perhaps your IceWarp disallows username in password?");
Log.WriteError(ex);
throw ex;
}
if (accountObject.New(mailbox.Name))
{
accountObject.SetProperty("U_Password", mailbox.Password);
accountObject.Save();
UpdateAccount(mailbox);
}
DisposeObject(accountObject);
}
public void UpdateAccount(MailAccount mailbox)
{
var accountObject = GetAccountObject(mailbox.Name);
accountObject.SetProperty("U_Name", mailbox.FullName);
accountObject.SetProperty("U_AccountDisabled", mailbox.IceWarpAccountState);
accountObject.SetProperty("U_DomainAdmin", mailbox.IsDomainAdmin);
accountObject.SetProperty("U_Password", mailbox.Password);
accountObject.SetProperty("U_MaxBoxSize", mailbox.MaxMailboxSize * 1024);
accountObject.SetProperty("U_MaxBox", mailbox.MaxMailboxSize > 0 ? "1" : "0");
accountObject.SetProperty("U_MaxMessageSize", mailbox.MaxMessageSizeMegaByte * 1024);
accountObject.SetProperty("U_MegabyteSendLimit", mailbox.MegaByteSendLimit);
accountObject.SetProperty("U_NumberSendLimit", mailbox.NumberSendLimit);
accountObject.SetProperty("U_AccountType", mailbox.IceWarpAccountType);
accountObject.SetProperty("U_Respond", mailbox.IceWarpRespondType);
accountObject.SetProperty("U_DeleteOlder", mailbox.DeleteOlder);
accountObject.SetProperty("U_DeleteOlderDays", mailbox.DeleteOlderDays);
accountObject.SetProperty("U_ForwardOlder", mailbox.ForwardOlder);
accountObject.SetProperty("U_ForwardOlderDays", mailbox.ForwardOlderDays);
accountObject.SetProperty("U_ForwardOlderTo", mailbox.ForwardOlderTo);
// Set initial defalt values for forwarding
accountObject.SetProperty("U_RemoteAddress", null);
accountObject.SetProperty("U_ForwardTo", null);
accountObject.SetProperty("U_UseRemoteAddress", false);
if (mailbox.ForwardingEnabled)
{
if (mailbox.DeleteOnForward)
{
accountObject.SetProperty("U_RemoteAddress", string.Join(";", mailbox.ForwardingAddresses));
accountObject.SetProperty("U_UseRemoteAddress", true);
}
else
{
accountObject.SetProperty("U_ForwardTo", string.Join(";", mailbox.ForwardingAddresses));
}
}
if (mailbox.IceWarpRespondType > 0)
{
if (mailbox.RespondOnlyBetweenDates)
{
accountObject.SetProperty("U_RespondBetweenFrom", mailbox.RespondFrom.ToShortDateString());
accountObject.SetProperty("U_RespondBetweenTo", mailbox.RespondTo.ToShortDateString());
}
else
{
accountObject.SetProperty("U_RespondBetweenFrom", null);
accountObject.SetProperty("U_RespondBetweenTo", null);
}
accountObject.SetProperty("U_RespondPeriod", mailbox.RespondPeriodInDays);
var responderContent = "";
if (!string.IsNullOrWhiteSpace(mailbox.RespondWithReplyFrom))
{
responderContent += "$$setactualfrom " + mailbox.RespondWithReplyFrom + "$$\n";
}
if (!string.IsNullOrWhiteSpace(mailbox.ResponderSubject))
{
responderContent += "$$setsubject " + mailbox.ResponderSubject + "$$\n";
}
accountObject.SetProperty("U_ResponderContent", responderContent + mailbox.ResponderMessage);
}
SaveAccount(accountObject);
DisposeObject(accountObject);
}
public void DeleteAccount(string mailboxName)
{
if (!AccountExists(mailboxName))
{
return;
}
var accountObject = GetAccountObject(mailboxName);
if (!accountObject.Delete())
{
Log.WriteError("Cannot delete account: " + GetErrorMessage(accountObject.LastErr), null);
}
DisposeObject(accountObject);
}
#endregion
#region Mail aliases
public bool MailAliasExists(string mailAliasName)
{
var accountObject = GetAccountObject();
var result = accountObject.Open(mailAliasName);
DisposeObject(accountObject);
return result;
}
protected IEnumerable<string> GetAliasListFromAccountObject(dynamic accountObject)
{
return SplitStringProperty(accountObject, "U_EmailAlias", ';');
}
protected string GetForwardToAddressFromAccountObject(dynamic accountObject)
{
var forwardTo = accountObject.EmailAddress;
var remoteAddress = accountObject.GetProperty("U_RemoteAddress");
if (!string.IsNullOrWhiteSpace(remoteAddress))
{
forwardTo = remoteAddress;
}
return forwardTo;
}
public MailAlias[] GetMailAliases(string domainName)
{
var aliasList = new List<MailAlias>();
var accountObject = GetAccountObject();
if (accountObject.FindInitQuery(domainName, "U_Type=" + (int)IceWarpAccountType.User))
{
while (accountObject.FindNext())
{
var forwardTo = GetForwardToAddressFromAccountObject(accountObject);
var aliases = GetAliasListFromAccountObject(accountObject) as IEnumerable<string>;
aliasList.AddRange(aliases.Where(a => a + "@" + domainName != forwardTo).Select(alias => new MailAlias { Name = alias + "@" + domainName, ForwardTo = forwardTo }));
}
accountObject.FindDone();
}
DisposeObject(accountObject);
return aliasList.ToArray();
}
public MailAlias GetMailAlias(string mailAliasName)
{
var accountObject = GetAccountObject(mailAliasName);
var forwardTo = GetForwardToAddressFromAccountObject(accountObject);
var result = new MailAlias { ForwardTo = forwardTo, Name = mailAliasName };
DisposeObject(accountObject);
return result;
}
public void CreateMailAlias(MailAlias mailAlias)
{
// If not forwardto-address exists or is in another domain, create a new account with remoteaddress
if (!GetEmailDomain(mailAlias.Name).Equals(GetEmailDomain(mailAlias.ForwardTo), StringComparison.InvariantCultureIgnoreCase) || !AccountExists(mailAlias.ForwardTo))
{
mailAlias.ForwardingEnabled = true;
mailAlias.DeleteOnForward = true;
mailAlias.ForwardingAddresses = new[] { mailAlias.ForwardTo };
mailAlias.Password = GetRandomPassword();
CreateAccount(mailAlias);
}
// else open account and add alias to list
else
{
var accountObject = GetAccountObject(mailAlias.ForwardTo);
var aliases = ((IEnumerable<string>)GetAliasListFromAccountObject(accountObject)).ToList();
aliases.Add(GetEmailUser(mailAlias.Name));
accountObject.SetProperty("U_EmailAlias", string.Join(";", aliases));
SaveAccount(accountObject, "account when creating mail alias");
DisposeObject(accountObject);
}
}
private static string GetRandowChars(string chars, int length)
{
var random = new Random();
return new string(Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)]).ToArray());
}
protected string GetRandomPassword()
{
var apiObject = GetApiObject();
var minLength = apiObject.GetProperty("C_Accounts_Policies_Pass_MinLength");
var digits = apiObject.GetProperty("C_Accounts_Policies_Pass_Digits");
var nonAlphaNum = apiObject.GetProperty("C_Accounts_Policies_Pass_NonAlphaNum");
var alpha = apiObject.GetProperty("C_Accounts_Policies_Pass_Alpha");
return System.Web.Security.Membership.GeneratePassword(minLength, nonAlphaNum) +
GetRandowChars("0123456789", digits) +
GetRandowChars("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", alpha);
}
public void UpdateMailAlias(MailAlias mailAlias)
{
// Delete alias based on mailAlias.Name
DeleteMailAlias(mailAlias.Name);
// Recreate alias
CreateMailAlias(mailAlias);
}
public void DeleteMailAlias(string mailAliasName)
{
// Find account where alias exists
var accountObject = GetAccountObject(mailAliasName);
// Check if it has any other aliases
var otherAliases = ((IEnumerable<string>)GetAliasListFromAccountObject(accountObject)).Where(a => a != GetEmailUser(mailAliasName)).ToArray();
if (otherAliases.Any())
{
accountObject.SetProperty("U_EmailAlias", string.Join(";", otherAliases));
SaveAccount(accountObject, "account during alias delete");
}
// If no other aliases, this should be an account with a remote address and then we should delete the account
else
{
DeleteAccount(mailAliasName);
}
DisposeObject(accountObject);
}
#endregion
#region Groups
public bool GroupExists(string groupName)
{
var accountObject = GetAccountObject();
var result = accountObject.Open(groupName) && (IceWarpAccountType)Enum.Parse(typeof(IceWarpAccountType), ((object)accountObject.GetProperty("U_Type")).ToString()) == IceWarpAccountType.UserGroup;
DisposeObject(accountObject);
return result;
}
public MailGroup[] GetGroups(string domainName)
{
return GetItems(domainName, IceWarpAccountType.UserGroup, CreateMailGroupFromAccountObject);
}
protected MailGroup CreateMailGroupFromAccountObject(dynamic accountObject)
{
var mailGroup = new MailGroup
{
Name = accountObject.EmailAddress,
Enabled = Convert.ToInt32((object)accountObject.GetProperty("U_AccountDisabled")) == 0,
GroupName = accountObject.GetProperty("G_Name"),
Members = ((IEnumerable<string>)SplitFileContents(accountObject, "G_ListFile_Contents")).ToArray()
};
return mailGroup;
}
public MailGroup GetGroup(string groupName)
{
var accountObject = GetAccountObject(groupName);
var result = CreateMailGroupFromAccountObject(accountObject);
DisposeObject(accountObject);
return result;
}
public void CreateGroup(MailGroup @group)
{
var accountObject = GetAccountObject();
if (accountObject.New(group.Name))
{
accountObject.SetProperty("U_Type", IceWarpAccountType.UserGroup);
accountObject.SetProperty("G_GroupwareMailDelivery", false);
SaveAccount(accountObject, "group account");
}
else
{
Log.WriteError("Failed to create group: " + GetErrorMessage(accountObject.LastErr), null);
}
UpdateGroup(group);
DisposeObject(accountObject);
}
public void UpdateGroup(MailGroup @group)
{
var accountObject = GetAccountObject(group.Name);
accountObject.SetProperty("G_Name", group.GroupName);
accountObject.SetProperty("U_AccountDisabled", group.Enabled ? 0 : 2);
accountObject.SetProperty("G_ListFile_Contents", string.Join("\n", group.Members));
SaveAccount(accountObject, "group");
DisposeObject(accountObject);
}
public void DeleteGroup(string groupName)
{
if (!GroupExists(groupName))
{
return;
}
var accountObject = GetAccountObject(groupName);
if (!accountObject.Delete())
{
Log.WriteError("Cannot delete group: " + GetErrorMessage(accountObject.LastErr), null);
}
DisposeObject(accountObject);
}
#endregion
#region Lists
public bool ListExists(string maillistName)
{
var accountObject = GetAccountObject();
var result = accountObject.Open(maillistName) && (IceWarpAccountType)Enum.Parse(typeof(IceWarpAccountType), ((object)accountObject.GetProperty("U_Type")).ToString()) == IceWarpAccountType.MailingList;
DisposeObject(accountObject);
return result;
}
public MailList[] GetLists(string domainName)
{
return GetItems(domainName, IceWarpAccountType.MailingList, CreateMailListFromAccountObject);
}
protected IEnumerable<string> SplitStringProperty(dynamic accountObject, string propertyName, char separator)
{
var value = (object)accountObject.GetProperty(propertyName);
return value == null ? new String[] { } : value.ToString().Split(new[] { separator }, StringSplitOptions.RemoveEmptyEntries);
}
protected IEnumerable<string> SplitFileContents(dynamic accountObject, string propertyName)
{
return SplitStringProperty(accountObject, propertyName, '\n');
}
protected MailList CreateMailListFromAccountObject(dynamic accountObject)
{
// IceWarp has separate settings for list server and mailing list. Together they have all the info we need for a WSP MailList
// From an accountObject of type list server, we can fetch the mailing lists associated with it
// So, first we search and find the list server account that is associated with this mailing list account.
var listServerAccountObject = FindMatchingListServerAccount(accountObject.EmailAddress, true);
var mailList = new MailList
{
//From mailing list account
Name = accountObject.EmailAddress,
Description = accountObject.GetProperty("M_Name"),
ModeratorAddress = accountObject.GetProperty("M_OwnerAddress"),
MembersSource = (IceWarpListMembersSource)Enum.Parse(typeof(IceWarpListMembersSource), ((object)accountObject.GetProperty("M_SendAllLists")).ToString()),
Members = ((IEnumerable<string>)SplitFileContents(accountObject, "M_ListFile_Contents")).Select(m => m.TrimEnd(new[] { ';', '0', '1', '2' })).ToArray(),
SetReceipientsToToHeader = Convert.ToBoolean((object)accountObject.GetProperty("M_SeparateTo")),
SubjectPrefix = accountObject.GetProperty("M_AddToSubject"),
Originator = (IceWarpListOriginator)Enum.Parse(typeof(IceWarpListOriginator), ((object)accountObject.GetProperty("M_ListSender")).ToString()),
PostingMode = Convert.ToBoolean((object)accountObject.GetProperty("M_MembersOnly")) ? PostingMode.MembersCanPost : PostingMode.AnyoneCanPost,
PasswordProtection = (PasswordProtection)Enum.Parse(typeof(PasswordProtection), ((object)accountObject.GetProperty("M_Moderated")).ToString()),
Password = accountObject.GetProperty("M_ModeratedPassword"),
DefaultRights = (IceWarpListDefaultRights)Enum.Parse(typeof(IceWarpListDefaultRights), ((object)accountObject.GetProperty("M_DefaultRights")).ToString()),
MaxMessageSizeEnabled = Convert.ToBoolean((object)accountObject.GetProperty("M_MaxList")),
MaxMessageSize = Convert.ToInt32((object)accountObject.GetProperty("M_MaxListSize")),
MaxMembers = Convert.ToInt32((object)accountObject.GetProperty("M_MaxMembers")),
SendToSender = Convert.ToBoolean((object)accountObject.GetProperty("M_SendToSender")),
DigestMode = Convert.ToBoolean((object)accountObject.GetProperty("M_DigestConfirmed")),
MaxMessagesPerMinute = Convert.ToInt32((object)accountObject.GetProperty("M_ListBatch")),
SendSubscribe = Convert.ToBoolean((object)accountObject.GetProperty("M_NotifyJoin")),
SendUnsubscribe = Convert.ToBoolean((object)accountObject.GetProperty("M_NotifyLeave")),
// From list server account
ConfirmSubscription = (IceWarpListConfirmSubscription)Enum.Parse(typeof(IceWarpListConfirmSubscription), ((object)listServerAccountObject.GetProperty("L_DigestConfirmed")).ToString()),
CommandsInSubject = Convert.ToBoolean((object)listServerAccountObject.GetProperty("L_ListSubject")),
DisableSubscribecommand = !Convert.ToBoolean((object)listServerAccountObject.GetProperty("M_JoinR")),
AllowUnsubscribe = Convert.ToBoolean((object)listServerAccountObject.GetProperty("M_LeaveR")),
DisableListcommand = !Convert.ToBoolean((object)listServerAccountObject.GetProperty("M_ListsR")),
DisableWhichCommand = !Convert.ToBoolean((object)listServerAccountObject.GetProperty("M_WhichR")),
DisableReviewCommand = !Convert.ToBoolean((object)listServerAccountObject.GetProperty("M_ReviewR")),
DisableVacationCommand = !Convert.ToBoolean((object)listServerAccountObject.GetProperty("M_VacationR")),
Moderated = Convert.ToBoolean((object)listServerAccountObject.GetProperty("L_Moderated")),
CommandPassword = listServerAccountObject.GetProperty("L_ModeratedPassword"),
SuppressCommandResponses = Convert.ToBoolean((object)listServerAccountObject.GetProperty("L_MaxList"))
};
// This is how I get values for from and replyto header values. TODO: There must be a better way, but I don't see the pattern right now...
var ss = Convert.ToInt32((object)accountObject.GetProperty("M_SetSender"));
var sv = Convert.ToInt32((object)accountObject.GetProperty("M_SetValue"));
var vm = Convert.ToBoolean((object)accountObject.GetProperty("M_ValueMode"));
var value = accountObject.GetProperty("M_HeaderValue");
switch (ss)
{
case 0:
switch (sv)
{
case 0:
mailList.FromHeader = IceWarpListFromAndReplyToHeader.NoChange;
mailList.ReplyToHeader = IceWarpListFromAndReplyToHeader.NoChange;
break;
case 1:
if (vm)
{
mailList.FromHeader = IceWarpListFromAndReplyToHeader.NoChange;
mailList.ReplyToHeader = IceWarpListFromAndReplyToHeader.SetToValue;
mailList.ListReplyToAddress = value;
}
else
{
mailList.FromHeader = IceWarpListFromAndReplyToHeader.SetToValue;
mailList.ReplyToHeader = IceWarpListFromAndReplyToHeader.NoChange;
mailList.ListFromAddress = value;
}
break;
case 2:
mailList.FromHeader = IceWarpListFromAndReplyToHeader.SetToValue;
mailList.ReplyToHeader = IceWarpListFromAndReplyToHeader.SetToValue;
var values = value.Split('|');
mailList.ListFromAddress = values[0];
mailList.ListReplyToAddress = values[1];
break;
}
break;
case 1:
switch (sv)
{
case 0:
mailList.FromHeader = IceWarpListFromAndReplyToHeader.SetToSender;
mailList.ReplyToHeader = IceWarpListFromAndReplyToHeader.NoChange;
break;
case 1:
if (vm)
{
mailList.FromHeader = IceWarpListFromAndReplyToHeader.SetToSender;
mailList.ReplyToHeader = IceWarpListFromAndReplyToHeader.SetToValue;
mailList.ListReplyToAddress = value;
}
else
{
mailList.FromHeader = IceWarpListFromAndReplyToHeader.SetToValue;
mailList.ReplyToHeader = IceWarpListFromAndReplyToHeader.SetToSender;
mailList.ListFromAddress = value;
}
break;
}
break;
case 2:
mailList.FromHeader = IceWarpListFromAndReplyToHeader.SetToSender;
mailList.ReplyToHeader = IceWarpListFromAndReplyToHeader.SetToSender;
break;
}
DisposeObject(listServerAccountObject);
return mailList;
}
public MailList GetList(string maillistName)
{
var accountObject = GetAccountObject(maillistName);
var result = CreateMailListFromAccountObject(accountObject);
DisposeObject(accountObject);
return result;
}
public void CreateList(MailList maillist)
{
if (string.IsNullOrWhiteSpace(maillist.Name))
{
var ex = new ArgumentNullException("maillist.Name", "Cannot create list with empty name");
Log.WriteError(ex);
throw ex;
}
var accountObject = GetAccountObject();
if (!accountObject.New(maillist.Name))
{
var ex = new Exception("Failed to create mailing list: " + GetErrorMessage(accountObject.LastErr));
Log.WriteError(ex);
throw ex;
}
accountObject.SetProperty("U_Type", IceWarpAccountType.MailingList);
SaveAccount(accountObject, "mailing list");
UpdateList(maillist);
DisposeObject(accountObject);
}
protected dynamic FindMatchingListServerAccount(string mailingListName, bool createListServerAccountIfNeeded)
{
var listServerAccountObject = GetAccountObject();
var forceCreatelistServerAccountObject = false;
var listServerAccountFound = false;
if (listServerAccountObject.FindInitQuery(GetEmailDomain(mailingListName), "U_Type=" + (int)IceWarpAccountType.ListServer))
{
while (listServerAccountObject.FindNext())
{
var lists = ((IEnumerable<string>)SplitFileContents(listServerAccountObject, "L_ListFile_Contents")).ToList();
if (lists.Contains(mailingListName))
{
listServerAccountFound = true;
// If this list server account is responsible for more than one mailing list, force creation of a new one.
if (lists.Count() > 1)
{
forceCreatelistServerAccountObject = true;
listServerAccountObject.SetProperty("L_ListFile_Contents", string.Join("\n", lists.Remove(mailingListName)));
SaveAccount(listServerAccountObject, "list server account ");
}
break;
}
}
}
// If no list server was found that was responsible for this mailing list, create one
if (forceCreatelistServerAccountObject || !listServerAccountFound && createListServerAccountIfNeeded)
{
// Create list server account
if (!listServerAccountObject.New("srv" + mailingListName))
{
var ex = new Exception("Cannot create listserver account to associate with mailing list." + GetErrorMessage(listServerAccountObject.LastErr));
Log.WriteError(ex);
throw ex;
}
listServerAccountObject.SetProperty("U_Type", IceWarpAccountType.ListServer);
listServerAccountObject.SetProperty("L_SendAllLists", 0);
listServerAccountObject.SetProperty("L_ListFile_Contents", mailingListName + "\n");
SaveAccount(listServerAccountObject, "listserver account to associate with mailing list");
}
return string.IsNullOrWhiteSpace(listServerAccountObject.EmailAddress) ? null : listServerAccountObject;
}
public void UpdateList(MailList maillist)
{
var accountObject = GetAccountObject(maillist.Name);
var listServerAccountObject = FindMatchingListServerAccount(maillist.Name, true);
accountObject.SetProperty("M_Name", maillist.Description);
accountObject.SetProperty("M_OwnerAddress", maillist.ModeratorAddress);
accountObject.SetProperty("M_SendAllLists", maillist.MembersSource);
accountObject.SetProperty("L_ListFile_Contents", string.Join(";0;\n", maillist.Members) + ";0;\n"); // 0 means that the members will have the default rights
// TODO: Create some way to manage list member rights. As it is now, all members will loose rights that is set using some other tool
var setSender = 0;
var setValue = 0;
var valueMode = false;
var value = "";
switch (maillist.FromHeader)
{
case IceWarpListFromAndReplyToHeader.NoChange:
switch (maillist.ReplyToHeader)
{
case IceWarpListFromAndReplyToHeader.NoChange:
break;
case IceWarpListFromAndReplyToHeader.SetToSender:
setSender = 1;
break;
case IceWarpListFromAndReplyToHeader.SetToValue:
setSender = 1;
valueMode = true;
value = maillist.ListReplyToAddress;
break;
}
break;
case IceWarpListFromAndReplyToHeader.SetToSender:
switch (maillist.ReplyToHeader)
{
case IceWarpListFromAndReplyToHeader.NoChange:
setSender = 1;
valueMode = true;
break;
case IceWarpListFromAndReplyToHeader.SetToSender:
setSender = 2;
valueMode = true;
break;
case IceWarpListFromAndReplyToHeader.SetToValue:
setSender = 1;
setValue = 1;
valueMode = true;
value = maillist.ListReplyToAddress;
break;
}
break;
case IceWarpListFromAndReplyToHeader.SetToValue:
switch (maillist.ReplyToHeader)
{
case IceWarpListFromAndReplyToHeader.NoChange:
setValue = 1;
value = maillist.ListFromAddress;
break;
case IceWarpListFromAndReplyToHeader.SetToSender:
setSender = 1;
setValue = 1;
value = maillist.ListFromAddress;
break;
case IceWarpListFromAndReplyToHeader.SetToValue:
setValue = 2;
value = maillist.ListFromAddress + "|" + maillist.ListReplyToAddress;
break;
}
break;
}
accountObject.SetProperty("M_SetSender", setSender);
accountObject.SetProperty("M_SetValue", setValue);
accountObject.SetProperty("M_ValueMode", valueMode);
accountObject.SetProperty("M_HeaderValue", value);
accountObject.SetProperty("M_SeparateTo", maillist.SetReceipientsToToHeader);
accountObject.SetProperty("M_AddToSubject", maillist.SubjectPrefix);
accountObject.SetProperty("M_ListSender", maillist.Originator);
accountObject.SetProperty("M_MembersOnly", maillist.PostingMode == PostingMode.MembersCanPost);
accountObject.SetProperty("M_Moderated", maillist.PasswordProtection);
accountObject.SetProperty("M_ModeratedPassword", maillist.Password);
accountObject.SetProperty("M_DefaultRights", maillist.DefaultRights);
accountObject.SetProperty("M_MaxList", maillist.MaxMessageSizeEnabled);
accountObject.SetProperty("M_MaxListSize", maillist.MaxMessageSize);
accountObject.SetProperty("M_MaxMembers", maillist.MaxMembers);
accountObject.SetProperty("M_SendToSender", maillist.SendToSender);
accountObject.SetProperty("M_DigestConfirmed", maillist.DigestMode);
accountObject.SetProperty("M_ListBatch", maillist.MaxMessagesPerMinute);
accountObject.SetProperty("M_NotifyJoin", maillist.SendSubscribe);
accountObject.SetProperty("M_NotifyLeave", maillist.SendUnsubscribe);
SaveAccount(accountObject, "mailing list account");
listServerAccountObject.SetProperty("L_Name", maillist.Description);
listServerAccountObject.SetProperty("L_OwnerAddress", maillist.ModeratorAddress);
listServerAccountObject.SetProperty("L_SendAllLists", 0);
listServerAccountObject.SetProperty("L_DigestConfirmed", maillist.ConfirmSubscription);
listServerAccountObject.SetProperty("L_ListSubject", maillist.CommandsInSubject);
listServerAccountObject.SetProperty("M_JoinR", !maillist.DisableSubscribecommand);
listServerAccountObject.SetProperty("M_LeaveR", maillist.AllowUnsubscribe);
listServerAccountObject.SetProperty("M_ListsR", !maillist.DisableListcommand);
listServerAccountObject.SetProperty("M_WhichR", !maillist.DisableWhichCommand);
listServerAccountObject.SetProperty("M_ReviewR", !maillist.DisableReviewCommand);
listServerAccountObject.SetProperty("M_VacationR", !maillist.DisableVacationCommand);
listServerAccountObject.SetProperty("L_Moderated", maillist.Moderated);
listServerAccountObject.SetProperty("L_ModeratedPassword", maillist.CommandPassword);
listServerAccountObject.SetProperty("L_ListSender", maillist.Originator);
listServerAccountObject.SetProperty("L_MaxList", maillist.SuppressCommandResponses);
SaveAccount(listServerAccountObject, "listserver account associated with mailing list");
}
public void DeleteList(string maillistName)
{
if (!ListExists(maillistName))
{
return;
}
var accountObject = GetAccountObject(maillistName);
var listServerAccountObject = FindMatchingListServerAccount(maillistName, false);
if (accountObject.Delete())
{
// If there is no matching list server account, we are done
if (listServerAccountObject == null)
{
return;
}
var lists = ((IEnumerable<string>)SplitFileContents(listServerAccountObject, "L_ListFile_Contents")).ToList();
if (lists.Count() == 1)
{
if (!listServerAccountObject.Delete())
{
var ex = new Exception("Deleted mail list, but list server account remains: " + GetErrorMessage(listServerAccountObject.LastErr));
Log.WriteError(ex);
throw ex;
}
}
else
{
listServerAccountObject.SetProperty("L_ListFile_Contents", string.Join("\n", lists.Remove(maillistName)));
if (!listServerAccountObject.Save())
{
var ex = new Exception("Deleted mail list, but associated list server account could not be updated: " + GetErrorMessage(listServerAccountObject.LastErr));
Log.WriteError(ex);
throw ex;
}
}
}
else
{
Log.WriteError("Cannot delete mail list: " + GetErrorMessage(accountObject.LastErr), null);
}
DisposeObject(accountObject);
DisposeObject(listServerAccountObject);
}
#endregion
public void Dispose()
{
Marshal.FinalReleaseComObject(_currentApiObject);
}
}
}
| |
/*
* 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 Nini.Config;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Server.Base;
using OpenSim.Server.Handlers.Base;
using OpenSim.Services.Interfaces;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Server.Handlers.Hypergrid
{
public class UserAgentServerConnector : ServiceConnector
{
// private static readonly ILog m_log =
// LogManager.GetLogger(
// MethodBase.GetCurrentMethod().DeclaringType);
private string[] m_AuthorizedCallers;
private IUserAgentService m_HomeUsersService;
private bool m_VerifyCallers = false;
public UserAgentServerConnector(IConfigSource config, IHttpServer server) :
this(config, server, (IFriendsSimConnector)null)
{
}
public UserAgentServerConnector(IConfigSource config, IHttpServer server, string configName) :
this(config, server)
{
}
public UserAgentServerConnector(IConfigSource config, IHttpServer server, IFriendsSimConnector friendsConnector) :
base(config, server, String.Empty)
{
IConfig gridConfig = config.Configs["UserAgentService"];
if (gridConfig != null)
{
string serviceDll = gridConfig.GetString("LocalServiceModule", string.Empty);
Object[] args = new Object[] { config, friendsConnector };
m_HomeUsersService = ServerUtils.LoadPlugin<IUserAgentService>(serviceDll, args);
}
if (m_HomeUsersService == null)
throw new Exception("UserAgent server connector cannot proceed because of missing service");
string loginServerIP = gridConfig.GetString("LoginServerIP", "127.0.0.1");
bool proxy = gridConfig.GetBoolean("HasProxy", false);
m_VerifyCallers = gridConfig.GetBoolean("VerifyCallers", false);
string csv = gridConfig.GetString("AuthorizedCallers", "127.0.0.1");
csv = csv.Replace(" ", "");
m_AuthorizedCallers = csv.Split(',');
server.AddXmlRPCHandler("agent_is_coming_home", AgentIsComingHome, false);
server.AddXmlRPCHandler("get_home_region", GetHomeRegion, false);
server.AddXmlRPCHandler("verify_agent", VerifyAgent, false);
server.AddXmlRPCHandler("verify_client", VerifyClient, false);
server.AddXmlRPCHandler("logout_agent", LogoutAgent, false);
server.AddXmlRPCHandler("status_notification", StatusNotification, false);
server.AddXmlRPCHandler("get_online_friends", GetOnlineFriends, false);
server.AddXmlRPCHandler("get_user_info", GetUserInfo, false);
server.AddXmlRPCHandler("get_server_urls", GetServerURLs, false);
server.AddXmlRPCHandler("locate_user", LocateUser, false);
server.AddXmlRPCHandler("get_uui", GetUUI, false);
server.AddXmlRPCHandler("get_uuid", GetUUID, false);
server.AddStreamHandler(new HomeAgentHandler(m_HomeUsersService, loginServerIP, proxy));
}
public IUserAgentService HomeUsersService
{
get { return m_HomeUsersService; }
}
public XmlRpcResponse AgentIsComingHome(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable requestData = (Hashtable)request.Params[0];
//string host = (string)requestData["host"];
//string portstr = (string)requestData["port"];
string sessionID_str = (string)requestData["sessionID"];
UUID sessionID = UUID.Zero;
UUID.TryParse(sessionID_str, out sessionID);
string gridName = (string)requestData["externalName"];
bool success = m_HomeUsersService.IsAgentComingHome(sessionID, gridName);
Hashtable hash = new Hashtable();
hash["result"] = success.ToString();
XmlRpcResponse response = new XmlRpcResponse();
response.Value = hash;
return response;
}
public XmlRpcResponse GetHomeRegion(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable requestData = (Hashtable)request.Params[0];
//string host = (string)requestData["host"];
//string portstr = (string)requestData["port"];
string userID_str = (string)requestData["userID"];
UUID userID = UUID.Zero;
UUID.TryParse(userID_str, out userID);
Vector3 position = Vector3.UnitY, lookAt = Vector3.UnitY;
GridRegion regInfo = m_HomeUsersService.GetHomeRegion(userID, out position, out lookAt);
Hashtable hash = new Hashtable();
if (regInfo == null)
hash["result"] = "false";
else
{
hash["result"] = "true";
hash["uuid"] = regInfo.RegionID.ToString();
hash["x"] = regInfo.RegionLocX.ToString();
hash["y"] = regInfo.RegionLocY.ToString();
hash["size_x"] = regInfo.RegionSizeX.ToString();
hash["size_y"] = regInfo.RegionSizeY.ToString();
hash["region_name"] = regInfo.RegionName;
hash["hostname"] = regInfo.ExternalHostName;
hash["http_port"] = regInfo.HttpPort.ToString();
hash["internal_port"] = regInfo.InternalEndPoint.Port.ToString();
hash["position"] = position.ToString();
hash["lookAt"] = lookAt.ToString();
}
XmlRpcResponse response = new XmlRpcResponse();
response.Value = hash;
return response;
}
[Obsolete]
public XmlRpcResponse GetOnlineFriends(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable hash = new Hashtable();
Hashtable requestData = (Hashtable)request.Params[0];
//string host = (string)requestData["host"];
//string portstr = (string)requestData["port"];
if (requestData.ContainsKey("userID"))
{
string userID_str = (string)requestData["userID"];
UUID userID = UUID.Zero;
UUID.TryParse(userID_str, out userID);
List<string> ids = new List<string>();
foreach (object key in requestData.Keys)
{
if (key is string && ((string)key).StartsWith("friend_") && requestData[key] != null)
ids.Add(requestData[key].ToString());
}
//List<UUID> online = m_HomeUsersService.GetOnlineFriends(userID, ids);
//if (online.Count > 0)
//{
// int i = 0;
// foreach (UUID id in online)
// {
// hash["friend_" + i.ToString()] = id.ToString();
// i++;
// }
//}
//else
// hash["result"] = "No Friends Online";
}
XmlRpcResponse response = new XmlRpcResponse();
response.Value = hash;
return response;
}
public XmlRpcResponse GetServerURLs(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable hash = new Hashtable();
Hashtable requestData = (Hashtable)request.Params[0];
//string host = (string)requestData["host"];
//string portstr = (string)requestData["port"];
if (requestData.ContainsKey("userID"))
{
string userID_str = (string)requestData["userID"];
UUID userID = UUID.Zero;
UUID.TryParse(userID_str, out userID);
Dictionary<string, object> serverURLs = m_HomeUsersService.GetServerURLs(userID);
if (serverURLs.Count > 0)
{
foreach (KeyValuePair<string, object> kvp in serverURLs)
hash["SRV_" + kvp.Key] = kvp.Value.ToString();
}
else
hash["result"] = "No Service URLs";
}
XmlRpcResponse response = new XmlRpcResponse();
response.Value = hash;
return response;
}
public XmlRpcResponse GetUserInfo(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable hash = new Hashtable();
Hashtable requestData = (Hashtable)request.Params[0];
// This needs checking!
if (requestData.ContainsKey("userID"))
{
string userID_str = (string)requestData["userID"];
UUID userID = UUID.Zero;
UUID.TryParse(userID_str, out userID);
//int userFlags = m_HomeUsersService.GetUserFlags(userID);
Dictionary<string, object> userInfo = m_HomeUsersService.GetUserInfo(userID);
if (userInfo.Count > 0)
{
foreach (KeyValuePair<string, object> kvp in userInfo)
{
hash[kvp.Key] = kvp.Value;
}
}
else
{
hash["result"] = "failure";
}
}
XmlRpcResponse response = new XmlRpcResponse();
response.Value = hash;
return response;
}
/// <summary>
/// Returns the UUI of a user given a UUID.
/// </summary>
/// <param name="request"></param>
/// <param name="remoteClient"></param>
/// <returns></returns>
public XmlRpcResponse GetUUI(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable hash = new Hashtable();
Hashtable requestData = (Hashtable)request.Params[0];
//string host = (string)requestData["host"];
//string portstr = (string)requestData["port"];
if (requestData.ContainsKey("userID") && requestData.ContainsKey("targetUserID"))
{
string userID_str = (string)requestData["userID"];
UUID userID = UUID.Zero;
UUID.TryParse(userID_str, out userID);
string tuserID_str = (string)requestData["targetUserID"];
UUID targetUserID = UUID.Zero;
UUID.TryParse(tuserID_str, out targetUserID);
string uui = m_HomeUsersService.GetUUI(userID, targetUserID);
if (uui != string.Empty)
hash["UUI"] = uui;
else
hash["result"] = "User unknown";
}
XmlRpcResponse response = new XmlRpcResponse();
response.Value = hash;
return response;
}
/// <summary>
/// Gets the UUID of a user given First name, Last name.
/// </summary>
/// <param name="request"></param>
/// <param name="remoteClient"></param>
/// <returns></returns>
public XmlRpcResponse GetUUID(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable hash = new Hashtable();
Hashtable requestData = (Hashtable)request.Params[0];
//string host = (string)requestData["host"];
//string portstr = (string)requestData["port"];
if (requestData.ContainsKey("first") && requestData.ContainsKey("last"))
{
string first = (string)requestData["first"];
string last = (string)requestData["last"];
UUID uuid = m_HomeUsersService.GetUUID(first, last);
hash["UUID"] = uuid.ToString();
}
XmlRpcResponse response = new XmlRpcResponse();
response.Value = hash;
return response;
}
/// <summary>
/// Locates the user.
/// This is a sensitive operation, only authorized IP addresses can perform it.
/// </summary>
/// <param name="request"></param>
/// <param name="remoteClient"></param>
/// <returns></returns>
public XmlRpcResponse LocateUser(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable hash = new Hashtable();
bool authorized = true;
if (m_VerifyCallers)
{
authorized = false;
foreach (string s in m_AuthorizedCallers)
if (s == remoteClient.Address.ToString())
{
authorized = true;
break;
}
}
if (authorized)
{
Hashtable requestData = (Hashtable)request.Params[0];
//string host = (string)requestData["host"];
//string portstr = (string)requestData["port"];
if (requestData.ContainsKey("userID"))
{
string userID_str = (string)requestData["userID"];
UUID userID = UUID.Zero;
UUID.TryParse(userID_str, out userID);
string url = m_HomeUsersService.LocateUser(userID);
if (url != string.Empty)
hash["URL"] = url;
else
hash["result"] = "Unable to locate user";
}
}
XmlRpcResponse response = new XmlRpcResponse();
response.Value = hash;
return response;
}
public XmlRpcResponse LogoutAgent(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable requestData = (Hashtable)request.Params[0];
//string host = (string)requestData["host"];
//string portstr = (string)requestData["port"];
string sessionID_str = (string)requestData["sessionID"];
UUID sessionID = UUID.Zero;
UUID.TryParse(sessionID_str, out sessionID);
string userID_str = (string)requestData["userID"];
UUID userID = UUID.Zero;
UUID.TryParse(userID_str, out userID);
m_HomeUsersService.LogoutAgent(userID, sessionID);
Hashtable hash = new Hashtable();
hash["result"] = "true";
XmlRpcResponse response = new XmlRpcResponse();
response.Value = hash;
return response;
}
public XmlRpcResponse StatusNotification(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable hash = new Hashtable();
hash["result"] = "false";
Hashtable requestData = (Hashtable)request.Params[0];
//string host = (string)requestData["host"];
//string portstr = (string)requestData["port"];
if (requestData.ContainsKey("userID") && requestData.ContainsKey("online"))
{
string userID_str = (string)requestData["userID"];
UUID userID = UUID.Zero;
UUID.TryParse(userID_str, out userID);
List<string> ids = new List<string>();
foreach (object key in requestData.Keys)
{
if (key is string && ((string)key).StartsWith("friend_") && requestData[key] != null)
ids.Add(requestData[key].ToString());
}
bool online = false;
bool.TryParse(requestData["online"].ToString(), out online);
// let's spawn a thread for this, because it may take a long time...
List<UUID> friendsOnline = m_HomeUsersService.StatusNotification(ids, userID, online);
if (friendsOnline.Count > 0)
{
int i = 0;
foreach (UUID id in friendsOnline)
{
hash["friend_" + i.ToString()] = id.ToString();
i++;
}
}
else
hash["result"] = "No Friends Online";
}
XmlRpcResponse response = new XmlRpcResponse();
response.Value = hash;
return response;
}
public XmlRpcResponse VerifyAgent(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable requestData = (Hashtable)request.Params[0];
//string host = (string)requestData["host"];
//string portstr = (string)requestData["port"];
string sessionID_str = (string)requestData["sessionID"];
UUID sessionID = UUID.Zero;
UUID.TryParse(sessionID_str, out sessionID);
string token = (string)requestData["token"];
bool success = m_HomeUsersService.VerifyAgent(sessionID, token);
Hashtable hash = new Hashtable();
hash["result"] = success.ToString();
XmlRpcResponse response = new XmlRpcResponse();
response.Value = hash;
return response;
}
public XmlRpcResponse VerifyClient(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable requestData = (Hashtable)request.Params[0];
//string host = (string)requestData["host"];
//string portstr = (string)requestData["port"];
string sessionID_str = (string)requestData["sessionID"];
UUID sessionID = UUID.Zero;
UUID.TryParse(sessionID_str, out sessionID);
string token = (string)requestData["token"];
bool success = m_HomeUsersService.VerifyClient(sessionID, token);
Hashtable hash = new Hashtable();
hash["result"] = success.ToString();
XmlRpcResponse response = new XmlRpcResponse();
response.Value = hash;
return response;
}
}
}
| |
#pragma warning disable 109, 114, 219, 429, 168, 162
namespace pony
{
public class Timer : global::pony.events.Signal
{
public Timer(global::haxe.lang.EmptyObject empty) : base(global::haxe.lang.EmptyObject.EMPTY)
{
unchecked
{
}
#line default
}
public Timer(int delay, global::haxe.lang.Null<bool> autoStart) : base(((global::haxe.lang.EmptyObject) (global::haxe.lang.EmptyObject.EMPTY) ))
{
unchecked
{
#line 44 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
global::pony.Timer.__hx_ctor_pony_Timer(this, delay, autoStart);
}
#line default
}
public static void __hx_ctor_pony_Timer(global::pony.Timer __temp_me99, int delay, global::haxe.lang.Null<bool> autoStart)
{
unchecked
{
#line 43 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
bool __temp_autoStart98 = ( (global::haxe.lang.Runtime.eq((autoStart).toDynamic(), (default(global::haxe.lang.Null<bool>)).toDynamic())) ? (((bool) (true) )) : (autoStart.@value) );
global::pony.events.Signal.__hx_ctor_pony_events_Signal(__temp_me99, default(object));
__temp_me99.delay = delay;
if (__temp_autoStart98)
{
#line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
__temp_me99.start();
}
}
#line default
}
public static global::pony.Timer tick(int delay)
{
unchecked
{
#line 81 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
{
#line 81 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
global::Array<int> count = new global::Array<int>(new int[]{1});
#line 81 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
global::pony.Timer _this = new global::pony.Timer(((int) (delay) ), ((global::haxe.lang.Null<bool>) (default(global::haxe.lang.Null<bool>)) ));
#line 81 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
global::Array<object> _g = new global::Array<object>(new object[]{_this});
#line 81 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
object __temp_stmt484 = default(object);
#line 81 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
{
#line 81 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
object f = global::pony._Function.Function_Impl_.@from(new global::pony.Timer_tick_81__Fun(((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (_g) ))) ), ((global::Array<int>) (global::Array<object>.__hx_cast<int>(((global::Array) (count) ))) )), 0);
#line 81 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
__temp_stmt484 = global::pony.events._Listener.Listener_Impl_._fromFunction(f, false);
}
#line 81 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
_this.@add(__temp_stmt484, new global::haxe.lang.Null<int>(10000, true));
#line 81 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
return _this;
}
}
#line default
}
public static new object __hx_createEmpty()
{
unchecked
{
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
return new global::pony.Timer(((global::haxe.lang.EmptyObject) (global::haxe.lang.EmptyObject.EMPTY) ));
}
#line default
}
public static new object __hx_create(global::Array arr)
{
unchecked
{
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
return new global::pony.Timer(((int) (global::haxe.lang.Runtime.toInt(arr[0])) ), global::haxe.lang.Null<object>.ofDynamic<bool>(arr[1]));
}
#line default
}
public int delay;
public global::haxe.Timer t;
public virtual global::pony.Timer start()
{
unchecked
{
#line 50 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
this.stop();
#line 52 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
this.t = new global::haxe.Timer(((int) (this.delay) ));
this.t.run = ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("run"), ((int) (5695307) ))) );
#line 55 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
return this;
}
#line default
}
public virtual void run()
{
unchecked
{
#line 130 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Signal.hx"
this.dispatchEvent(new global::pony.events.Event(((global::Array) (new global::Array<object>(new object[]{})) ), ((object) (this.target) ), ((global::pony.events.Event) (default(global::pony.events.Event)) )));
#line 130 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Signal.hx"
global::pony.Timer __temp_expr482 = this;
}
#line default
}
public virtual global::pony.Timer stop()
{
unchecked
{
#line 62 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
if (( this.t != default(global::haxe.Timer) ))
{
this.t.stop();
this.t = default(global::haxe.Timer);
}
#line 67 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
return this;
}
#line default
}
public void clear()
{
unchecked
{
#line 71 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
this.stop();
this.removeAllListeners();
}
#line default
}
public global::pony.Timer setTickCount(int count)
{
unchecked
{
#line 75 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
global::Array<int> count1 = new global::Array<int>(new int[]{count});
#line 75 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
global::Array<object> _g = new global::Array<object>(new object[]{this});
object __temp_stmt483 = default(object);
#line 76 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
{
#line 76 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
object f = global::pony._Function.Function_Impl_.@from(new global::pony.Timer_setTickCount_76__Fun(((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (_g) ))) ), ((global::Array<int>) (global::Array<object>.__hx_cast<int>(((global::Array) (count1) ))) )), 0);
#line 76 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
__temp_stmt483 = global::pony.events._Listener.Listener_Impl_._fromFunction(f, false);
}
#line 76 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
this.@add(__temp_stmt483, new global::haxe.lang.Null<int>(10000, true));
return this;
}
#line default
}
public override double __hx_setField_f(string field, int hash, double @value, bool handleProperties)
{
unchecked
{
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
switch (hash)
{
case 1462163331:
{
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
this.delay = ((int) (@value) );
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
return @value;
}
default:
{
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
return base.__hx_setField_f(field, hash, @value, handleProperties);
}
}
}
#line default
}
public override object __hx_setField(string field, int hash, object @value, bool handleProperties)
{
unchecked
{
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
switch (hash)
{
case 116:
{
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
this.t = ((global::haxe.Timer) (@value) );
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
return @value;
}
case 1462163331:
{
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
this.delay = ((int) (global::haxe.lang.Runtime.toInt(@value)) );
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
return @value;
}
default:
{
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
return base.__hx_setField(field, hash, @value, handleProperties);
}
}
}
#line default
}
public override object __hx_getField(string field, int hash, bool throwErrors, bool isCheck, bool handleProperties)
{
unchecked
{
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
switch (hash)
{
case 1777426480:
{
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("setTickCount"), ((int) (1777426480) ))) );
}
case 1213952397:
{
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("clear"), ((int) (1213952397) ))) );
}
case 1281093634:
{
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("stop"), ((int) (1281093634) ))) );
}
case 5695307:
{
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("run"), ((int) (5695307) ))) );
}
case 67859554:
{
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("start"), ((int) (67859554) ))) );
}
case 116:
{
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
return this.t;
}
case 1462163331:
{
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
return this.delay;
}
default:
{
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
return base.__hx_getField(field, hash, throwErrors, isCheck, handleProperties);
}
}
}
#line default
}
public override double __hx_getField_f(string field, int hash, bool throwErrors, bool handleProperties)
{
unchecked
{
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
switch (hash)
{
case 1462163331:
{
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
return ((double) (this.delay) );
}
default:
{
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
return base.__hx_getField_f(field, hash, throwErrors, handleProperties);
}
}
}
#line default
}
public override object __hx_invokeField(string field, int hash, global::Array dynargs)
{
unchecked
{
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
switch (hash)
{
case 1777426480:
{
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
return this.setTickCount(((int) (global::haxe.lang.Runtime.toInt(dynargs[0])) ));
}
case 1213952397:
{
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
this.clear();
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
break;
}
case 1281093634:
{
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
return this.stop();
}
case 5695307:
{
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
this.run();
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
break;
}
case 67859554:
{
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
return this.start();
}
default:
{
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
return base.__hx_invokeField(field, hash, dynargs);
}
}
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
return default(object);
}
#line default
}
public override void __hx_getFields(global::Array<object> baseArr)
{
unchecked
{
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
baseArr.push("t");
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
baseArr.push("delay");
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
{
#line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
base.__hx_getFields(baseArr);
}
}
#line default
}
}
}
#pragma warning disable 109, 114, 219, 429, 168, 162
namespace pony
{
public class Timer_setTickCount_76__Fun : global::haxe.lang.Function
{
public Timer_setTickCount_76__Fun(global::Array<object> _g, global::Array<int> count1) : base(0, 0)
{
unchecked
{
#line 76 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
this._g = _g;
#line 76 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
this.count1 = count1;
}
#line default
}
public override object __hx_invoke0_o()
{
unchecked
{
#line 76 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
if (( -- this.count1[0] == 0 ))
{
#line 76 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
((global::pony.Timer) (this._g[0]) ).stop();
#line 76 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
((global::pony.Timer) (this._g[0]) ).removeAllListeners();
}
#line 76 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
return default(object);
}
#line default
}
public global::Array<object> _g;
public global::Array<int> count1;
}
}
#pragma warning disable 109, 114, 219, 429, 168, 162
namespace pony
{
public class Timer_tick_81__Fun : global::haxe.lang.Function
{
public Timer_tick_81__Fun(global::Array<object> _g, global::Array<int> count) : base(0, 0)
{
unchecked
{
#line 81 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
this._g = _g;
#line 81 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
this.count = count;
}
#line default
}
public override object __hx_invoke0_o()
{
unchecked
{
#line 81 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
if (( -- this.count[0] == 0 ))
{
#line 81 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
((global::pony.Timer) (this._g[0]) ).stop();
#line 81 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
((global::pony.Timer) (this._g[0]) ).removeAllListeners();
}
#line 81 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Timer.hx"
return default(object);
}
#line default
}
public global::Array<object> _g;
public global::Array<int> count;
}
}
| |
using OpenKh.Common;
using OpenKh.Kh2;
using OpenKh.Tools.Common.Wpf;
using OpenKh.Tools.ModsManager.Services;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using System.Windows;
using Xe.IO;
using Xe.Tools;
using Xe.Tools.Wpf.Commands;
using Xe.Tools.Wpf.Dialogs;
namespace OpenKh.Tools.ModsManager.ViewModels
{
public class SetupWizardViewModel : BaseNotifyPropertyChanged
{
private const int BufferSize = 65536;
private static string ApplicationName = Utilities.GetApplicationName();
private static List<FileDialogFilter> _isoFilter = FileDialogFilterComposer
.Compose()
.AddExtensions("PlayStation 2 game ISO", "iso");
private static List<FileDialogFilter> _openkhGeFilter = FileDialogFilterComposer
.Compose()
.AddExtensions("OpenKH Game Engine executable", "*Game.exe");
private static List<FileDialogFilter> _pcsx2Filter = FileDialogFilterComposer
.Compose()
.AddExtensions("PCSX2 emulator", "exe");
private int _gameEdition;
private string _isoLocation;
private string _openKhGameEngineLocation;
private string _pcsx2Location;
private string _pcReleaseLocation;
private string _gameDataLocation;
public string Title => $"Set-up wizard | {ApplicationName}";
public RelayCommand SelectIsoCommand { get; }
public string GameId { get; set; }
public string GameName { get; set; }
public string IsoLocation
{
get => _isoLocation;
set
{
_isoLocation = value;
if (File.Exists(_isoLocation))
{
var game = GameService.DetectGameId(_isoLocation);
GameId = game?.Id;
GameName = game?.Name;
}
else
{
GameId = null;
GameName = null;
}
OnPropertyChanged();
OnPropertyChanged(nameof(IsIsoSelected));
OnPropertyChanged(nameof(GameId));
OnPropertyChanged(nameof(GameName));
OnPropertyChanged(nameof(GameRecognizedVisibility));
OnPropertyChanged(nameof(GameNotRecognizedVisibility));
OnPropertyChanged(nameof(IsGameRecognized));
}
}
public bool IsIsoSelected => !string.IsNullOrEmpty(IsoLocation) && File.Exists(IsoLocation);
public bool IsGameRecognized => IsIsoSelected && GameId != null;
public Visibility GameRecognizedVisibility => IsIsoSelected && GameId != null ? Visibility.Visible : Visibility.Collapsed;
public Visibility GameNotRecognizedVisibility => IsIsoSelected && GameId == null ? Visibility.Visible : Visibility.Collapsed;
public bool IsGameSelected
{
get
{
var location = GameEdition switch
{
0 => OpenKhGameEngineLocation,
1 => Pcsx2Location,
2 => PcReleaseLocation,
_ => string.Empty,
};
return !string.IsNullOrEmpty(location) && File.Exists(location);
}
}
public int GameEdition
{
get => _gameEdition;
set
{
_gameEdition = value;
OnPropertyChanged();
OnPropertyChanged(nameof(IsGameSelected));
OnPropertyChanged(nameof(OpenKhGameEngineConfigVisibility));
OnPropertyChanged(nameof(Pcsx2ConfigVisibility));
OnPropertyChanged(nameof(PcReleaseConfigVisibility));
}
}
public RelayCommand SelectOpenKhGameEngineCommand { get; }
public Visibility OpenKhGameEngineConfigVisibility => GameEdition == 0 ? Visibility.Visible : Visibility.Collapsed;
public string OpenKhGameEngineLocation
{
get => _openKhGameEngineLocation;
set
{
_openKhGameEngineLocation = value;
OnPropertyChanged();
OnPropertyChanged(nameof(IsGameSelected));
}
}
public RelayCommand SelectPcsx2Command { get; }
public Visibility Pcsx2ConfigVisibility => GameEdition == 1 ? Visibility.Visible : Visibility.Collapsed;
public string Pcsx2Location
{
get => _pcsx2Location;
set
{
_pcsx2Location = value;
OnPropertyChanged();
OnPropertyChanged(nameof(IsGameSelected));
}
}
public RelayCommand SelectPcReleaseCommand { get; }
public Visibility PcReleaseConfigVisibility => GameEdition == 2 ? Visibility.Visible : Visibility.Collapsed;
public string PcReleaseLocation
{
get => _pcReleaseLocation;
set
{
_pcReleaseLocation = value;
OnPropertyChanged();
OnPropertyChanged(nameof(IsGameSelected));
}
}
public RelayCommand SelectGameDataLocationCommand { get; }
public string GameDataLocation
{
get => _gameDataLocation;
set
{
_gameDataLocation = value;
OnPropertyChanged();
OnPropertyChanged(nameof(IsGameDataFound));
OnPropertyChanged(nameof(GameDataNotFoundVisibility));
OnPropertyChanged(nameof(GameDataFoundVisibility));
}
}
public bool IsNotExtracting { get; private set; }
public bool IsGameDataFound => IsNotExtracting && File.Exists(Path.Combine(GameDataLocation ?? "", "00objentry.bin"));
public Visibility GameDataNotFoundVisibility => !IsGameDataFound ? Visibility.Visible : Visibility.Collapsed;
public Visibility GameDataFoundVisibility => IsGameDataFound ? Visibility.Visible : Visibility.Collapsed;
public Visibility ProgressBarVisibility => IsNotExtracting ? Visibility.Collapsed : Visibility.Visible;
public Visibility ExtractionCompleteVisibility => ExtractionProgress == 1f ? Visibility.Visible : Visibility.Collapsed;
public RelayCommand ExtractGameDataCommand { get; set; }
public float ExtractionProgress { get; set; }
public int RegionId { get; set; }
public SetupWizardViewModel()
{
IsNotExtracting = true;
SelectIsoCommand = new RelayCommand(_ =>
FileDialog.OnOpen(fileName => IsoLocation = fileName, _isoFilter));
SelectOpenKhGameEngineCommand = new RelayCommand(_ =>
FileDialog.OnOpen(fileName => OpenKhGameEngineLocation = fileName, _openkhGeFilter));
SelectPcsx2Command = new RelayCommand(_ =>
FileDialog.OnOpen(fileName => Pcsx2Location = fileName, _pcsx2Filter));
SelectGameDataLocationCommand = new RelayCommand(_ =>
FileDialog.OnFolder(path => GameDataLocation = path));
ExtractGameDataCommand = new RelayCommand(async _ =>
await ExtractGameData(IsoLocation, GameDataLocation));
}
private async Task ExtractGameData(string isoLocation, string gameDataLocation)
{
var fileBlocks = File.OpenRead(isoLocation).Using(stream =>
{
var bufferedStream = new BufferedStream(stream);
var idxBlock = IsoUtility.GetFileOffset(bufferedStream, "KH2.IDX;1");
var imgBlock = IsoUtility.GetFileOffset(bufferedStream, "KH2.IMG;1");
return (idxBlock, imgBlock);
});
if (fileBlocks.idxBlock == -1 || fileBlocks.imgBlock == -1)
{
MessageBox.Show(
$"Unable to find the files KH2.IDX and KH2.IMG in the ISO at '{isoLocation}'. The extraction will stop.",
"Extraction error",
MessageBoxButton.OK,
MessageBoxImage.Error);
return;
}
IsNotExtracting = false;
ExtractionProgress = 0;
OnPropertyChanged(nameof(IsNotExtracting));
OnPropertyChanged(nameof(IsGameDataFound));
OnPropertyChanged(nameof(ProgressBarVisibility));
OnPropertyChanged(nameof(ExtractionCompleteVisibility));
OnPropertyChanged(nameof(ExtractionProgress));
await Task.Run(() =>
{
using var isoStream = File.OpenRead(isoLocation);
var idxOffset = fileBlocks.idxBlock * 0x800L;
var idx = Idx.Read(new SubStream(isoStream, idxOffset, isoStream.Length - idxOffset));
var imgOffset = fileBlocks.imgBlock * 0x800L;
var imgStream = new SubStream(isoStream, imgOffset, isoStream.Length - imgOffset);
var img = new Img(imgStream, idx, true);
var fileCount = img.Entries.Count;
var fileProcessed = 0;
foreach (var fileEntry in img.Entries)
{
var fileName = IdxName.Lookup(fileEntry) ?? $"@{fileEntry.Hash32:08X}_{fileEntry.Hash16:04X}";
using var stream = img.FileOpen(fileEntry);
var fileDestination = Path.Combine(gameDataLocation, fileName);
var directoryDestination = Path.GetDirectoryName(fileDestination);
if (!Directory.Exists(directoryDestination))
Directory.CreateDirectory(directoryDestination);
File.Create(fileDestination).Using(dstStream => stream.CopyTo(dstStream, BufferSize));
fileProcessed++;
ExtractionProgress = (float)fileProcessed / fileCount;
OnPropertyChanged(nameof(ExtractionProgress));
}
Application.Current.Dispatcher.Invoke(() =>
{
IsNotExtracting = true;
ExtractionProgress = 1.0f;
OnPropertyChanged(nameof(IsNotExtracting));
OnPropertyChanged(nameof(IsGameDataFound));
OnPropertyChanged(nameof(GameDataNotFoundVisibility));
OnPropertyChanged(nameof(GameDataFoundVisibility));
OnPropertyChanged(nameof(ProgressBarVisibility));
OnPropertyChanged(nameof(ExtractionCompleteVisibility));
OnPropertyChanged(nameof(ExtractionProgress));
});
});
}
}
}
| |
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using DemoGame.DbObjs;
using log4net;
using NetGore;
using NetGore.Features.Shops;
using NetGore.Graphics;
using NetGore.Graphics.GUI;
using SFML.Graphics;
using SFML.Window;
namespace DemoGame.Client
{
/// <summary>
/// A <see cref="Form"/> that displays the contents of a shop.
/// </summary>
public class ShopForm : Form, IDragDropProvider
{
/// <summary>
/// The number of items on each row.
/// </summary>
const int _columns = 6;
/// <summary>
/// The size of each item slot.
/// </summary>
static readonly Vector2 _itemSize = new Vector2(32, 32);
/// <summary>
/// The amount of space between each item slot.
/// </summary>
static readonly Vector2 _padding = new Vector2(2, 2);
static readonly ShopSettings _shopSettings = ShopSettings.Instance;
readonly DragDropHandler _dragDropHandler;
ShopInfo<IItemTemplateTable> _shopInfo;
/// <summary>
/// Initializes a new instance of the <see cref="ShopForm"/> class.
/// </summary>
/// <param name="dragDropHandler">The drag-drop handler callback.</param>
/// <param name="position">The position.</param>
/// <param name="parent">The parent.</param>
public ShopForm(DragDropHandler dragDropHandler, Vector2 position, Control parent)
: base(parent, position, new Vector2(200, 200))
{
_dragDropHandler = dragDropHandler;
IsVisible = false;
var itemsSize = _columns * _itemSize;
var paddingSize = (_columns + 1) * _padding;
Size = itemsSize + paddingSize + Border.Size;
CreateItemSlots();
}
/// <summary>
/// Notifies listeners when a request has been made to purchase an item from the shop.
/// </summary>
public event TypedEventHandler<ShopForm, EventArgs<ShopItemIndex>> RequestPurchase;
/// <summary>
/// Gets the information for the current shop, or null if no shop is set.
/// </summary>
public ShopInfo<IItemTemplateTable> ShopInfo
{
get { return _shopInfo; }
}
/// <summary>
/// Creates the <see cref="ShopItemPB"/>s for the form.
/// </summary>
void CreateItemSlots()
{
var offset = _padding;
var offsetMultiplier = _itemSize + _padding;
for (var i = 0; i < _shopSettings.MaxShopItems; i++)
{
var x = i % _columns;
var y = i / _columns;
var pos = offset + new Vector2(x, y) * offsetMultiplier;
new ShopItemPB(this, pos, new ShopItemIndex((byte)i));
}
}
/// <summary>
/// Shows the shop form.
/// </summary>
/// <param name="shopInfo">The info for the shop to display.</param>
public void DisplayShop(ShopInfo<IItemTemplateTable> shopInfo)
{
_shopInfo = shopInfo;
IsVisible = true;
}
/// <summary>
/// Hides the shop form.
/// </summary>
public void HideShop()
{
IsVisible = false;
_shopInfo = null;
}
/// <summary>
/// Sets the default values for the <see cref="Control"/>. This should always begin with a call to the
/// base class's method to ensure that changes to settings are hierchical.
/// </summary>
protected override void SetDefaultValues()
{
base.SetDefaultValues();
Text = "Shop";
}
/// <summary>
/// Handles the <see cref="Control.MouseUp"/> event from the <see cref="ShopItemPB"/>s on this form.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="MouseButtonEventArgs"/> instance containing the event data.</param>
void ShopItemPB_OnMouseUp(object sender, MouseButtonEventArgs e)
{
var src = (ShopItemPB)sender;
if (src.ItemInfo != null)
{
if (RequestPurchase != null)
RequestPurchase.Raise(this, EventArgsHelper.Create(src.Slot));
}
}
#region IDragDropProvider Members
/// <summary>
/// Gets if this <see cref="IDragDropProvider"/> can be dragged. In the case of something that only
/// supports having items dropped on it but not dragging, this will always return false. For items that can be
/// dragged, this will return false if there is currently nothing to drag (such as an empty inventory slot) or
/// there is some other reason that this item cannot currently be dragged.
/// </summary>
bool IDragDropProvider.CanDragContents
{
get { return false; }
}
/// <summary>
/// Gets if the specified <see cref="IDragDropProvider"/> can be dropped on this <see cref="IDragDropProvider"/>.
/// </summary>
/// <param name="source">The <see cref="IDragDropProvider"/> to check if can be dropped on this
/// <see cref="IDragDropProvider"/>. This value will never be null.</param>
/// <returns>True if the <paramref name="source"/> can be dropped on this <see cref="IDragDropProvider"/>;
/// otherwise false.</returns>
bool IDragDropProvider.CanDrop(IDragDropProvider source)
{
return _dragDropHandler.CanDrop(source, this);
}
/// <summary>
/// Draws the item that this <see cref="IDragDropProvider"/> contains for when this item
/// is being dragged.
/// </summary>
/// <param name="spriteBatch">The <see cref="ISpriteBatch"/> to use to draw.</param>
/// <param name="position">The position to draw the sprite at.</param>
/// <param name="color">The color to use when drawing the item.</param>
void IDragDropProvider.DrawDraggedItem(ISpriteBatch spriteBatch, Vector2 position, Color color)
{
}
/// <summary>
/// Draws a visual highlighting on this <see cref="IDragDropProvider"/> for when an item is being
/// dragged onto it but not yet dropped.
/// </summary>
/// <param name="spriteBatch">The <see cref="ISpriteBatch"/> to use to draw.</param>
void IDragDropProvider.DrawDropHighlight(ISpriteBatch spriteBatch)
{
}
/// <summary>
/// Handles when the specified <see cref="IDragDropProvider"/> is dropped on this <see cref="IDragDropProvider"/>.
/// </summary>
/// <param name="source">The <see cref="IDragDropProvider"/> that is being dropped on this
/// <see cref="IDragDropProvider"/>.</param>
void IDragDropProvider.Drop(IDragDropProvider source)
{
_dragDropHandler.Drop(source, this);
}
#endregion
/// <summary>
/// A <see cref="PictureBox"/> that contains an item in a <see cref="ShopForm"/>.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
public class ShopItemPB : PictureBox, IDragDropProvider
{
static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
static readonly TooltipHandler _tooltipHandler = TooltipCallback;
readonly ShopItemIndex _slot;
Grh _grh;
/// <summary>
/// Initializes a new instance of the <see cref="ShopItemPB"/> class.
/// </summary>
/// <param name="parent">The parent.</param>
/// <param name="pos">The pos.</param>
/// <param name="index">The <see cref="ShopItemIndex"/>.</param>
/// <exception cref="ArgumentNullException"><paramref name="parent" /> is <c>null</c>.</exception>
public ShopItemPB(ShopForm parent, Vector2 pos, ShopItemIndex index) : base(parent, pos, _itemSize)
{
if (parent == null)
throw new ArgumentNullException("parent");
_slot = index;
Tooltip = _tooltipHandler;
MouseUp += ShopForm.ShopItemPB_OnMouseUp;
}
/// <summary>
/// Gets the <see cref="IItemTemplateTable"/> for the item in this slot, or null if there is no
/// item in the slot.
/// </summary>
public IItemTemplateTable ItemInfo
{
get
{
var shopInfo = ShopInfo;
if (shopInfo == null)
return null;
return ShopInfo.GetItemInfo(Slot);
}
}
/// <summary>
/// Gets the <see cref="ShopForm"/> that this <see cref="ShopItemPB"/> is on.
/// </summary>
public ShopForm ShopForm
{
get { return (ShopForm)Parent; }
}
/// <summary>
/// Gets the shop information for the shop that this item belongs to.
/// </summary>
ShopInfo<IItemTemplateTable> ShopInfo
{
get { return ShopForm.ShopInfo; }
}
/// <summary>
/// Gets the <see cref="ShopItemIndex"/> of this slot.
/// </summary>
public ShopItemIndex Slot
{
get { return _slot; }
}
/// <summary>
/// Draws the <see cref="Control"/>.
/// </summary>
/// <param name="spriteBatch">The <see cref="ISpriteBatch"/> to draw to.</param>
protected override void DrawControl(ISpriteBatch spriteBatch)
{
base.DrawControl(spriteBatch);
var itemInfo = ItemInfo;
if (itemInfo == null)
{
_grh = null;
return;
}
if (_grh == null || _grh.GrhData.GrhIndex != itemInfo.Graphic)
{
try
{
_grh = new Grh(itemInfo.Graphic, AnimType.Loop, 0);
}
catch (Exception ex)
{
_grh = null;
if (log.IsErrorEnabled)
log.ErrorFormat("Failed to load shop Grh with index `{0}`: `{1}`", itemInfo.Graphic, ex);
}
}
if (_grh == null)
return;
// Draw the item in the center of the slot
var offset = (_itemSize - _grh.Size) / 2f;
_grh.Draw(spriteBatch, ScreenPosition + offset);
}
/// <summary>
/// When overridden in the derived class, loads the skinning information for the <see cref="Control"/>
/// from the given <paramref name="skinManager"/>.
/// </summary>
/// <param name="skinManager">The <see cref="ISkinManager"/> to load the skinning information from.</param>
public override void LoadSkin(ISkinManager skinManager)
{
base.LoadSkin(skinManager);
Sprite = GUIManager.SkinManager.GetSprite("item_slot");
}
/// <summary>
/// Handles when a mouse button has been raised on the <see cref="Control"/>.
/// This is called immediately before <see cref="Control.OnMouseUp"/>.
/// Override this method instead of using an event hook on <see cref="Control.MouseUp"/> when possible.
/// </summary>
/// <param name="e">The event args.</param>
protected override void OnMouseUp(MouseButtonEventArgs e)
{
base.OnMouseUp(e);
}
/// <summary>
/// Gets the text for the <see cref="Tooltip"/>.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="args">The args.</param>
/// <returns>The text for the <see cref="Tooltip"/>.</returns>
static StyledText[] TooltipCallback(Control sender, TooltipArgs args)
{
var src = (ShopItemPB)sender;
var itemInfo = src.ItemInfo;
return ItemInfoHelper.GetStyledText(itemInfo);
}
#region IDragDropProvider Members
/// <summary>
/// Gets if this <see cref="IDragDropProvider"/> can be dragged. In the case of something that only
/// supports having items dropped on it but not dragging, this will always return false. For items that can be
/// dragged, this will return false if there is currently nothing to drag (such as an empty inventory slot) or
/// there is some other reason that this item cannot currently be dragged.
/// </summary>
bool IDragDropProvider.CanDragContents
{
get { return true; }
}
/// <summary>
/// Gets if the specified <see cref="IDragDropProvider"/> can be dropped on this <see cref="IDragDropProvider"/>.
/// </summary>
/// <param name="source">The <see cref="IDragDropProvider"/> to check if can be dropped on this
/// <see cref="IDragDropProvider"/>. This value will never be null.</param>
/// <returns>True if the <paramref name="source"/> can be dropped on this <see cref="IDragDropProvider"/>;
/// otherwise false.</returns>
bool IDragDropProvider.CanDrop(IDragDropProvider source)
{
return ShopForm._dragDropHandler.CanDrop(source, this);
}
/// <summary>
/// Draws the item that this <see cref="IDragDropProvider"/> contains for when this item
/// is being dragged.
/// </summary>
/// <param name="spriteBatch">The <see cref="ISpriteBatch"/> to use to draw.</param>
/// <param name="position">The position to draw the sprite at.</param>
/// <param name="color">The color to use when drawing the item.</param>
void IDragDropProvider.DrawDraggedItem(ISpriteBatch spriteBatch, Vector2 position, Color color)
{
if (_grh == null)
return;
_grh.Draw(spriteBatch, position, color);
}
/// <summary>
/// Draws a visual highlighting on this <see cref="IDragDropProvider"/> for when an item is being
/// dragged onto it but not yet dropped.
/// </summary>
/// <param name="spriteBatch">The <see cref="ISpriteBatch"/> to use to draw.</param>
void IDragDropProvider.DrawDropHighlight(ISpriteBatch spriteBatch)
{
}
/// <summary>
/// Handles when the specified <see cref="IDragDropProvider"/> is dropped on this <see cref="IDragDropProvider"/>.
/// </summary>
/// <param name="source">The <see cref="IDragDropProvider"/> that is being dropped on this
/// <see cref="IDragDropProvider"/>.</param>
void IDragDropProvider.Drop(IDragDropProvider source)
{
ShopForm._dragDropHandler.Drop(source, this);
}
#endregion
}
}
}
| |
#region License
/* The MIT License
*
* Copyright (c) 2011 Red Badger Consulting
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
//-------------------------------------------------------------------------------------------------
// <auto-generated>
// Marked as auto-generated so StyleCop will ignore BDD style tests
// </auto-generated>
//-------------------------------------------------------------------------------------------------
#pragma warning disable 169
// ReSharper disable InconsistentNaming
// ReSharper disable UnusedMember.Global
// ReSharper disable UnusedMember.Local
namespace RedBadger.Xpf.Specs.UIElementSpecs
{
using Machine.Specifications;
using Moq;
using Moq.Protected;
using It = Machine.Specifications.It;
[Subject(typeof(UIElement), "Layout - explicit sizes")]
public class when_an_explicit_size_is_set : a_UIElement
{
private static readonly Size availableSize = new Size(300, 300);
private static readonly Size explicitSize = new Size(100, 100);
private Because of = () =>
{
Subject.Object.Width = explicitSize.Width;
Subject.Object.Height = explicitSize.Height;
Subject.Object.Measure(availableSize);
};
private It should_measure_its_children_with_that_size =
() =>
Subject.Protected().Verify(
MeasureOverride, Times.Once(), ItExpr.Is<Size>(size => size.Equals(explicitSize)));
}
[Subject(typeof(UIElement), "Layout - explicit sizes")]
public class when_an_explicit_size_is_set_and_the_children_want_less_space : a_UIElement_in_a_RootElement
{
private static readonly Size availableSize = new Size(300, 300);
private static readonly Size desiredSize = new Size(50, 50);
private static readonly Vector expectedVisualOffset = new Vector(125, 125);
private static readonly Size explicitSize = new Size(100, 100);
private Establish context = () =>
{
Subject.Protected().Setup<Size>(MeasureOverride, ItExpr.IsAny<Size>()).Returns(desiredSize);
Subject.Protected().Setup<Size>(ArrangeOverride, ItExpr.IsAny<Size>()).Returns(desiredSize);
};
private Because of = () =>
{
Subject.Object.Width = explicitSize.Width;
Subject.Object.Height = explicitSize.Height;
Subject.Object.Measure(availableSize);
Subject.Object.Arrange(new Rect(availableSize));
};
private It should_arrange_its_children_within_the_explicit_size =
() =>
Subject.Protected().Verify(
ArrangeOverride, Times.Once(), ItExpr.Is<Size>(size => size.Equals(explicitSize)));
private It should_have_a_desired_size_equal_to_the_size_that_was_specified =
() => Subject.Object.DesiredSize.ShouldEqual(explicitSize);
private It should_have_the_correct_visual_offset =
() => Subject.Object.VisualOffset.ShouldEqual(expectedVisualOffset);
private It should_not_clip =
() => Subject.Object.ClippingRect.ShouldEqual(Rect.Empty);
}
[Subject(typeof(UIElement), "Layout - explicit sizes")]
public class when_an_explicit_size_is_set_and_the_children_want_more_space : a_UIElement_in_a_RootElement
{
private static readonly Size availableSize = new Size(300, 300);
private static readonly Size desiredSize = new Size(200, 200);
private static readonly Vector expectedVisualOffset = new Vector(100, 100);
private static readonly Size explicitSize = new Size(100, 100);
private Establish context = () =>
{
Subject.Protected().Setup<Size>(MeasureOverride, ItExpr.IsAny<Size>()).Returns(desiredSize);
Subject.Protected().Setup<Size>(ArrangeOverride, ItExpr.IsAny<Size>()).Returns(desiredSize);
};
private Because of = () =>
{
Subject.Object.Width = explicitSize.Width;
Subject.Object.Height = explicitSize.Height;
Subject.Object.Measure(availableSize);
Subject.Object.Arrange(new Rect(availableSize));
};
private It should_arrange_its_children_within_the_unclipped_desired_size =
() =>
Subject.Protected().Verify(ArrangeOverride, Times.Once(), ItExpr.Is<Size>(size => size.Equals(desiredSize)));
private It should_clip =
() => Subject.Object.ClippingRect.ShouldEqual(new Rect(explicitSize));
private It should_have_a_desired_size_equal_to_the_size_that_was_specified =
() => Subject.Object.DesiredSize.ShouldEqual(explicitSize);
private It should_have_the_correct_visual_offset =
() => Subject.Object.VisualOffset.ShouldEqual(expectedVisualOffset);
}
[Subject(typeof(UIElement), "Layout - explicit sizes")]
public class when_a_minimum_size_is_set_and_the_children_want_less_space : a_UIElement_in_a_RootElement
{
private static readonly Size availableSize = new Size(300, 300);
private static readonly Size desiredSize = new Size(50, 50);
private static readonly Vector expectedVisualOffset = new Vector(125, 125);
private static readonly Size minimumSize = new Size(100, 100);
private Establish context = () =>
{
Subject.Protected().Setup<Size>(MeasureOverride, ItExpr.IsAny<Size>()).Returns(desiredSize);
Subject.Protected().Setup<Size>(ArrangeOverride, ItExpr.IsAny<Size>()).Returns(desiredSize);
};
private Because of = () =>
{
Subject.Object.MinWidth = minimumSize.Width;
Subject.Object.MinHeight = minimumSize.Height;
Subject.Object.Measure(availableSize);
Subject.Object.Arrange(new Rect(availableSize));
};
private It should_arrange_its_children_within_the_available_size =
() =>
Subject.Protected().Verify(
ArrangeOverride, Times.Once(), ItExpr.Is<Size>(size => size.Equals(availableSize)));
private It should_have_a_desired_size_equal_to_the_minimum_size_that_was_specified =
() => Subject.Object.DesiredSize.ShouldEqual(minimumSize);
private It should_have_the_correct_visual_offset =
() => Subject.Object.VisualOffset.ShouldEqual(expectedVisualOffset);
private It should_not_clip =
() => Subject.Object.ClippingRect.ShouldEqual(Rect.Empty);
}
[Subject(typeof(UIElement), "Layout - explicit sizes")]
public class when_a_maximum_size_is_set_and_the_children_want_more_space : a_UIElement_in_a_RootElement
{
private static readonly Size availableSize = new Size(300, 300);
private static readonly Size desiredSize = new Size(200, 200);
private static readonly Vector expectedVisualOffset = new Vector(100, 100);
private static readonly Size maximumSize = new Size(100, 100);
private Establish context = () =>
{
Subject.Protected().Setup<Size>(MeasureOverride, ItExpr.IsAny<Size>()).Returns(desiredSize);
Subject.Protected().Setup<Size>(ArrangeOverride, ItExpr.IsAny<Size>()).Returns(desiredSize);
};
private Because of = () =>
{
Subject.Object.MaxWidth = maximumSize.Width;
Subject.Object.MaxHeight = maximumSize.Height;
Subject.Object.Measure(availableSize);
Subject.Object.Arrange(new Rect(availableSize));
};
private It should_arrange_its_children_within_the_unclipped_desired_size =
() =>
Subject.Protected().Verify(ArrangeOverride, Times.Once(), ItExpr.Is<Size>(size => size.Equals(desiredSize)));
private It should_clip =
() => Subject.Object.ClippingRect.ShouldEqual(new Rect(maximumSize));
private It should_have_a_desired_size_equal_to_the_maximum_size_that_was_specified =
() => Subject.Object.DesiredSize.ShouldEqual(maximumSize);
private It should_have_the_correct_visual_offset =
() => Subject.Object.VisualOffset.ShouldEqual(expectedVisualOffset);
}
[Subject(typeof(UIElement), "Layout - Invalidate")]
public class when_measure_is_invalidated : a_Measured_and_Arranged_UIElement
{
private Establish context = () =>
{
var parentUiElement = new Mock<UIElement>();
parentUiElement.Object.Measure(Size.Empty);
parentUiElement.Object.Arrange(Rect.Empty);
Subject.Object.VisualParent = parentUiElement.Object;
};
private Because of = () => Subject.Object.InvalidateMeasure();
private It should_invalidate_arrange = () => Subject.Object.IsArrangeValid.ShouldBeFalse();
private It should_invalidate_its_parents_arrange =
() => Subject.Object.VisualParent.IsArrangeValid.ShouldBeFalse();
private It should_invalidate_its_parents_measure =
() => Subject.Object.VisualParent.IsMeasureValid.ShouldBeFalse();
private It should_invalidate_measure = () => Subject.Object.IsMeasureValid.ShouldBeFalse();
}
[Subject(typeof(UIElement), "Layout - Invalidate")]
public class when_arrange_is_invalidated : a_Measured_and_Arranged_UIElement
{
private Establish context = () =>
{
var parentUiElement = new Mock<UIElement>();
parentUiElement.Object.Measure(Size.Empty);
parentUiElement.Object.Arrange(Rect.Empty);
Subject.Object.VisualParent = parentUiElement.Object;
};
private Because of = () => Subject.Object.InvalidateArrange();
private It should_invalidate_arrange = () => Subject.Object.IsArrangeValid.ShouldBeFalse();
private It should_invalidate_its_parents_arrange =
() => Subject.Object.VisualParent.IsArrangeValid.ShouldBeFalse();
private It should_not_invalidate_its_parents_measure =
() => Subject.Object.VisualParent.IsMeasureValid.ShouldBeTrue();
private It should_not_invalidate_measure = () => Subject.Object.IsMeasureValid.ShouldBeTrue();
}
[Subject(typeof(UIElement), "Layout - Invalidate")]
public class when_height_is_changed : a_Measured_and_Arranged_UIElement
{
private Because of = () => Subject.Object.Height = 100;
private It should_invalidate_arrange = () => Subject.Object.IsArrangeValid.ShouldBeFalse();
private It should_invalidate_measure = () => Subject.Object.IsMeasureValid.ShouldBeFalse();
}
[Subject(typeof(UIElement), "Layout - Invalidate")]
public class when_minimum_height_is_changed : a_Measured_and_Arranged_UIElement
{
private Because of = () => Subject.Object.MinHeight = 100;
private It should_invalidate_arrange = () => Subject.Object.IsArrangeValid.ShouldBeFalse();
private It should_invalidate_measure = () => Subject.Object.IsMeasureValid.ShouldBeFalse();
}
[Subject(typeof(UIElement), "Layout - Invalidate")]
public class when_maximum_height_is_changed : a_Measured_and_Arranged_UIElement
{
private Because of = () => Subject.Object.MaxHeight = 100;
private It should_invalidate_arrange = () => Subject.Object.IsArrangeValid.ShouldBeFalse();
private It should_invalidate_measure = () => Subject.Object.IsMeasureValid.ShouldBeFalse();
}
[Subject(typeof(UIElement), "Layout - Invalidate")]
public class when_width_is_changed : a_Measured_and_Arranged_UIElement
{
private Because of = () => Subject.Object.Width = 100;
private It should_invalidate_arrange = () => Subject.Object.IsArrangeValid.ShouldBeFalse();
private It should_invalidate_measure = () => Subject.Object.IsMeasureValid.ShouldBeFalse();
}
[Subject(typeof(UIElement), "Layout - Invalidate")]
public class when_minimum_width_is_changed : a_Measured_and_Arranged_UIElement
{
private Because of = () => Subject.Object.MinWidth = 100;
private It should_invalidate_arrange = () => Subject.Object.IsArrangeValid.ShouldBeFalse();
private It should_invalidate_measure = () => Subject.Object.IsMeasureValid.ShouldBeFalse();
}
[Subject(typeof(UIElement), "Layout - Invalidate")]
public class when_maximum_width_is_changed : a_Measured_and_Arranged_UIElement
{
private Because of = () => Subject.Object.MaxWidth = 100;
private It should_invalidate_arrange = () => Subject.Object.IsArrangeValid.ShouldBeFalse();
private It should_invalidate_measure = () => Subject.Object.IsMeasureValid.ShouldBeFalse();
}
[Subject(typeof(UIElement), "Layout - Invalidate")]
public class when_margin_is_changed : a_Measured_and_Arranged_UIElement
{
private Because of = () => Subject.Object.Margin = new Thickness(10, 20, 30, 40);
private It should_invalidate_arrange = () => Subject.Object.IsArrangeValid.ShouldBeFalse();
private It should_invalidate_measure = () => Subject.Object.IsMeasureValid.ShouldBeFalse();
}
[Subject(typeof(UIElement), "Layout - Invalidate")]
public class when_horizontal_alignment_is_changed : a_Measured_and_Arranged_UIElement
{
private Because of = () => Subject.Object.HorizontalAlignment = HorizontalAlignment.Left;
private It should_invalidate_arrange = () => Subject.Object.IsArrangeValid.ShouldBeFalse();
private It should_not_invalidate_measure = () => Subject.Object.IsMeasureValid.ShouldBeTrue();
}
[Subject(typeof(UIElement), "Layout - Invalidate")]
public class when_vertical_alignment_is_changed : a_Measured_and_Arranged_UIElement
{
private Because of = () => Subject.Object.VerticalAlignment = VerticalAlignment.Bottom;
private It should_invalidate_arrange = () => Subject.Object.IsArrangeValid.ShouldBeFalse();
private It should_not_invalidate_measure = () => Subject.Object.IsMeasureValid.ShouldBeTrue();
}
[Subject(typeof(UIElement), "Layout - Invalidate")]
public class when_data_context_is_changed : a_Measured_and_Arranged_UIElement
{
private Because of = () => Subject.Object.DataContext = new object();
private It should_invalidate_arrange = () => Subject.Object.IsArrangeValid.ShouldBeFalse();
private It should_invalidate_measure = () => Subject.Object.IsMeasureValid.ShouldBeFalse();
}
[Subject(typeof(UIElement), "Layout - Size Change")]
public class when_the_available_size_changes : a_Measured_UIElement
{
private Because of = () => Subject.Object.Measure(new Size(200, 200));
private It should_measure_again =
() => Subject.Protected().Verify(MeasureOverride, Times.Exactly(2), ItExpr.IsAny<Size>());
}
[Subject(typeof(UIElement), "Layout - Size Change")]
public class when_the_available_size_doesnt_change_enough : a_Measured_UIElement
{
private Because of = () => Subject.Object.Measure(new Size(100.000001f, 100.000001f));
private It should_not_measure_again =
() => Subject.Protected().Verify(MeasureOverride, Times.Once(), ItExpr.IsAny<Size>());
}
[Subject(typeof(UIElement), "Layout - Size Change")]
public class when_the_final_size_changes : a_Measured_and_Arranged_UIElement
{
private Because of = () => Subject.Object.Arrange(new Rect(new Size(200, 200)));
private It should_arrange_again =
() => Subject.Protected().Verify(ArrangeOverride, Times.Exactly(2), ItExpr.IsAny<Size>());
}
[Subject(typeof(UIElement), "Layout - Size Change")]
public class when_the_final_size_doesnt_change_enough : a_Measured_and_Arranged_UIElement
{
private Because of = () => Subject.Object.Arrange(new Rect(new Size(100.000001f, 100.000001f)));
private It should_not_arrange_again =
() => Subject.Protected().Verify(ArrangeOverride, Times.Once(), ItExpr.IsAny<Size>());
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Diagnostics;
namespace System.Net.Sockets
{
public partial class SocketAsyncEventArgs : EventArgs, IDisposable
{
private int _acceptedFileDescriptor;
private int _socketAddressSize;
private SocketFlags _receivedFlags;
internal int? SendPacketsDescriptorCount { get { return null; } }
private void InitializeInternals()
{
// No-op for *nix.
}
private void FreeInternals(bool calledFromFinalizer)
{
// No-op for *nix.
}
private void SetupSingleBuffer()
{
// No-op for *nix.
}
private void SetupMultipleBuffers()
{
// No-op for *nix.
}
private void SetupSendPacketsElements()
{
// No-op for *nix.
}
private void InnerComplete()
{
// No-op for *nix.
}
private void InnerStartOperationAccept(bool userSuppliedBuffer)
{
_acceptedFileDescriptor = -1;
}
private void AcceptCompletionCallback(int acceptedFileDescriptor, byte[] socketAddress, int socketAddressSize, SocketError socketError)
{
// TODO: receive bytes on socket if requested
_acceptedFileDescriptor = acceptedFileDescriptor;
Debug.Assert(socketAddress == null || socketAddress == _acceptBuffer);
_acceptAddressBufferCount = socketAddressSize;
CompletionCallback(0, socketError);
}
internal unsafe SocketError DoOperationAccept(Socket socket, SafeCloseSocket handle, SafeCloseSocket acceptHandle, out int bytesTransferred)
{
Debug.Assert(acceptHandle == null);
bytesTransferred = 0;
return handle.AsyncContext.AcceptAsync(_buffer ?? _acceptBuffer, _acceptAddressBufferCount / 2, AcceptCompletionCallback);
}
private void InnerStartOperationConnect()
{
// No-op for *nix.
}
private void ConnectCompletionCallback(SocketError socketError)
{
CompletionCallback(0, socketError);
}
internal unsafe SocketError DoOperationConnect(Socket socket, SafeCloseSocket handle, out int bytesTransferred)
{
bytesTransferred = 0;
return handle.AsyncContext.ConnectAsync(_socketAddress.Buffer, _socketAddress.Size, ConnectCompletionCallback);
}
private void InnerStartOperationDisconnect()
{
throw new PlatformNotSupportedException();
}
internal unsafe SocketError DoOperationDisconnect(Socket socket, SafeCloseSocket handle)
{
throw new PlatformNotSupportedException();
}
private void TransferCompletionCallback(int bytesTransferred, byte[] socketAddress, int socketAddressSize, int receivedFlags, SocketError socketError)
{
Debug.Assert(socketAddress == null || socketAddress == _socketAddress.Buffer);
_socketAddressSize = socketAddressSize;
_receivedFlags = SocketPal.GetSocketFlags(receivedFlags);
CompletionCallback(bytesTransferred, socketError);
}
private void InnerStartOperationReceive()
{
_receivedFlags = System.Net.Sockets.SocketFlags.None;
_socketAddressSize = 0;
}
internal unsafe SocketError DoOperationReceive(SafeCloseSocket handle, out SocketFlags flags, out int bytesTransferred)
{
int platformFlags = SocketPal.GetPlatformSocketFlags(_socketFlags);
SocketError errorCode;
if (_buffer != null)
{
errorCode = handle.AsyncContext.ReceiveAsync(_buffer, _offset, _count, platformFlags, TransferCompletionCallback);
}
else
{
errorCode = handle.AsyncContext.ReceiveAsync(_bufferList, platformFlags, TransferCompletionCallback);
}
flags = _socketFlags;
bytesTransferred = 0;
return errorCode;
}
private void InnerStartOperationReceiveFrom()
{
_receivedFlags = System.Net.Sockets.SocketFlags.None;
_socketAddressSize = 0;
}
internal unsafe SocketError DoOperationReceiveFrom(SafeCloseSocket handle, out SocketFlags flags, out int bytesTransferred)
{
int platformFlags = SocketPal.GetPlatformSocketFlags(_socketFlags);
SocketError errorCode;
if (_buffer != null)
{
errorCode = handle.AsyncContext.ReceiveFromAsync(_buffer, _offset, _count, platformFlags, _socketAddress.Buffer, _socketAddress.Size, TransferCompletionCallback);
}
else
{
errorCode = handle.AsyncContext.ReceiveFromAsync(_bufferList, platformFlags, _socketAddress.Buffer, _socketAddress.Size, TransferCompletionCallback);
}
flags = _socketFlags;
bytesTransferred = 0;
return errorCode;
}
private void InnerStartOperationReceiveMessageFrom()
{
_receiveMessageFromPacketInfo = default(IPPacketInformation);
_receivedFlags = System.Net.Sockets.SocketFlags.None;
_socketAddressSize = 0;
}
private void ReceiveMessageFromCompletionCallback(int bytesTransferred, byte[] socketAddress, int socketAddressSize, int receivedFlags, IPPacketInformation ipPacketInformation, SocketError errorCode)
{
Debug.Assert(_socketAddress != null);
Debug.Assert(socketAddress == null || _socketAddress.Buffer == socketAddress);
_socketAddressSize = socketAddressSize;
_receivedFlags = SocketPal.GetSocketFlags(receivedFlags);
_receiveMessageFromPacketInfo = ipPacketInformation;
CompletionCallback(bytesTransferred, errorCode);
}
internal unsafe SocketError DoOperationReceiveMessageFrom(Socket socket, SafeCloseSocket handle, out int bytesTransferred)
{
int platformFlags = SocketPal.GetPlatformSocketFlags(_socketFlags);
bool isIPv4, isIPv6;
Socket.GetIPProtocolInformation(socket.AddressFamily, _socketAddress, out isIPv4, out isIPv6);
bytesTransferred = 0;
return handle.AsyncContext.ReceiveMessageFromAsync(_buffer, _offset, _count, platformFlags, _socketAddress.Buffer, _socketAddress.Size, isIPv4, isIPv6, ReceiveMessageFromCompletionCallback);
}
private void InnerStartOperationSend()
{
_receivedFlags = System.Net.Sockets.SocketFlags.None;
_socketAddressSize = 0;
}
internal unsafe SocketError DoOperationSend(SafeCloseSocket handle, out int bytesTransferred)
{
int platformFlags = SocketPal.GetPlatformSocketFlags(_socketFlags);
SocketError errorCode;
if (_buffer != null)
{
errorCode = handle.AsyncContext.SendAsync(_buffer, _offset, _count, platformFlags, TransferCompletionCallback);
}
else
{
errorCode = handle.AsyncContext.SendAsync(_bufferList, platformFlags, TransferCompletionCallback);
}
bytesTransferred = 0;
return errorCode;
}
private void InnerStartOperationSendPackets()
{
throw new PlatformNotSupportedException();
}
internal SocketError DoOperationSendPackets(Socket socket, SafeCloseSocket handle)
{
throw new PlatformNotSupportedException();
}
private void InnerStartOperationSendTo()
{
_receivedFlags = System.Net.Sockets.SocketFlags.None;
_socketAddressSize = 0;
}
internal SocketError DoOperationSendTo(SafeCloseSocket handle, out int bytesTransferred)
{
int platformFlags = SocketPal.GetPlatformSocketFlags(_socketFlags);
SocketError errorCode;
if (_buffer != null)
{
errorCode = handle.AsyncContext.SendToAsync(_buffer, _offset, _count, platformFlags, _socketAddress.Buffer, _socketAddress.Size, TransferCompletionCallback);
}
else
{
errorCode = handle.AsyncContext.SendToAsync(_bufferList, platformFlags, _socketAddress.Buffer, _socketAddress.Size, TransferCompletionCallback);
}
bytesTransferred = 0;
return errorCode;
}
internal void LogBuffer(int size)
{
// TODO: implement?
}
internal void LogSendPacketsBuffers(int size)
{
throw new PlatformNotSupportedException();
}
private SocketError FinishOperationAccept(Internals.SocketAddress remoteSocketAddress)
{
System.Buffer.BlockCopy(_acceptBuffer, 0, remoteSocketAddress.Buffer, 0, _acceptAddressBufferCount);
_acceptSocket = _currentSocket.CreateAcceptSocket(
SafeCloseSocket.CreateSocket(_acceptedFileDescriptor),
_currentSocket._rightEndPoint.Create(remoteSocketAddress));
return SocketError.Success;
}
private SocketError FinishOperationConnect()
{
// No-op for *nix.
return SocketError.Success;
}
private unsafe int GetSocketAddressSize()
{
return _socketAddressSize;
}
private unsafe void FinishOperationReceiveMessageFrom()
{
// No-op for *nix.
}
private void FinishOperationSendPackets()
{
throw new PlatformNotSupportedException();
}
private void CompletionCallback(int bytesTransferred, SocketError socketError)
{
// TODO: plumb SocketFlags through TransferOperation
if (socketError == SocketError.Success)
{
FinishOperationSuccess(socketError, bytesTransferred, _receivedFlags);
}
else
{
if (_currentSocket.CleanedUp)
{
socketError = SocketError.OperationAborted;
}
FinishOperationAsyncFailure(socketError, bytesTransferred, _receivedFlags);
}
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.5448
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
//
// This source code was auto-generated by wsdl, Version=2.0.50727.42.
//
namespace WebsitePanel.Providers.HostedSolution
{
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
using WebsitePanel.Providers.SharePoint;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name = "HostedSharePointServerSoap", Namespace = "http://smbsaas/websitepanel/server/")]
[System.Xml.Serialization.XmlIncludeAttribute(typeof(ServiceProviderItem))]
public partial class HostedSharePointServer : Microsoft.Web.Services3.WebServicesClientProtocol
{
public ServiceProviderSettingsSoapHeader ServiceProviderSettingsSoapHeaderValue;
private System.Threading.SendOrPostCallback GetSupportedLanguagesOperationCompleted;
private System.Threading.SendOrPostCallback GetSiteCollectionsOperationCompleted;
private System.Threading.SendOrPostCallback GetSiteCollectionOperationCompleted;
private System.Threading.SendOrPostCallback CreateSiteCollectionOperationCompleted;
private System.Threading.SendOrPostCallback UpdateQuotasOperationCompleted;
private System.Threading.SendOrPostCallback CalculateSiteCollectionsDiskSpaceOperationCompleted;
private System.Threading.SendOrPostCallback DeleteSiteCollectionOperationCompleted;
private System.Threading.SendOrPostCallback BackupSiteCollectionOperationCompleted;
private System.Threading.SendOrPostCallback RestoreSiteCollectionOperationCompleted;
private System.Threading.SendOrPostCallback GetTempFileBinaryChunkOperationCompleted;
private System.Threading.SendOrPostCallback AppendTempFileBinaryChunkOperationCompleted;
private System.Threading.SendOrPostCallback GetSiteCollectionSizeOperationCompleted;
private System.Threading.SendOrPostCallback SetPeoplePickerOuOperationCompleted;
/// <remarks/>
public HostedSharePointServer()
{
this.Url = "http://localhost:9003/HostedSharePointServer.asmx";
}
/// <remarks/>
public event GetSupportedLanguagesCompletedEventHandler GetSupportedLanguagesCompleted;
/// <remarks/>
public event GetSiteCollectionsCompletedEventHandler GetSiteCollectionsCompleted;
/// <remarks/>
public event GetSiteCollectionCompletedEventHandler GetSiteCollectionCompleted;
/// <remarks/>
public event CreateSiteCollectionCompletedEventHandler CreateSiteCollectionCompleted;
/// <remarks/>
public event UpdateQuotasCompletedEventHandler UpdateQuotasCompleted;
/// <remarks/>
public event CalculateSiteCollectionsDiskSpaceCompletedEventHandler CalculateSiteCollectionsDiskSpaceCompleted;
/// <remarks/>
public event DeleteSiteCollectionCompletedEventHandler DeleteSiteCollectionCompleted;
/// <remarks/>
public event BackupSiteCollectionCompletedEventHandler BackupSiteCollectionCompleted;
/// <remarks/>
public event RestoreSiteCollectionCompletedEventHandler RestoreSiteCollectionCompleted;
/// <remarks/>
public event GetTempFileBinaryChunkCompletedEventHandler GetTempFileBinaryChunkCompleted;
/// <remarks/>
public event AppendTempFileBinaryChunkCompletedEventHandler AppendTempFileBinaryChunkCompleted;
/// <remarks/>
public event GetSiteCollectionSizeCompletedEventHandler GetSiteCollectionSizeCompleted;
/// <remarks/>
public event SetPeoplePickerOuCompletedEventHandler SetPeoplePickerOuCompleted;
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/GetSupportedLanguages", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public int[] GetSupportedLanguages()
{
object[] results = this.Invoke("GetSupportedLanguages", new object[0]);
return ((int[])(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginGetSupportedLanguages(System.AsyncCallback callback, object asyncState)
{
return this.BeginInvoke("GetSupportedLanguages", new object[0], callback, asyncState);
}
/// <remarks/>
public int[] EndGetSupportedLanguages(System.IAsyncResult asyncResult)
{
object[] results = this.EndInvoke(asyncResult);
return ((int[])(results[0]));
}
/// <remarks/>
public void GetSupportedLanguagesAsync()
{
this.GetSupportedLanguagesAsync(null);
}
/// <remarks/>
public void GetSupportedLanguagesAsync(object userState)
{
if ((this.GetSupportedLanguagesOperationCompleted == null))
{
this.GetSupportedLanguagesOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetSupportedLanguagesOperationCompleted);
}
this.InvokeAsync("GetSupportedLanguages", new object[0], this.GetSupportedLanguagesOperationCompleted, userState);
}
private void OnGetSupportedLanguagesOperationCompleted(object arg)
{
if ((this.GetSupportedLanguagesCompleted != null))
{
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.GetSupportedLanguagesCompleted(this, new GetSupportedLanguagesCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/GetSiteCollections", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public SharePointSiteCollection[] GetSiteCollections()
{
object[] results = this.Invoke("GetSiteCollections", new object[0]);
return ((SharePointSiteCollection[])(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginGetSiteCollections(System.AsyncCallback callback, object asyncState)
{
return this.BeginInvoke("GetSiteCollections", new object[0], callback, asyncState);
}
/// <remarks/>
public SharePointSiteCollection[] EndGetSiteCollections(System.IAsyncResult asyncResult)
{
object[] results = this.EndInvoke(asyncResult);
return ((SharePointSiteCollection[])(results[0]));
}
/// <remarks/>
public void GetSiteCollectionsAsync()
{
this.GetSiteCollectionsAsync(null);
}
/// <remarks/>
public void GetSiteCollectionsAsync(object userState)
{
if ((this.GetSiteCollectionsOperationCompleted == null))
{
this.GetSiteCollectionsOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetSiteCollectionsOperationCompleted);
}
this.InvokeAsync("GetSiteCollections", new object[0], this.GetSiteCollectionsOperationCompleted, userState);
}
private void OnGetSiteCollectionsOperationCompleted(object arg)
{
if ((this.GetSiteCollectionsCompleted != null))
{
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.GetSiteCollectionsCompleted(this, new GetSiteCollectionsCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/GetSiteCollection", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public SharePointSiteCollection GetSiteCollection(string url)
{
object[] results = this.Invoke("GetSiteCollection", new object[] {
url});
return ((SharePointSiteCollection)(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginGetSiteCollection(string url, System.AsyncCallback callback, object asyncState)
{
return this.BeginInvoke("GetSiteCollection", new object[] {
url}, callback, asyncState);
}
/// <remarks/>
public SharePointSiteCollection EndGetSiteCollection(System.IAsyncResult asyncResult)
{
object[] results = this.EndInvoke(asyncResult);
return ((SharePointSiteCollection)(results[0]));
}
/// <remarks/>
public void GetSiteCollectionAsync(string url)
{
this.GetSiteCollectionAsync(url, null);
}
/// <remarks/>
public void GetSiteCollectionAsync(string url, object userState)
{
if ((this.GetSiteCollectionOperationCompleted == null))
{
this.GetSiteCollectionOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetSiteCollectionOperationCompleted);
}
this.InvokeAsync("GetSiteCollection", new object[] {
url}, this.GetSiteCollectionOperationCompleted, userState);
}
private void OnGetSiteCollectionOperationCompleted(object arg)
{
if ((this.GetSiteCollectionCompleted != null))
{
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.GetSiteCollectionCompleted(this, new GetSiteCollectionCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/CreateSiteCollection", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public void CreateSiteCollection(SharePointSiteCollection siteCollection)
{
this.Invoke("CreateSiteCollection", new object[] {
siteCollection});
}
/// <remarks/>
public System.IAsyncResult BeginCreateSiteCollection(SharePointSiteCollection siteCollection, System.AsyncCallback callback, object asyncState)
{
return this.BeginInvoke("CreateSiteCollection", new object[] {
siteCollection}, callback, asyncState);
}
/// <remarks/>
public void EndCreateSiteCollection(System.IAsyncResult asyncResult)
{
this.EndInvoke(asyncResult);
}
/// <remarks/>
public void CreateSiteCollectionAsync(SharePointSiteCollection siteCollection)
{
this.CreateSiteCollectionAsync(siteCollection, null);
}
/// <remarks/>
public void CreateSiteCollectionAsync(SharePointSiteCollection siteCollection, object userState)
{
if ((this.CreateSiteCollectionOperationCompleted == null))
{
this.CreateSiteCollectionOperationCompleted = new System.Threading.SendOrPostCallback(this.OnCreateSiteCollectionOperationCompleted);
}
this.InvokeAsync("CreateSiteCollection", new object[] {
siteCollection}, this.CreateSiteCollectionOperationCompleted, userState);
}
private void OnCreateSiteCollectionOperationCompleted(object arg)
{
if ((this.CreateSiteCollectionCompleted != null))
{
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.CreateSiteCollectionCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/UpdateQuotas", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public void UpdateQuotas(string url, long maxSize, long warningSize)
{
this.Invoke("UpdateQuotas", new object[] {
url,
maxSize,
warningSize});
}
/// <remarks/>
public System.IAsyncResult BeginUpdateQuotas(string url, long maxSize, long warningSize, System.AsyncCallback callback, object asyncState)
{
return this.BeginInvoke("UpdateQuotas", new object[] {
url,
maxSize,
warningSize}, callback, asyncState);
}
/// <remarks/>
public void EndUpdateQuotas(System.IAsyncResult asyncResult)
{
this.EndInvoke(asyncResult);
}
/// <remarks/>
public void UpdateQuotasAsync(string url, long maxSize, long warningSize)
{
this.UpdateQuotasAsync(url, maxSize, warningSize, null);
}
/// <remarks/>
public void UpdateQuotasAsync(string url, long maxSize, long warningSize, object userState)
{
if ((this.UpdateQuotasOperationCompleted == null))
{
this.UpdateQuotasOperationCompleted = new System.Threading.SendOrPostCallback(this.OnUpdateQuotasOperationCompleted);
}
this.InvokeAsync("UpdateQuotas", new object[] {
url,
maxSize,
warningSize}, this.UpdateQuotasOperationCompleted, userState);
}
private void OnUpdateQuotasOperationCompleted(object arg)
{
if ((this.UpdateQuotasCompleted != null))
{
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.UpdateQuotasCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/CalculateSiteCollectionsDiskSpace", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public SharePointSiteDiskSpace[] CalculateSiteCollectionsDiskSpace(string[] urls)
{
object[] results = this.Invoke("CalculateSiteCollectionsDiskSpace", new object[] {
urls});
return ((SharePointSiteDiskSpace[])(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginCalculateSiteCollectionsDiskSpace(string[] urls, System.AsyncCallback callback, object asyncState)
{
return this.BeginInvoke("CalculateSiteCollectionsDiskSpace", new object[] {
urls}, callback, asyncState);
}
/// <remarks/>
public SharePointSiteDiskSpace[] EndCalculateSiteCollectionsDiskSpace(System.IAsyncResult asyncResult)
{
object[] results = this.EndInvoke(asyncResult);
return ((SharePointSiteDiskSpace[])(results[0]));
}
/// <remarks/>
public void CalculateSiteCollectionsDiskSpaceAsync(string[] urls)
{
this.CalculateSiteCollectionsDiskSpaceAsync(urls, null);
}
/// <remarks/>
public void CalculateSiteCollectionsDiskSpaceAsync(string[] urls, object userState)
{
if ((this.CalculateSiteCollectionsDiskSpaceOperationCompleted == null))
{
this.CalculateSiteCollectionsDiskSpaceOperationCompleted = new System.Threading.SendOrPostCallback(this.OnCalculateSiteCollectionsDiskSpaceOperationCompleted);
}
this.InvokeAsync("CalculateSiteCollectionsDiskSpace", new object[] {
urls}, this.CalculateSiteCollectionsDiskSpaceOperationCompleted, userState);
}
private void OnCalculateSiteCollectionsDiskSpaceOperationCompleted(object arg)
{
if ((this.CalculateSiteCollectionsDiskSpaceCompleted != null))
{
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.CalculateSiteCollectionsDiskSpaceCompleted(this, new CalculateSiteCollectionsDiskSpaceCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/DeleteSiteCollection", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public void DeleteSiteCollection(SharePointSiteCollection siteCollection)
{
this.Invoke("DeleteSiteCollection", new object[] {
siteCollection});
}
/// <remarks/>
public System.IAsyncResult BeginDeleteSiteCollection(SharePointSiteCollection siteCollection, System.AsyncCallback callback, object asyncState)
{
return this.BeginInvoke("DeleteSiteCollection", new object[] {
siteCollection}, callback, asyncState);
}
/// <remarks/>
public void EndDeleteSiteCollection(System.IAsyncResult asyncResult)
{
this.EndInvoke(asyncResult);
}
/// <remarks/>
public void DeleteSiteCollectionAsync(SharePointSiteCollection siteCollection)
{
this.DeleteSiteCollectionAsync(siteCollection, null);
}
/// <remarks/>
public void DeleteSiteCollectionAsync(SharePointSiteCollection siteCollection, object userState)
{
if ((this.DeleteSiteCollectionOperationCompleted == null))
{
this.DeleteSiteCollectionOperationCompleted = new System.Threading.SendOrPostCallback(this.OnDeleteSiteCollectionOperationCompleted);
}
this.InvokeAsync("DeleteSiteCollection", new object[] {
siteCollection}, this.DeleteSiteCollectionOperationCompleted, userState);
}
private void OnDeleteSiteCollectionOperationCompleted(object arg)
{
if ((this.DeleteSiteCollectionCompleted != null))
{
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.DeleteSiteCollectionCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/BackupSiteCollection", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public string BackupSiteCollection(string url, string filename, bool zip)
{
object[] results = this.Invoke("BackupSiteCollection", new object[] {
url,
filename,
zip});
return ((string)(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginBackupSiteCollection(string url, string filename, bool zip, System.AsyncCallback callback, object asyncState)
{
return this.BeginInvoke("BackupSiteCollection", new object[] {
url,
filename,
zip}, callback, asyncState);
}
/// <remarks/>
public string EndBackupSiteCollection(System.IAsyncResult asyncResult)
{
object[] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
/// <remarks/>
public void BackupSiteCollectionAsync(string url, string filename, bool zip)
{
this.BackupSiteCollectionAsync(url, filename, zip, null);
}
/// <remarks/>
public void BackupSiteCollectionAsync(string url, string filename, bool zip, object userState)
{
if ((this.BackupSiteCollectionOperationCompleted == null))
{
this.BackupSiteCollectionOperationCompleted = new System.Threading.SendOrPostCallback(this.OnBackupSiteCollectionOperationCompleted);
}
this.InvokeAsync("BackupSiteCollection", new object[] {
url,
filename,
zip}, this.BackupSiteCollectionOperationCompleted, userState);
}
private void OnBackupSiteCollectionOperationCompleted(object arg)
{
if ((this.BackupSiteCollectionCompleted != null))
{
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.BackupSiteCollectionCompleted(this, new BackupSiteCollectionCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/RestoreSiteCollection", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public void RestoreSiteCollection(SharePointSiteCollection siteCollection, string filename)
{
this.Invoke("RestoreSiteCollection", new object[] {
siteCollection,
filename});
}
/// <remarks/>
public System.IAsyncResult BeginRestoreSiteCollection(SharePointSiteCollection siteCollection, string filename, System.AsyncCallback callback, object asyncState)
{
return this.BeginInvoke("RestoreSiteCollection", new object[] {
siteCollection,
filename}, callback, asyncState);
}
/// <remarks/>
public void EndRestoreSiteCollection(System.IAsyncResult asyncResult)
{
this.EndInvoke(asyncResult);
}
/// <remarks/>
public void RestoreSiteCollectionAsync(SharePointSiteCollection siteCollection, string filename)
{
this.RestoreSiteCollectionAsync(siteCollection, filename, null);
}
/// <remarks/>
public void RestoreSiteCollectionAsync(SharePointSiteCollection siteCollection, string filename, object userState)
{
if ((this.RestoreSiteCollectionOperationCompleted == null))
{
this.RestoreSiteCollectionOperationCompleted = new System.Threading.SendOrPostCallback(this.OnRestoreSiteCollectionOperationCompleted);
}
this.InvokeAsync("RestoreSiteCollection", new object[] {
siteCollection,
filename}, this.RestoreSiteCollectionOperationCompleted, userState);
}
private void OnRestoreSiteCollectionOperationCompleted(object arg)
{
if ((this.RestoreSiteCollectionCompleted != null))
{
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.RestoreSiteCollectionCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/GetTempFileBinaryChunk", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
[return: System.Xml.Serialization.XmlElementAttribute(DataType = "base64Binary")]
public byte[] GetTempFileBinaryChunk(string path, int offset, int length)
{
object[] results = this.Invoke("GetTempFileBinaryChunk", new object[] {
path,
offset,
length});
return ((byte[])(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginGetTempFileBinaryChunk(string path, int offset, int length, System.AsyncCallback callback, object asyncState)
{
return this.BeginInvoke("GetTempFileBinaryChunk", new object[] {
path,
offset,
length}, callback, asyncState);
}
/// <remarks/>
public byte[] EndGetTempFileBinaryChunk(System.IAsyncResult asyncResult)
{
object[] results = this.EndInvoke(asyncResult);
return ((byte[])(results[0]));
}
/// <remarks/>
public void GetTempFileBinaryChunkAsync(string path, int offset, int length)
{
this.GetTempFileBinaryChunkAsync(path, offset, length, null);
}
/// <remarks/>
public void GetTempFileBinaryChunkAsync(string path, int offset, int length, object userState)
{
if ((this.GetTempFileBinaryChunkOperationCompleted == null))
{
this.GetTempFileBinaryChunkOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetTempFileBinaryChunkOperationCompleted);
}
this.InvokeAsync("GetTempFileBinaryChunk", new object[] {
path,
offset,
length}, this.GetTempFileBinaryChunkOperationCompleted, userState);
}
private void OnGetTempFileBinaryChunkOperationCompleted(object arg)
{
if ((this.GetTempFileBinaryChunkCompleted != null))
{
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.GetTempFileBinaryChunkCompleted(this, new GetTempFileBinaryChunkCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/AppendTempFileBinaryChunk", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public string AppendTempFileBinaryChunk(string fileName, string path, [System.Xml.Serialization.XmlElementAttribute(DataType = "base64Binary")] byte[] chunk)
{
object[] results = this.Invoke("AppendTempFileBinaryChunk", new object[] {
fileName,
path,
chunk});
return ((string)(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginAppendTempFileBinaryChunk(string fileName, string path, byte[] chunk, System.AsyncCallback callback, object asyncState)
{
return this.BeginInvoke("AppendTempFileBinaryChunk", new object[] {
fileName,
path,
chunk}, callback, asyncState);
}
/// <remarks/>
public string EndAppendTempFileBinaryChunk(System.IAsyncResult asyncResult)
{
object[] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
/// <remarks/>
public void AppendTempFileBinaryChunkAsync(string fileName, string path, byte[] chunk)
{
this.AppendTempFileBinaryChunkAsync(fileName, path, chunk, null);
}
/// <remarks/>
public void AppendTempFileBinaryChunkAsync(string fileName, string path, byte[] chunk, object userState)
{
if ((this.AppendTempFileBinaryChunkOperationCompleted == null))
{
this.AppendTempFileBinaryChunkOperationCompleted = new System.Threading.SendOrPostCallback(this.OnAppendTempFileBinaryChunkOperationCompleted);
}
this.InvokeAsync("AppendTempFileBinaryChunk", new object[] {
fileName,
path,
chunk}, this.AppendTempFileBinaryChunkOperationCompleted, userState);
}
private void OnAppendTempFileBinaryChunkOperationCompleted(object arg)
{
if ((this.AppendTempFileBinaryChunkCompleted != null))
{
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.AppendTempFileBinaryChunkCompleted(this, new AppendTempFileBinaryChunkCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/GetSiteCollectionSize", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public long GetSiteCollectionSize(string url)
{
object[] results = this.Invoke("GetSiteCollectionSize", new object[] {
url});
return ((long)(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginGetSiteCollectionSize(string url, System.AsyncCallback callback, object asyncState)
{
return this.BeginInvoke("GetSiteCollectionSize", new object[] {
url}, callback, asyncState);
}
/// <remarks/>
public long EndGetSiteCollectionSize(System.IAsyncResult asyncResult)
{
object[] results = this.EndInvoke(asyncResult);
return ((long)(results[0]));
}
/// <remarks/>
public void GetSiteCollectionSizeAsync(string url)
{
this.GetSiteCollectionSizeAsync(url, null);
}
/// <remarks/>
public void GetSiteCollectionSizeAsync(string url, object userState)
{
if ((this.GetSiteCollectionSizeOperationCompleted == null))
{
this.GetSiteCollectionSizeOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetSiteCollectionSizeOperationCompleted);
}
this.InvokeAsync("GetSiteCollectionSize", new object[] {
url}, this.GetSiteCollectionSizeOperationCompleted, userState);
}
private void OnGetSiteCollectionSizeOperationCompleted(object arg)
{
if ((this.GetSiteCollectionSizeCompleted != null))
{
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.GetSiteCollectionSizeCompleted(this, new GetSiteCollectionSizeCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/SetPeoplePickerOu", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public void SetPeoplePickerOu(string site, string ou)
{
this.Invoke("SetPeoplePickerOu", new object[] {
site,
ou});
}
/// <remarks/>
public System.IAsyncResult BeginSetPeoplePickerOu(string site, string ou, System.AsyncCallback callback, object asyncState)
{
return this.BeginInvoke("SetPeoplePickerOu", new object[] {
site,
ou}, callback, asyncState);
}
/// <remarks/>
public void EndSetPeoplePickerOu(System.IAsyncResult asyncResult)
{
this.EndInvoke(asyncResult);
}
/// <remarks/>
public void SetPeoplePickerOuAsync(string site, string ou)
{
this.SetPeoplePickerOuAsync(site, ou, null);
}
/// <remarks/>
public void SetPeoplePickerOuAsync(string site, string ou, object userState)
{
if ((this.SetPeoplePickerOuOperationCompleted == null))
{
this.SetPeoplePickerOuOperationCompleted = new System.Threading.SendOrPostCallback(this.OnSetPeoplePickerOuOperationCompleted);
}
this.InvokeAsync("SetPeoplePickerOu", new object[] {
site,
ou}, this.SetPeoplePickerOuOperationCompleted, userState);
}
private void OnSetPeoplePickerOuOperationCompleted(object arg)
{
if ((this.SetPeoplePickerOuCompleted != null))
{
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.SetPeoplePickerOuCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
public new void CancelAsync(object userState)
{
base.CancelAsync(userState);
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void GetSupportedLanguagesCompletedEventHandler(object sender, GetSupportedLanguagesCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class GetSupportedLanguagesCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs
{
private object[] results;
internal GetSupportedLanguagesCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState)
{
this.results = results;
}
/// <remarks/>
public int[] Result
{
get
{
this.RaiseExceptionIfNecessary();
return ((int[])(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void GetSiteCollectionsCompletedEventHandler(object sender, GetSiteCollectionsCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class GetSiteCollectionsCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs
{
private object[] results;
internal GetSiteCollectionsCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState)
{
this.results = results;
}
/// <remarks/>
public SharePointSiteCollection[] Result
{
get
{
this.RaiseExceptionIfNecessary();
return ((SharePointSiteCollection[])(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void GetSiteCollectionCompletedEventHandler(object sender, GetSiteCollectionCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class GetSiteCollectionCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs
{
private object[] results;
internal GetSiteCollectionCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState)
{
this.results = results;
}
/// <remarks/>
public SharePointSiteCollection Result
{
get
{
this.RaiseExceptionIfNecessary();
return ((SharePointSiteCollection)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void CreateSiteCollectionCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void UpdateQuotasCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void CalculateSiteCollectionsDiskSpaceCompletedEventHandler(object sender, CalculateSiteCollectionsDiskSpaceCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class CalculateSiteCollectionsDiskSpaceCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs
{
private object[] results;
internal CalculateSiteCollectionsDiskSpaceCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState)
{
this.results = results;
}
/// <remarks/>
public SharePointSiteDiskSpace[] Result
{
get
{
this.RaiseExceptionIfNecessary();
return ((SharePointSiteDiskSpace[])(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void DeleteSiteCollectionCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void BackupSiteCollectionCompletedEventHandler(object sender, BackupSiteCollectionCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class BackupSiteCollectionCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs
{
private object[] results;
internal BackupSiteCollectionCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState)
{
this.results = results;
}
/// <remarks/>
public string Result
{
get
{
this.RaiseExceptionIfNecessary();
return ((string)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void RestoreSiteCollectionCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void GetTempFileBinaryChunkCompletedEventHandler(object sender, GetTempFileBinaryChunkCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class GetTempFileBinaryChunkCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs
{
private object[] results;
internal GetTempFileBinaryChunkCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState)
{
this.results = results;
}
/// <remarks/>
public byte[] Result
{
get
{
this.RaiseExceptionIfNecessary();
return ((byte[])(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void AppendTempFileBinaryChunkCompletedEventHandler(object sender, AppendTempFileBinaryChunkCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class AppendTempFileBinaryChunkCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs
{
private object[] results;
internal AppendTempFileBinaryChunkCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState)
{
this.results = results;
}
/// <remarks/>
public string Result
{
get
{
this.RaiseExceptionIfNecessary();
return ((string)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void GetSiteCollectionSizeCompletedEventHandler(object sender, GetSiteCollectionSizeCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class GetSiteCollectionSizeCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs
{
private object[] results;
internal GetSiteCollectionSizeCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState)
{
this.results = results;
}
/// <remarks/>
public long Result
{
get
{
this.RaiseExceptionIfNecessary();
return ((long)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void SetPeoplePickerOuCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e);
}
| |
using Xunit;
namespace Jint.Tests.Ecma
{
public class Test_15_2_3_13 : EcmaTest
{
[Fact]
[Trait("Category", "15.2.3.13")]
public void ObjectIsextensibleMustExistAsAFunction()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-0-1.js", false);
}
[Fact]
[Trait("Category", "15.2.3.13")]
public void ObjectIsextensibleMustExistAsAFunctionTaking1Parameter()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-0-2.js", false);
}
[Fact]
[Trait("Category", "15.2.3.13")]
public void ANewlyCreatedObjectUsingTheObjectContructorHasItsExtensiblePropertySetToTrueByDefault15221Step8()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-0-3.js", false);
}
[Fact]
[Trait("Category", "15.2.3.13")]
public void ObjectIsextensibleThrowsTypeerrorIfOIsUndefined()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-1-1.js", false);
}
[Fact]
[Trait("Category", "15.2.3.13")]
public void ObjectIsextensibleThrowsTypeerrorIfOIsNull()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-1-2.js", false);
}
[Fact]
[Trait("Category", "15.2.3.13")]
public void ObjectIsextensibleThrowsTypeerrorIfOIsABoolean()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-1-3.js", false);
}
[Fact]
[Trait("Category", "15.2.3.13")]
public void ObjectIsextensibleThrowsTypeerrorIfOIsAString()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-1-4.js", false);
}
[Fact]
[Trait("Category", "15.2.3.13")]
public void ObjectIsextensibleThrowsTypeerrorIfTypeOfFirstParamIsNotObject()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-1.js", false);
}
[Fact]
[Trait("Category", "15.2.3.13")]
public void ObjectIsextensibleReturnsTrueForAllBuiltInObjectsGlobal()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-2-1.js", false);
}
[Fact]
[Trait("Category", "15.2.3.13")]
public void ObjectIsextensibleReturnsTrueForAllBuiltInObjectsRegexp()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-2-10.js", false);
}
[Fact]
[Trait("Category", "15.2.3.13")]
public void ObjectIsextensibleReturnsTrueForAllBuiltInObjectsError()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-2-11.js", false);
}
[Fact]
[Trait("Category", "15.2.3.13")]
public void ObjectIsextensibleReturnsTrueForAllBuiltInObjectsJson()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-2-12.js", false);
}
[Fact]
[Trait("Category", "15.2.3.13")]
public void ObjectIsextensibleReturnsTrueForAllBuiltInObjectsFunctionConstructor()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-2-13.js", false);
}
[Fact]
[Trait("Category", "15.2.3.13")]
public void ObjectIsextensibleReturnsTrueForAllBuiltInObjectsFunctionPrototype()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-2-14.js", false);
}
[Fact]
[Trait("Category", "15.2.3.13")]
public void ObjectIsextensibleReturnsTrueForAllBuiltInObjectsArrayPrototype()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-2-15.js", false);
}
[Fact]
[Trait("Category", "15.2.3.13")]
public void ObjectIsextensibleReturnsTrueForAllBuiltInObjectsStringPrototype()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-2-16.js", false);
}
[Fact]
[Trait("Category", "15.2.3.13")]
public void ObjectIsextensibleReturnsTrueForAllBuiltInObjectsBooleanPrototype()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-2-17.js", false);
}
[Fact]
[Trait("Category", "15.2.3.13")]
public void ObjectIsextensibleReturnsTrueForAllBuiltInObjectsNumberPrototype()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-2-18.js", false);
}
[Fact]
[Trait("Category", "15.2.3.13")]
public void ObjectIsextensibleReturnsTrueForAllBuiltInObjectsDatePrototype()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-2-19.js", false);
}
[Fact]
[Trait("Category", "15.2.3.13")]
public void ObjectIsextensibleReturnsTrueForAllBuiltInObjectsObject()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-2-2.js", false);
}
[Fact]
[Trait("Category", "15.2.3.13")]
public void ObjectIsextensibleReturnsTrueForAllBuiltInObjectsRegexpPrototype()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-2-20.js", false);
}
[Fact]
[Trait("Category", "15.2.3.13")]
public void FunctionConstructorFunctionPrototypeArrayPrototypeStringPrototypeBooleanPrototypeNumberPrototypeDatePrototypeRegexpPrototypeErrorPrototype()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-2-21.js", false);
}
[Fact]
[Trait("Category", "15.2.3.13")]
public void ObjectIsextensibleReturnsTrueIfOIsExtensible()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-2-22.js", false);
}
[Fact]
[Trait("Category", "15.2.3.13")]
public void ObjectIsextensibleReturnsFalseIfOIsNotExtensible()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-2-23.js", false);
}
[Fact]
[Trait("Category", "15.2.3.13")]
public void ObjectIsextensibleReturnsTrueIfOIsExtensibleAndHasAPrototypeThatIsExtensible()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-2-24.js", false);
}
[Fact]
[Trait("Category", "15.2.3.13")]
public void ObjectIsextensibleReturnsTrueIfOIsExtensibleAndHasAPrototypeThatIsNotExtensible()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-2-25.js", false);
}
[Fact]
[Trait("Category", "15.2.3.13")]
public void ObjectIsextensibleReturnsFalseIfOIsNotExtensibleAndHasAPrototypeThatIsExtensible()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-2-26.js", false);
}
[Fact]
[Trait("Category", "15.2.3.13")]
public void ObjectIsextensibleReturnsFalseIfOIsNotExtensibleAndHasAPrototypeThatIsNotExtensible()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-2-27.js", false);
}
[Fact]
[Trait("Category", "15.2.3.13")]
public void ObjectIsextensibleReturnsTrueForTheGlobalObject()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-2-29.js", false);
}
[Fact]
[Trait("Category", "15.2.3.13")]
public void ObjectIsextensibleReturnsTrueForAllBuiltInObjectsFunction()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-2-3.js", false);
}
[Fact]
[Trait("Category", "15.2.3.13")]
public void ObjectIsextensibleReturnsTrueForAllBuiltInObjectsArray()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-2-4.js", false);
}
[Fact]
[Trait("Category", "15.2.3.13")]
public void ObjectIsextensibleReturnsTrueForAllBuiltInObjectsString()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-2-5.js", false);
}
[Fact]
[Trait("Category", "15.2.3.13")]
public void ObjectIsextensibleReturnsTrueForAllBuiltInObjectsBoolean()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-2-6.js", false);
}
[Fact]
[Trait("Category", "15.2.3.13")]
public void ObjectIsextensibleReturnsTrueForAllBuiltInObjectsNumber()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-2-7.js", false);
}
[Fact]
[Trait("Category", "15.2.3.13")]
public void ObjectIsextensibleReturnsTrueForAllBuiltInObjectsMath()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-2-8.js", false);
}
[Fact]
[Trait("Category", "15.2.3.13")]
public void ObjectIsextensibleReturnsTrueForAllBuiltInObjectsDate()
{
RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-2-9.js", false);
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// 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.IO;
using System.Text;
using System.Threading.Tasks;
using Microsoft.PythonTools.Parsing;
using Microsoft.PythonTools.Parsing.Ast;
namespace Microsoft.PythonTools.Debugger {
class PythonStackFrame {
private int _lineNo; // mutates on set next line
private readonly string _frameName, _filename;
private readonly int _argCount, _frameId;
private readonly int _startLine, _endLine;
private PythonEvaluationResult[] _variables;
private readonly PythonThread _thread;
private readonly FrameKind _kind;
public PythonStackFrame(PythonThread thread, string frameName, string filename, int startLine, int endLine, int lineNo, int argCount, int frameId, FrameKind kind) {
_thread = thread;
_frameName = frameName;
_filename = filename;
_argCount = argCount;
_lineNo = lineNo;
_frameId = frameId;
_startLine = startLine;
_endLine = endLine;
_kind = kind;
}
/// <summary>
/// The line nubmer where the current function/class/module starts
/// </summary>
public int StartLine {
get {
return _startLine;
}
}
/// <summary>
/// The line number where the current function/class/module ends.
/// </summary>
public int EndLine {
get {
return _endLine;
}
}
public PythonThread Thread {
get {
return _thread;
}
}
public int LineNo {
get {
return _lineNo;
}
set {
_lineNo = value;
}
}
public string FunctionName {
get {
return _frameName;
}
}
public string FileName {
get {
return _thread.Process.MapFile(_filename, toDebuggee: false);
}
}
public FrameKind Kind {
get {
return _kind;
}
}
/// <summary>
/// Gets the ID of the frame. Frame 0 is the currently executing frame, 1 is the caller of the currently executing frame, etc...
/// </summary>
public int FrameId {
get {
return _frameId;
}
}
internal void SetVariables(PythonEvaluationResult[] variables) {
_variables = variables;
}
public IList<PythonEvaluationResult> Locals {
get {
PythonEvaluationResult[] res = new PythonEvaluationResult[_variables.Length - _argCount];
for (int i = _argCount; i < _variables.Length; i++) {
res[i - _argCount] = _variables[i];
}
return res;
}
}
public IList<PythonEvaluationResult> Parameters {
get {
PythonEvaluationResult[] res = new PythonEvaluationResult[_argCount];
for (int i = 0; i < _argCount; i++) {
res[i] = _variables[i];
}
return res;
}
}
/// <summary>
/// Attempts to parse the given text. Returns true if the text is a valid expression. Returns false if the text is not
/// a valid expression and assigns the error messages produced to errorMsg.
/// </summary>
public virtual bool TryParseText(string text, out string errorMsg) {
CollectingErrorSink errorSink = new CollectingErrorSink();
Parser parser = Parser.CreateParser(new StringReader(text), _thread.Process.LanguageVersion, new ParserOptions() { ErrorSink = errorSink });
var ast = parser.ParseSingleStatement();
if (errorSink.Errors.Count > 0) {
StringBuilder msg = new StringBuilder();
foreach (var error in errorSink.Errors) {
msg.Append(error.Message);
msg.Append(Environment.NewLine);
}
errorMsg = msg.ToString();
return false;
}
errorMsg = null;
return true;
}
/// <summary>
/// Executes the given text against this stack frame.
/// </summary>
/// <param name="text"></param>
public void ExecuteText(string text, Action<PythonEvaluationResult> completion) {
ExecuteText(text, PythonEvaluationResultReprKind.Normal, completion);
}
public void ExecuteText(string text, PythonEvaluationResultReprKind reprKind, Action<PythonEvaluationResult> completion) {
_thread.Process.ExecuteText(text, reprKind, this, completion);
}
public Task<PythonEvaluationResult> ExecuteTextAsync(string text, PythonEvaluationResultReprKind reprKind = PythonEvaluationResultReprKind.Normal) {
var tcs = new TaskCompletionSource<PythonEvaluationResult>();
EventHandler<ProcessExitedEventArgs> processExited = delegate {
tcs.TrySetCanceled();
};
tcs.Task.ContinueWith(_ => _thread.Process.ProcessExited -= processExited);
_thread.Process.ProcessExited += processExited;
ExecuteText(text, reprKind, result => {
tcs.TrySetResult(result);
});
return tcs.Task;
}
/// <summary>
/// Sets the line number that this current frame is executing. Returns true
/// if the line was successfully set or false if the line number cannot be changed
/// to this line.
/// </summary>
public bool SetLineNumber(int lineNo) {
return _thread.Process.SetLineNumber(this, lineNo);
}
public string GetQualifiedFunctionName() {
return GetQualifiedFunctionName(_thread.Process, FileName, LineNo, FunctionName);
}
/// <summary>
/// Computes the fully qualified function name, including name of the enclosing class for methods,
/// and, recursively, names of any outer functions.
/// </summary>
/// <example>
/// Given this code:
/// <code>
/// class A:
/// def b(self):
/// def c():
/// class D:
/// def e(self):
/// pass
/// </code>
/// And with the current statement being <c>pass</c>, the qualified name is "D.e in c in A.b".
/// </example>
public static string GetQualifiedFunctionName(PythonProcess process, string filename, int lineNo, string functionName) {
var ast = process.GetAst(filename);
if (ast == null) {
return functionName;
}
var walker = new QualifiedFunctionNameWalker(ast, lineNo, functionName);
try {
ast.Walk(walker);
} catch (InvalidDataException) {
// Walker ran into a mismatch between expected function name and AST, so we cannot
// rely on AST to construct an accurate qualified name. Just return what we have.
return functionName;
}
string qualName = walker.Name;
if (string.IsNullOrEmpty(qualName)) {
return functionName;
}
return qualName;
}
private class QualifiedFunctionNameWalker : PythonWalker {
private PythonAst _ast;
private int _lineNumber;
private StringBuilder _name = new StringBuilder();
private readonly string _expectedFuncName;
public QualifiedFunctionNameWalker(PythonAst ast, int lineNumber, string expectedFuncName) {
_ast = ast;
_lineNumber = lineNumber;
_expectedFuncName = expectedFuncName;
}
public string Name {
get { return _name.ToString(); }
}
public override void PostWalk(FunctionDefinition node) {
int start = node.GetStart(_ast).Line;
int end = node.Body.GetEnd(_ast).Line + 1;
if (_lineNumber < start || _lineNumber >= end) {
return;
}
string funcName = node.Name;
if (_name.Length == 0 && funcName != _expectedFuncName) {
// The innermost function name must match the one that we've got from the code object.
// If it doesn't, the source code that we're parsing is out of sync with the running program,
// and cannot be used to compute the fully qualified name.
throw new InvalidDataException();
}
for (var classDef = node.Parent as ClassDefinition; classDef != null; classDef = classDef.Parent as ClassDefinition) {
funcName = classDef.Name + "." + funcName;
}
if (_name.Length != 0) {
_name.Append(" in ");
}
_name.Append(funcName);
}
}
}
class DjangoStackFrame : PythonStackFrame {
private readonly string _sourceFile;
private readonly int _sourceLine;
public DjangoStackFrame(PythonThread thread, string frameName, string filename, int startLine, int endLine, int lineNo, int argCount, int frameId, string sourceFile, int sourceLine)
: base(thread, frameName, filename, startLine, endLine, lineNo, argCount, frameId, FrameKind.Django) {
_sourceFile = sourceFile;
_sourceLine = sourceLine;
}
/// <summary>
/// The source .py file which implements the template logic. The normal filename is the
/// name of the template it's self.
/// </summary>
public string SourceFile {
get {
return _sourceFile;
}
}
/// <summary>
/// The line in the source .py file which implements the template logic.
/// </summary>
public int SourceLine {
get {
return _sourceLine;
}
}
}
}
| |
//
// System.IO.MemoryStreamTest
//
// Authors:
// Marcin Szczepanski (marcins@zipworld.com.au)
// Gonzalo Paniagua Javier (gonzalo@ximian.com)
// Sebastien Pouliot <sebastien@ximian.com>
//
// (c) 2003 Ximian, Inc. (http://www.ximian.com)
// Copyright (C) 2004 Novell (http://www.novell.com)
//
using NUnit.Framework;
using System.IO;
using System;
using System.Text;
namespace MonoTests.System.IO
{
[TestFixture]
public class MemoryStreamTest : Assertion
{
MemoryStream testStream;
byte [] testStreamData;
[SetUp]
public void SetUp ()
{
testStreamData = new byte [100];
for (int i = 0; i < 100; i++)
testStreamData[i] = (byte) (100 - i);
testStream = new MemoryStream (testStreamData);
}
//
// Verify that the first count bytes in testBytes are the same as
// the count bytes from index start in testStreamData
//
void VerifyTestData (string id, byte [] testBytes, int start, int count)
{
if (testBytes == null)
Fail (id + "+1 testBytes is null");
if (start < 0 ||
count < 0 ||
start + count > testStreamData.Length ||
start > testStreamData.Length)
throw new ArgumentOutOfRangeException (id + "+2");
for (int test = 0; test < count; test++) {
if (testBytes [test] == testStreamData [start + test])
continue;
string failStr = "testByte {0} (testStream {1}) was <{2}>, expecting <{3}>";
failStr = String.Format (failStr,
test,
start + test,
testBytes [test],
testStreamData [start + test]);
Fail (id + "-3" + failStr);
}
}
[Test]
public void ConstructorsOne ()
{
MemoryStream ms = new MemoryStream();
AssertEquals ("#01", 0L, ms.Length);
AssertEquals ("#02", 0, ms.Capacity);
AssertEquals ("#03", true, ms.CanWrite);
}
[Test]
public void ConstructorsTwo ()
{
MemoryStream ms = new MemoryStream (10);
AssertEquals ("#01", 0L, ms.Length);
AssertEquals ("#02", 10, ms.Capacity);
ms.Capacity = 0;
byte [] buffer = ms.GetBuffer ();
// Begin: wow!!!
AssertEquals ("#03", -1, ms.ReadByte ());
AssertEquals ("#04", null, buffer); // <--
ms.Read (new byte [5], 0, 5);
AssertEquals ("#05", 0, ms.Position);
AssertEquals ("#06", 0, ms.Length);
// End
}
[Test]
public void ConstructorsThree ()
{
MemoryStream ms = new MemoryStream (testStreamData);
AssertEquals ("#01", 100, ms.Length);
AssertEquals ("#02", 0, ms.Position);
}
[Test]
public void ConstructorsFour ()
{
MemoryStream ms = new MemoryStream (testStreamData, true);
AssertEquals ("#01", 100, ms.Length);
AssertEquals ("#02", 0, ms.Position);
ms.Position = 50;
byte saved = testStreamData [50];
try {
ms.WriteByte (23);
AssertEquals ("#03", testStreamData [50], 23);
} finally {
testStreamData [50] = saved;
}
ms.Position = 100;
try {
ms.WriteByte (23);
} catch (Exception) {
return;
}
Fail ("#04");
}
[Test]
public void ConstructorsFive ()
{
MemoryStream ms = new MemoryStream (testStreamData, 50, 50);
AssertEquals ("#01", 50, ms.Length);
AssertEquals ("#02", 0, ms.Position);
AssertEquals ("#03", 50, ms.Capacity);
ms.Position = 1;
byte saved = testStreamData [51];
try {
ms.WriteByte (23);
AssertEquals ("#04", testStreamData [51], 23);
} finally {
testStreamData [51] = saved;
}
ms.Position = 100;
bool gotException = false;
try {
ms.WriteByte (23);
} catch (NotSupportedException) {
gotException = true;
}
if (!gotException)
Fail ("#05");
gotException = false;
try {
ms.GetBuffer ();
} catch (UnauthorizedAccessException) {
gotException = true;
}
if (!gotException)
Fail ("#06");
ms.Capacity = 100; // Allowed. It's the same as the one in the ms.
// This is lame, as the length is 50!!!
gotException = false;
try {
ms.Capacity = 51;
} catch (NotSupportedException) {
gotException = true;
}
if (!gotException)
Fail ("#07");
AssertEquals ("#08", 50, ms.ToArray ().Length);
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException))]
public void ConstructorsSix ()
{
MemoryStream ms = new MemoryStream (-2);
}
[Test]
public void Read ()
{
byte [] readBytes = new byte [20];
/* Test simple read */
testStream.Read (readBytes, 0, 10);
VerifyTestData ("R1", readBytes, 0, 10);
/* Seek back to beginning */
testStream.Seek (0, SeekOrigin.Begin);
/* Read again, bit more this time */
testStream.Read (readBytes, 0, 20);
VerifyTestData ("R2", readBytes, 0, 20);
/* Seek to 20 bytes from End */
testStream.Seek (-20, SeekOrigin.End);
testStream.Read (readBytes, 0, 20);
VerifyTestData ("R3", readBytes, 80, 20);
int readByte = testStream.ReadByte();
AssertEquals (-1, readByte);
}
[Test]
public void WriteBytes ()
{
byte[] readBytes = new byte[100];
MemoryStream ms = new MemoryStream (100);
for (int i = 0; i < 100; i++)
ms.WriteByte (testStreamData [i]);
ms.Seek (0, SeekOrigin.Begin);
testStream.Read (readBytes, 0, 100);
VerifyTestData ("W1", readBytes, 0, 100);
}
[Test]
public void WriteBlock ()
{
byte[] readBytes = new byte[100];
MemoryStream ms = new MemoryStream (100);
ms.Write (testStreamData, 0, 100);
ms.Seek (0, SeekOrigin.Begin);
testStream.Read (readBytes, 0, 100);
VerifyTestData ("WB1", readBytes, 0, 100);
byte[] arrayBytes = testStream.ToArray();
AssertEquals ("#01", 100, arrayBytes.Length);
VerifyTestData ("WB2", arrayBytes, 0, 100);
}
[Test]
public void PositionLength ()
{
MemoryStream ms = new MemoryStream ();
ms.Position = 4;
ms.WriteByte ((byte) 'M');
ms.WriteByte ((byte) 'O');
AssertEquals ("#01", 6, ms.Length);
AssertEquals ("#02", 6, ms.Position);
ms.Position = 0;
AssertEquals ("#03", 0, ms.Position);
}
[Test]
[ExpectedException (typeof (NotSupportedException))]
public void MorePositionLength ()
{
MemoryStream ms = new MemoryStream (testStreamData);
ms.Position = 101;
AssertEquals ("#01", 101, ms.Position);
AssertEquals ("#02", 100, ms.Length);
ms.WriteByte (1); // This should throw the exception
}
[Test]
public void GetBufferOne ()
{
MemoryStream ms = new MemoryStream ();
byte [] buffer = ms.GetBuffer ();
AssertEquals ("#01", 0, buffer.Length);
}
[Test]
public void GetBufferTwo ()
{
MemoryStream ms = new MemoryStream (100);
byte [] buffer = ms.GetBuffer ();
AssertEquals ("#01", 100, buffer.Length);
ms.Write (testStreamData, 0, 100);
ms.Write (testStreamData, 0, 100);
AssertEquals ("#02", 200, ms.Length);
buffer = ms.GetBuffer ();
AssertEquals ("#03", 256, buffer.Length); // Minimun size after writing
}
[Test]
public void Closed ()
{
MemoryStream ms = new MemoryStream (100);
ms.Close ();
bool thrown = false;
try {
int x = ms.Capacity;
} catch (ObjectDisposedException) {
thrown = true;
}
if (!thrown)
Fail ("#01");
thrown = false;
try {
ms.Capacity = 1;
} catch (ObjectDisposedException) {
thrown = true;
}
if (!thrown)
Fail ("#02");
// The first exception thrown is ObjectDisposed, not ArgumentNull
thrown = false;
try {
ms.Read (null, 0, 1);
} catch (ObjectDisposedException) {
thrown = true;
}
if (!thrown)
Fail ("#03");
thrown = false;
try {
ms.Write (null, 0, 1);
} catch (ObjectDisposedException) {
thrown = true;
}
if (!thrown)
Fail ("#03");
}
[Test]
[ExpectedException (typeof (ObjectDisposedException))]
public void Close_get_Length ()
{
MemoryStream ms = new MemoryStream (100);
ms.Close ();
long x = ms.Length;
}
[Test]
[ExpectedException (typeof (ObjectDisposedException))]
public void Close_get_Position ()
{
MemoryStream ms = new MemoryStream (100);
ms.Close ();
long x = ms.Position;
}
[Test]
[ExpectedException (typeof (ObjectDisposedException))]
public void Close_set_Position ()
{
MemoryStream ms = new MemoryStream (100);
ms.Close ();
ms.Position = 0;
}
[Test]
public void Seek ()
{
MemoryStream ms = new MemoryStream (100);
ms.Write (testStreamData, 0, 100);
ms.Seek (0, SeekOrigin.Begin);
ms.Position = 50;
ms.Seek (-50, SeekOrigin.Current);
ms.Seek (-50, SeekOrigin.End);
bool thrown = false;
ms.Position = 49;
try {
ms.Seek (-50, SeekOrigin.Current);
} catch (IOException) {
thrown = true;
}
if (!thrown)
Fail ("#01");
thrown = false;
try {
ms.Seek (Int64.MaxValue, SeekOrigin.Begin);
} catch (ArgumentOutOfRangeException) {
thrown = true;
}
if (!thrown)
Fail ("#02");
thrown=false;
try {
// Oh, yes. They throw IOException for this one, but ArgumentOutOfRange for the previous one
ms.Seek (Int64.MinValue, SeekOrigin.Begin);
} catch (IOException) {
thrown = true;
}
if (!thrown)
Fail ("#03");
ms=new MemoryStream (256);
ms.Write (testStreamData, 0, 100);
ms.Position=0;
AssertEquals ("#01", 100, ms.Length);
AssertEquals ("#02", 0, ms.Position);
ms.Position=128;
AssertEquals ("#03", 100, ms.Length);
AssertEquals ("#04", 128, ms.Position);
ms.Position=768;
AssertEquals ("#05", 100, ms.Length);
AssertEquals ("#06", 768, ms.Position);
ms.WriteByte (0);
AssertEquals ("#07", 769, ms.Length);
AssertEquals ("#08", 769, ms.Position);
}
[Test]
[ExpectedException (typeof (ObjectDisposedException))]
public void Seek_Disposed ()
{
MemoryStream ms = new MemoryStream ();
ms.Close ();
ms.Seek (0, SeekOrigin.Begin);
}
[Test]
public void SetLength ()
{
MemoryStream ms = new MemoryStream ();
ms.Write (testStreamData, 0, 100);
ms.Position = 100;
ms.SetLength (150);
AssertEquals ("#01", 150, ms.Length);
AssertEquals ("#02", 100, ms.Position);
ms.SetLength (80);
AssertEquals ("#03", 80, ms.Length);
AssertEquals ("#04", 80, ms.Position);
}
[Test]
[ExpectedException (typeof (NotSupportedException))]
public void SetLength_ReadOnly ()
{
MemoryStream ms = new MemoryStream (testStreamData, false);
ms.SetLength (10);
}
[Test]
[ExpectedException (typeof (NotSupportedException))]
public void WriteNonWritable ()
{
MemoryStream ms = new MemoryStream (testStreamData, false);
ms.Write (testStreamData, 0, 100);
}
[Test]
[ExpectedException (typeof (NotSupportedException))]
public void WriteExpand ()
{
MemoryStream ms = new MemoryStream (testStreamData);
ms.Write (testStreamData, 0, 100);
ms.Write (testStreamData, 0, 100); // This one throws the exception
}
[Test]
public void WriteByte ()
{
MemoryStream ms = new MemoryStream (100);
ms.Write (testStreamData, 0, 100);
ms.Position = 100;
ms.WriteByte (101);
AssertEquals ("#01", 101, ms.Position);
AssertEquals ("#02", 101, ms.Length);
AssertEquals ("#03", 256, ms.Capacity);
ms.Write (testStreamData, 0, 100);
ms.Write (testStreamData, 0, 100);
// 301
AssertEquals ("#04", 301, ms.Position);
AssertEquals ("#05", 301, ms.Length);
AssertEquals ("#06", 512, ms.Capacity);
}
[Test]
public void WriteLengths () {
MemoryStream ms=new MemoryStream (256);
BinaryWriter writer=new BinaryWriter (ms);
writer.Write ((byte)'1');
AssertEquals ("#01", 1, ms.Length);
AssertEquals ("#02", 256, ms.Capacity);
writer.Write ((ushort)0);
AssertEquals ("#03", 3, ms.Length);
AssertEquals ("#04", 256, ms.Capacity);
writer.Write (testStreamData, 0, 23);
AssertEquals ("#05", 26, ms.Length);
AssertEquals ("#06", 256, ms.Capacity);
writer.Write (testStreamData);
writer.Write (testStreamData);
writer.Write (testStreamData);
AssertEquals ("#07", 326, ms.Length);
}
[Test]
public void MoreWriteByte ()
{
byte[] buffer = new byte [44];
MemoryStream ms = new MemoryStream (buffer);
BinaryWriter bw = new BinaryWriter (ms);
for(int i=0; i < 44; i++)
bw.Write ((byte) 1);
}
[Test]
[ExpectedException (typeof (NotSupportedException))]
public void MoreWriteByte2 ()
{
byte[] buffer = new byte [43]; // Note the 43 here
MemoryStream ms = new MemoryStream (buffer);
BinaryWriter bw = new BinaryWriter (ms);
for(int i=0; i < 44; i++)
bw.Write ((byte) 1);
}
[Test]
public void Expand ()
{
byte[] array = new byte [8] { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 };
MemoryStream ms = new MemoryStream ();
ms.Write (array, 0, array.Length);
ms.SetLength (4);
ms.Seek (4, SeekOrigin.End);
ms.WriteByte (0xFF);
AssertEquals ("Result", "01-01-01-01-00-00-00-00-FF", BitConverter.ToString (ms.ToArray ()));
}
}
}
| |
/*
* 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.Impl.Datastream
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Portable;
/// <summary>
/// Data streamer batch.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")]
internal class DataStreamerBatch<TK, TV>
{
/** Queue. */
private readonly ConcurrentQueue<object> _queue = new ConcurrentQueue<object>();
/** Lock for concurrency. */
private readonly ReaderWriterLockSlim _rwLock = new ReaderWriterLockSlim();
/** Previous batch. */
private volatile DataStreamerBatch<TK, TV> _prev;
/** Current queue size.*/
private volatile int _size;
/** Send guard. */
private bool _sndGuard;
/** */
private readonly Future<object> _fut = new Future<object>();
/// <summary>
/// Constructor.
/// </summary>
public DataStreamerBatch() : this(null)
{
// No-op.
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="prev">Previous batch.</param>
public DataStreamerBatch(DataStreamerBatch<TK, TV> prev)
{
_prev = prev;
if (prev != null)
Thread.MemoryBarrier(); // Prevent "prev" field escape.
_fut.Listen(() => ParentsCompleted());
}
/// <summary>
/// Gets the future.
/// </summary>
public IFuture Future
{
get { return _fut; }
}
/// <summary>
/// Add object to the batch.
/// </summary>
/// <param name="val">Value.</param>
/// <param name="cnt">Items count.</param>
/// <returns>Positive value in case batch is active, -1 in case no more additions are allowed.</returns>
public int Add(object val, int cnt)
{
// If we cannot enter read-lock immediately, then send is scheduled and batch is definetely blocked.
if (!_rwLock.TryEnterReadLock(0))
return -1;
try
{
// 1. Ensure additions are possible
if (_sndGuard)
return -1;
// 2. Add data and increase size.
_queue.Enqueue(val);
#pragma warning disable 0420
int newSize = Interlocked.Add(ref _size, cnt);
#pragma warning restore 0420
return newSize;
}
finally
{
_rwLock.ExitReadLock();
}
}
/// <summary>
/// Internal send routine.
/// </summary>
/// <param name="ldr">streamer.</param>
/// <param name="plc">Policy.</param>
public void Send(DataStreamerImpl<TK, TV> ldr, int plc)
{
// 1. Delegate to the previous batch first.
DataStreamerBatch<TK, TV> prev0 = _prev;
if (prev0 != null)
prev0.Send(ldr, DataStreamerImpl<TK, TV>.PlcContinue);
// 2. Set guard.
_rwLock.EnterWriteLock();
try
{
if (_sndGuard)
return;
else
_sndGuard = true;
}
finally
{
_rwLock.ExitWriteLock();
}
var handleRegistry = ldr.Marshaller.Ignite.HandleRegistry;
long futHnd = 0;
// 3. Actual send.
ldr.Update(writer =>
{
writer.WriteInt(plc);
if (plc != DataStreamerImpl<TK, TV>.PlcCancelClose)
{
futHnd = handleRegistry.Allocate(_fut);
try
{
writer.WriteLong(futHnd);
WriteTo(writer);
}
catch (Exception)
{
handleRegistry.Release(futHnd);
throw;
}
}
});
if (plc == DataStreamerImpl<TK, TV>.PlcCancelClose || _size == 0)
{
_fut.OnNullResult();
handleRegistry.Release(futHnd);
}
}
/// <summary>
/// Await completion of current and all previous loads.
/// </summary>
public void AwaitCompletion()
{
DataStreamerBatch<TK, TV> curBatch = this;
while (curBatch != null)
{
try
{
curBatch._fut.Get();
}
catch (Exception)
{
// Ignore.
}
curBatch = curBatch._prev;
}
}
/// <summary>
/// Write batch content.
/// </summary>
/// <param name="writer">Portable writer.</param>
private void WriteTo(PortableWriterImpl writer)
{
writer.WriteInt(_size);
object val;
while (_queue.TryDequeue(out val))
{
// 1. Is it a collection?
ICollection<KeyValuePair<TK, TV>> entries = val as ICollection<KeyValuePair<TK, TV>>;
if (entries != null)
{
foreach (KeyValuePair<TK, TV> item in entries)
{
writer.Write(item.Key);
writer.Write(item.Value);
}
continue;
}
// 2. Is it a single entry?
DataStreamerEntry<TK, TV> entry = val as DataStreamerEntry<TK, TV>;
if (entry != null) {
writer.Write(entry.Key);
writer.Write(entry.Value);
continue;
}
// 3. Is it remove merker?
DataStreamerRemoveEntry<TK> rmvEntry = val as DataStreamerRemoveEntry<TK>;
if (rmvEntry != null)
{
writer.Write(rmvEntry.Key);
writer.Write<object>(null);
}
}
}
/// <summary>
/// Checck whether all previous batches are completed.
/// </summary>
/// <returns></returns>
private bool ParentsCompleted()
{
DataStreamerBatch<TK, TV> prev0 = _prev;
if (prev0 != null)
{
if (prev0.ParentsCompleted())
_prev = null;
else
return false;
}
return _fut.IsDone;
}
}
}
| |
namespace epms.Data.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class Initial : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.AccountCategory",
c => new
{
Id = c.Int(nullable: false, identity: true),
CategoryCode = c.String(maxLength: 100),
CategoryName = c.String(maxLength: 150),
GroupId = c.Int(nullable: false),
CreatedBy = c.Int(nullable: false),
CreatedDateTime = c.DateTime(nullable: false),
UpdatedBy = c.Int(nullable: false),
UpdatedDateTime = c.DateTime(nullable: false),
Status = c.Boolean(nullable: false),
BranchId = c.Int(nullable: false),
CompanyId = c.Int(nullable: false),
IsApproved = c.Boolean(nullable: false),
IsActive = c.Boolean(nullable: false),
IsDeleted = c.Boolean(nullable: false),
SortedBy = c.Int(nullable: false),
Remarks = c.String(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AccountGroup", t => t.GroupId)
.ForeignKey("dbo.Company", t => t.CompanyId)
.Index(t => t.GroupId)
.Index(t => t.CompanyId);
CreateTable(
"dbo.AccountGroup",
c => new
{
Id = c.Int(nullable: false, identity: true),
GroupCode = c.String(maxLength: 50),
GroupName = c.String(maxLength: 200),
CreatedBy = c.Int(nullable: false),
CreatedDateTime = c.DateTime(nullable: false),
UpdatedBy = c.Int(nullable: false),
UpdatedDateTime = c.DateTime(nullable: false),
Status = c.Boolean(nullable: false),
BranchId = c.Int(nullable: false),
CompanyId = c.Int(nullable: false),
IsApproved = c.Boolean(nullable: false),
IsActive = c.Boolean(),
IsDeleted = c.Boolean(nullable: false),
SortedBy = c.Int(nullable: false),
Remarks = c.String(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Company", t => t.CompanyId)
.Index(t => t.CompanyId);
CreateTable(
"dbo.AccountMaster",
c => new
{
Id = c.Int(nullable: false, identity: true),
AccountCode = c.String(nullable: false, maxLength: 50),
AccountName = c.String(nullable: false),
Description = c.String(),
GroupId = c.Int(nullable: false),
CategoryId = c.Int(nullable: false),
IsTransactional = c.Boolean(),
OpeningBalanceDate = c.DateTime(),
IsBankAccount = c.Boolean(),
IsSubCode = c.Boolean(),
SubCodeId = c.String(maxLength: 50),
Debit = c.Decimal(precision: 18, scale: 2, storeType: "numeric"),
Credit = c.Decimal(precision: 18, scale: 2, storeType: "numeric"),
BankName = c.String(maxLength: 200),
BranchName = c.String(maxLength: 200),
BankAccountNo = c.String(maxLength: 100),
SupplierCode = c.String(maxLength: 50),
SupplierName = c.String(maxLength: 100),
SupplierCompany = c.String(maxLength: 200),
ClientCode = c.String(maxLength: 50),
ClientName = c.String(maxLength: 100),
ClientCompany = c.String(maxLength: 200),
CPhone = c.String(maxLength: 20),
Phone = c.String(maxLength: 20),
CreatedBy = c.Int(nullable: false),
CreatedDateTime = c.DateTime(nullable: false),
UpdatedBy = c.Int(nullable: false),
UpdatedDateTime = c.DateTime(nullable: false),
Status = c.Boolean(nullable: false),
BranchId = c.Int(nullable: false),
CompanyId = c.Int(nullable: false),
IsApproved = c.Boolean(nullable: false),
IsActive = c.Boolean(nullable: false),
IsDeleted = c.Boolean(),
SortedBy = c.Int(nullable: false),
Remarks = c.String(maxLength: 500),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AccountCategory", t => t.CategoryId)
.ForeignKey("dbo.AccountGroup", t => t.GroupId)
.ForeignKey("dbo.Company", t => t.CompanyId)
.Index(t => t.GroupId)
.Index(t => t.CategoryId)
.Index(t => t.CompanyId);
CreateTable(
"dbo.Company",
c => new
{
Id = c.Int(nullable: false, identity: true),
CompanyName = c.String(nullable: false, maxLength: 100),
Logo = c.String(maxLength: 300),
Address = c.String(nullable: false, maxLength: 150),
Phone = c.String(maxLength: 15),
Fax = c.String(maxLength: 15),
Email = c.String(maxLength: 50),
CreatedBy = c.Int(nullable: false),
CreatedDate = c.DateTime(nullable: false),
UpdatedBy = c.Int(),
UpdatedDate = c.DateTime(),
Status = c.Boolean(nullable: false),
BranchId = c.Int(nullable: false),
CompanyId = c.Int(nullable: false),
IsApproved = c.Boolean(nullable: false),
IsActive = c.Boolean(nullable: false),
IsDeleted = c.Boolean(nullable: false),
SortedBy = c.Int(nullable: false),
Remarks = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.BillingsHistory",
c => new
{
Id = c.Int(nullable: false, identity: true),
Year = c.Int(nullable: false),
Month = c.String(),
BillingDate = c.DateTime(nullable: false),
UnitPrice = c.Double(),
Quentity = c.Int(),
TotalPrice = c.Double(),
VatAmount = c.Double(),
Discount = c.Double(),
PaidAmount = c.Double(),
PaidDate = c.DateTime(nullable: false),
BillStatus = c.Boolean(),
PackageId = c.Int(nullable: false),
CustomerId = c.Int(nullable: false),
CreatedBy = c.Int(nullable: false),
CreatedDate = c.DateTime(nullable: false),
UpdatedBy = c.Int(),
UpdatedDate = c.DateTime(),
Status = c.Boolean(nullable: false),
BranchId = c.Int(nullable: false),
CompanyId = c.Int(nullable: false),
IsApproved = c.Boolean(),
IsActive = c.Boolean(nullable: false),
IsDeleted = c.Boolean(),
SortedBy = c.Int(),
Remarks = c.String(maxLength: 500),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Branch", t => t.BranchId)
.ForeignKey("dbo.Company", t => t.CompanyId)
.ForeignKey("dbo.Customer", t => t.CustomerId)
.ForeignKey("dbo.Package", t => t.PackageId)
.Index(t => t.PackageId)
.Index(t => t.CustomerId)
.Index(t => t.BranchId)
.Index(t => t.CompanyId);
CreateTable(
"dbo.Branch",
c => new
{
Id = c.Int(nullable: false, identity: true),
BranchName = c.String(nullable: false, maxLength: 150),
BranchCode = c.Int(nullable: false),
Address = c.String(nullable: false, maxLength: 150),
Phone = c.String(maxLength: 15),
Fax = c.String(maxLength: 15),
Email = c.String(maxLength: 50),
CreatedBy = c.Int(nullable: false),
CreatedDateTime = c.DateTime(nullable: false),
UpdatedBy = c.Int(nullable: false),
UpdatedDateTime = c.DateTime(nullable: false),
Status = c.Boolean(nullable: false),
BranchId = c.Int(nullable: false),
CompanyId = c.Int(nullable: false),
IsApproved = c.Boolean(nullable: false),
IsActive = c.Boolean(nullable: false),
IsDeleted = c.Boolean(nullable: false),
SortedBy = c.Int(nullable: false),
Remarks = c.String(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Company", t => t.CompanyId)
.Index(t => t.CompanyId);
CreateTable(
"dbo.Customer",
c => new
{
Id = c.Int(nullable: false, identity: true),
CustomerName = c.String(maxLength: 100),
CustomerImage = c.String(),
FatherName = c.String(maxLength: 100),
MotherName = c.String(maxLength: 100),
SpouseName = c.String(maxLength: 100),
Gender = c.String(maxLength: 20),
CustomerEntryDate = c.DateTime(),
DateOfBirth = c.DateTime(),
TradeLicenseDate = c.DateTime(),
TradeLicenseNo = c.String(maxLength: 50),
Nationality = c.String(maxLength: 100),
RegistrationAuthority = c.String(maxLength: 50),
RegistrationNo = c.String(maxLength: 50),
BirthCertificateNo = c.String(maxLength: 25),
NationalId = c.String(maxLength: 25),
OccupationAndPosition = c.String(maxLength: 100),
Position = c.String(maxLength: 100),
PassportNo = c.String(maxLength: 50),
PassportExpireDate = c.DateTime(),
TINNo = c.String(maxLength: 50),
DrivingLicenseNo = c.String(maxLength: 50),
PresentAddress = c.String(maxLength: 300),
PermanentAddress = c.String(maxLength: 300),
OfficeAddress = c.String(maxLength: 300),
Mobile = c.String(maxLength: 15),
AnotherCellNo = c.String(maxLength: 15),
Home = c.String(maxLength: 15),
Office = c.String(maxLength: 15),
Email = c.String(maxLength: 50),
CustomerIncomeSource = c.String(maxLength: 50),
TradeLicAuthority = c.String(maxLength: 50),
CreatedBy = c.Int(nullable: false),
CreatedDate = c.DateTime(nullable: false),
UpdatedBy = c.Int(),
UpdatedDate = c.DateTime(),
Status = c.Boolean(nullable: false),
BranchId = c.Int(nullable: false),
CompanyId = c.Int(nullable: false),
IsApproved = c.Boolean(),
IsActive = c.Boolean(nullable: false),
IsDeleted = c.Boolean(),
SortedBy = c.Int(),
Remarks = c.String(maxLength: 500),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Branch", t => t.BranchId)
.ForeignKey("dbo.Company", t => t.CompanyId)
.Index(t => t.BranchId)
.Index(t => t.CompanyId);
CreateTable(
"dbo.Package",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(maxLength: 100),
Details = c.String(maxLength: 500),
Price = c.Decimal(nullable: false, precision: 18, scale: 2),
ActivatedDate = c.DateTime(),
CreatedBy = c.Int(nullable: false),
CreatedDate = c.DateTime(nullable: false),
UpdatedBy = c.Int(),
UpdatedDate = c.DateTime(),
Status = c.Boolean(nullable: false),
BranchId = c.Int(nullable: false),
CompanyId = c.Int(nullable: false),
IsApproved = c.Boolean(),
IsActive = c.Boolean(nullable: false),
IsDeleted = c.Boolean(),
SortedBy = c.Int(),
Remarks = c.String(maxLength: 500),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Branch", t => t.BranchId)
.ForeignKey("dbo.Company", t => t.CompanyId)
.Index(t => t.BranchId)
.Index(t => t.CompanyId);
}
public override void Down()
{
DropForeignKey("dbo.AccountCategory", "CompanyId", "dbo.Company");
DropForeignKey("dbo.AccountCategory", "GroupId", "dbo.AccountGroup");
DropForeignKey("dbo.AccountGroup", "CompanyId", "dbo.Company");
DropForeignKey("dbo.AccountMaster", "CompanyId", "dbo.Company");
DropForeignKey("dbo.BillingsHistory", "PackageId", "dbo.Package");
DropForeignKey("dbo.BillingsHistory", "CustomerId", "dbo.Customer");
DropForeignKey("dbo.BillingsHistory", "CompanyId", "dbo.Company");
DropForeignKey("dbo.BillingsHistory", "BranchId", "dbo.Branch");
DropForeignKey("dbo.Package", "CompanyId", "dbo.Company");
DropForeignKey("dbo.Package", "BranchId", "dbo.Branch");
DropForeignKey("dbo.Customer", "CompanyId", "dbo.Company");
DropForeignKey("dbo.Customer", "BranchId", "dbo.Branch");
DropForeignKey("dbo.Branch", "CompanyId", "dbo.Company");
DropForeignKey("dbo.AccountMaster", "GroupId", "dbo.AccountGroup");
DropForeignKey("dbo.AccountMaster", "CategoryId", "dbo.AccountCategory");
DropIndex("dbo.Package", new[] { "CompanyId" });
DropIndex("dbo.Package", new[] { "BranchId" });
DropIndex("dbo.Customer", new[] { "CompanyId" });
DropIndex("dbo.Customer", new[] { "BranchId" });
DropIndex("dbo.Branch", new[] { "CompanyId" });
DropIndex("dbo.BillingsHistory", new[] { "CompanyId" });
DropIndex("dbo.BillingsHistory", new[] { "BranchId" });
DropIndex("dbo.BillingsHistory", new[] { "CustomerId" });
DropIndex("dbo.BillingsHistory", new[] { "PackageId" });
DropIndex("dbo.AccountMaster", new[] { "CompanyId" });
DropIndex("dbo.AccountMaster", new[] { "CategoryId" });
DropIndex("dbo.AccountMaster", new[] { "GroupId" });
DropIndex("dbo.AccountGroup", new[] { "CompanyId" });
DropIndex("dbo.AccountCategory", new[] { "CompanyId" });
DropIndex("dbo.AccountCategory", new[] { "GroupId" });
DropTable("dbo.Package");
DropTable("dbo.Customer");
DropTable("dbo.Branch");
DropTable("dbo.BillingsHistory");
DropTable("dbo.Company");
DropTable("dbo.AccountMaster");
DropTable("dbo.AccountGroup");
DropTable("dbo.AccountCategory");
}
}
}
| |
// 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.
/*=============================================================================
**
** Class: Queue
**
** Purpose: Represents a first-in, first-out collection of objects.
**
=============================================================================*/
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
namespace System.Collections
{
// A simple Queue of objects. Internally it is implemented as a circular
// buffer, so Enqueue can be O(n). Dequeue is O(1).
[DebuggerTypeProxy(typeof(System.Collections.Queue.QueueDebugView))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
public class Queue : ICollection, ICloneable
{
private Object[] _array;
private int _head; // First valid element in the queue
private int _tail; // Last valid element in the queue
private int _size; // Number of elements.
private int _growFactor; // 100 == 1.0, 130 == 1.3, 200 == 2.0
private int _version;
[NonSerialized]
private Object _syncRoot;
private const int _MinimumGrow = 4;
private const int _ShrinkThreshold = 32;
// Creates a queue with room for capacity objects. The default initial
// capacity and grow factor are used.
public Queue()
: this(32, (float)2.0)
{
}
// Creates a queue with room for capacity objects. The default grow factor
// is used.
//
public Queue(int capacity)
: this(capacity, (float)2.0)
{
}
// Creates a queue with room for capacity objects. When full, the new
// capacity is set to the old capacity * growFactor.
//
public Queue(int capacity, float growFactor)
{
if (capacity < 0)
throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NeedNonNegNum);
if (!(growFactor >= 1.0 && growFactor <= 10.0))
throw new ArgumentOutOfRangeException(nameof(growFactor), SR.Format(SR.ArgumentOutOfRange_QueueGrowFactor, 1, 10));
Contract.EndContractBlock();
_array = new Object[capacity];
_head = 0;
_tail = 0;
_size = 0;
_growFactor = (int)(growFactor * 100);
}
// Fills a Queue with the elements of an ICollection. Uses the enumerator
// to get each of the elements.
//
public Queue(ICollection col) : this((col == null ? 32 : col.Count))
{
if (col == null)
throw new ArgumentNullException(nameof(col));
Contract.EndContractBlock();
IEnumerator en = col.GetEnumerator();
while (en.MoveNext())
Enqueue(en.Current);
}
public virtual int Count
{
get { return _size; }
}
public virtual Object Clone()
{
Queue q = new Queue(_size);
q._size = _size;
int numToCopy = _size;
int firstPart = (_array.Length - _head < numToCopy) ? _array.Length - _head : numToCopy;
Array.Copy(_array, _head, q._array, 0, firstPart);
numToCopy -= firstPart;
if (numToCopy > 0)
Array.Copy(_array, 0, q._array, _array.Length - _head, numToCopy);
q._version = _version;
return q;
}
public virtual bool IsSynchronized
{
get { return false; }
}
public virtual Object SyncRoot
{
get
{
if (_syncRoot == null)
{
System.Threading.Interlocked.CompareExchange(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
// Removes all Objects from the queue.
public virtual void Clear()
{
if (_size != 0)
{
if (_head < _tail)
Array.Clear(_array, _head, _size);
else
{
Array.Clear(_array, _head, _array.Length - _head);
Array.Clear(_array, 0, _tail);
}
_size = 0;
}
_head = 0;
_tail = 0;
_version++;
}
// CopyTo copies a collection into an Array, starting at a particular
// index into the array.
//
public virtual void CopyTo(Array array, int index)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (array.Rank != 1)
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array));
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
Contract.EndContractBlock();
int arrayLen = array.Length;
if (arrayLen - index < _size)
throw new ArgumentException(SR.Argument_InvalidOffLen);
int numToCopy = _size;
if (numToCopy == 0)
return;
int firstPart = (_array.Length - _head < numToCopy) ? _array.Length - _head : numToCopy;
Array.Copy(_array, _head, array, index, firstPart);
numToCopy -= firstPart;
if (numToCopy > 0)
Array.Copy(_array, 0, array, index + _array.Length - _head, numToCopy);
}
// Adds obj to the tail of the queue.
//
public virtual void Enqueue(Object obj)
{
if (_size == _array.Length)
{
int newcapacity = (int)((long)_array.Length * (long)_growFactor / 100);
if (newcapacity < _array.Length + _MinimumGrow)
{
newcapacity = _array.Length + _MinimumGrow;
}
SetCapacity(newcapacity);
}
_array[_tail] = obj;
_tail = (_tail + 1) % _array.Length;
_size++;
_version++;
}
// GetEnumerator returns an IEnumerator over this Queue. This
// Enumerator will support removing.
//
public virtual IEnumerator GetEnumerator()
{
return new QueueEnumerator(this);
}
// Removes the object at the head of the queue and returns it. If the queue
// is empty, this method simply returns null.
public virtual Object Dequeue()
{
if (Count == 0)
throw new InvalidOperationException(SR.InvalidOperation_EmptyQueue);
Contract.EndContractBlock();
Object removed = _array[_head];
_array[_head] = null;
_head = (_head + 1) % _array.Length;
_size--;
_version++;
return removed;
}
// Returns the object at the head of the queue. The object remains in the
// queue. If the queue is empty, this method throws an
// InvalidOperationException.
public virtual Object Peek()
{
if (Count == 0)
throw new InvalidOperationException(SR.InvalidOperation_EmptyQueue);
Contract.EndContractBlock();
return _array[_head];
}
// Returns a synchronized Queue. Returns a synchronized wrapper
// class around the queue - the caller must not use references to the
// original queue.
//
public static Queue Synchronized(Queue queue)
{
if (queue == null)
throw new ArgumentNullException(nameof(queue));
Contract.EndContractBlock();
return new SynchronizedQueue(queue);
}
// Returns true if the queue contains at least one object equal to obj.
// Equality is determined using obj.Equals().
//
// Exceptions: ArgumentNullException if obj == null.
public virtual bool Contains(Object obj)
{
int index = _head;
int count = _size;
while (count-- > 0)
{
if (obj == null)
{
if (_array[index] == null)
return true;
}
else if (_array[index] != null && _array[index].Equals(obj))
{
return true;
}
index = (index + 1) % _array.Length;
}
return false;
}
internal Object GetElement(int i)
{
return _array[(_head + i) % _array.Length];
}
// Iterates over the objects in the queue, returning an array of the
// objects in the Queue, or an empty array if the queue is empty.
// The order of elements in the array is first in to last in, the same
// order produced by successive calls to Dequeue.
public virtual Object[] ToArray()
{
if (_size == 0)
return Array.Empty<Object>();
Object[] arr = new Object[_size];
if (_head < _tail)
{
Array.Copy(_array, _head, arr, 0, _size);
}
else
{
Array.Copy(_array, _head, arr, 0, _array.Length - _head);
Array.Copy(_array, 0, arr, _array.Length - _head, _tail);
}
return arr;
}
// PRIVATE Grows or shrinks the buffer to hold capacity objects. Capacity
// must be >= _size.
private void SetCapacity(int capacity)
{
Object[] newarray = new Object[capacity];
if (_size > 0)
{
if (_head < _tail)
{
Array.Copy(_array, _head, newarray, 0, _size);
}
else
{
Array.Copy(_array, _head, newarray, 0, _array.Length - _head);
Array.Copy(_array, 0, newarray, _array.Length - _head, _tail);
}
}
_array = newarray;
_head = 0;
_tail = (_size == capacity) ? 0 : _size;
_version++;
}
public virtual void TrimToSize()
{
SetCapacity(_size);
}
// Implements a synchronization wrapper around a queue.
[Serializable]
private class SynchronizedQueue : Queue
{
private Queue _q;
private Object _root;
internal SynchronizedQueue(Queue q)
{
_q = q;
_root = _q.SyncRoot;
}
public override bool IsSynchronized
{
get { return true; }
}
public override Object SyncRoot
{
get
{
return _root;
}
}
public override int Count
{
get
{
lock (_root)
{
return _q.Count;
}
}
}
public override void Clear()
{
lock (_root)
{
_q.Clear();
}
}
public override Object Clone()
{
lock (_root)
{
return new SynchronizedQueue((Queue)_q.Clone());
}
}
public override bool Contains(Object obj)
{
lock (_root)
{
return _q.Contains(obj);
}
}
public override void CopyTo(Array array, int arrayIndex)
{
lock (_root)
{
_q.CopyTo(array, arrayIndex);
}
}
public override void Enqueue(Object value)
{
lock (_root)
{
_q.Enqueue(value);
}
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Thread safety problems with precondition - can't express the precondition as of Dev10.
public override Object Dequeue()
{
lock (_root)
{
return _q.Dequeue();
}
}
public override IEnumerator GetEnumerator()
{
lock (_root)
{
return _q.GetEnumerator();
}
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Thread safety problems with precondition - can't express the precondition as of Dev10.
public override Object Peek()
{
lock (_root)
{
return _q.Peek();
}
}
public override Object[] ToArray()
{
lock (_root)
{
return _q.ToArray();
}
}
public override void TrimToSize()
{
lock (_root)
{
_q.TrimToSize();
}
}
}
// Implements an enumerator for a Queue. The enumerator uses the
// internal version number of the list to ensure that no modifications are
// made to the list while an enumeration is in progress.
[Serializable]
private class QueueEnumerator : IEnumerator, ICloneable
{
private Queue _q;
private int _index;
private int _version;
private Object _currentElement;
internal QueueEnumerator(Queue q)
{
_q = q;
_version = _q._version;
_index = 0;
_currentElement = _q._array;
if (_q._size == 0)
_index = -1;
}
public object Clone() => MemberwiseClone();
public virtual bool MoveNext()
{
if (_version != _q._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
if (_index < 0)
{
_currentElement = _q._array;
return false;
}
_currentElement = _q.GetElement(_index);
_index++;
if (_index == _q._size)
_index = -1;
return true;
}
public virtual Object Current
{
get
{
if (_currentElement == _q._array)
{
if (_index == 0)
throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted);
else
throw new InvalidOperationException(SR.InvalidOperation_EnumEnded);
}
return _currentElement;
}
}
public virtual void Reset()
{
if (_version != _q._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
if (_q._size == 0)
_index = -1;
else
_index = 0;
_currentElement = _q._array;
}
}
internal class QueueDebugView
{
private Queue _queue;
public QueueDebugView(Queue queue)
{
if (queue == null)
throw new ArgumentNullException(nameof(queue));
Contract.EndContractBlock();
_queue = queue;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public Object[] Items
{
get
{
return _queue.ToArray();
}
}
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Diagnostics;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Utils;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Scoring;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Rulesets.Osu.Statistics
{
public class AccuracyHeatmap : CompositeDrawable
{
/// <summary>
/// Size of the inner circle containing the "hit" points, relative to the size of this <see cref="AccuracyHeatmap"/>.
/// All other points outside of the inner circle are "miss" points.
/// </summary>
private const float inner_portion = 0.8f;
/// <summary>
/// Number of rows/columns of points.
/// ~4px per point @ 128x128 size (the contents of the <see cref="AccuracyHeatmap"/> are always square). 1089 total points.
/// </summary>
private const int points_per_dimension = 33;
private const float rotation = 45;
private BufferedContainer bufferedGrid;
private GridContainer pointGrid;
private readonly ScoreInfo score;
private readonly IBeatmap playableBeatmap;
private const float line_thickness = 2;
/// <summary>
/// The highest count of any point currently being displayed.
/// </summary>
protected float PeakValue { get; private set; }
public AccuracyHeatmap(ScoreInfo score, IBeatmap playableBeatmap)
{
this.score = score;
this.playableBeatmap = playableBeatmap;
}
[BackgroundDependencyLoader]
private void load()
{
InternalChild = new Container
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
FillMode = FillMode.Fit,
Children = new Drawable[]
{
new CircularContainer
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
Size = new Vector2(inner_portion),
Masking = true,
BorderThickness = line_thickness,
BorderColour = Color4.White,
Child = new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4Extensions.FromHex("#202624")
}
},
new Container
{
RelativeSizeAxes = Axes.Both,
Children = new Drawable[]
{
new Container
{
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding(1),
Child = new Container
{
RelativeSizeAxes = Axes.Both,
Masking = true,
Children = new Drawable[]
{
new Box
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
EdgeSmoothness = new Vector2(1),
RelativeSizeAxes = Axes.Y,
Height = 2, // We're rotating along a diagonal - we don't really care how big this is.
Width = line_thickness / 2,
Rotation = -rotation,
Alpha = 0.3f,
},
new Box
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
EdgeSmoothness = new Vector2(1),
RelativeSizeAxes = Axes.Y,
Height = 2, // We're rotating along a diagonal - we don't really care how big this is.
Width = line_thickness / 2, // adjust for edgesmoothness
Rotation = rotation
},
}
},
},
new Box
{
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
Width = 10,
EdgeSmoothness = new Vector2(1),
Height = line_thickness / 2, // adjust for edgesmoothness
},
new Box
{
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
EdgeSmoothness = new Vector2(1),
Width = line_thickness / 2, // adjust for edgesmoothness
Height = 10,
}
}
},
bufferedGrid = new BufferedContainer
{
RelativeSizeAxes = Axes.Both,
CacheDrawnFrameBuffer = true,
BackgroundColour = Color4Extensions.FromHex("#202624").Opacity(0),
Child = pointGrid = new GridContainer
{
RelativeSizeAxes = Axes.Both
}
},
}
};
Vector2 centre = new Vector2(points_per_dimension) / 2;
float innerRadius = centre.X * inner_portion;
Drawable[][] points = new Drawable[points_per_dimension][];
for (int r = 0; r < points_per_dimension; r++)
{
points[r] = new Drawable[points_per_dimension];
for (int c = 0; c < points_per_dimension; c++)
{
HitPointType pointType = Vector2.Distance(new Vector2(c, r), centre) <= innerRadius
? HitPointType.Hit
: HitPointType.Miss;
var point = new HitPoint(pointType, this)
{
BaseColour = pointType == HitPointType.Hit ? new Color4(102, 255, 204, 255) : new Color4(255, 102, 102, 255)
};
points[r][c] = point;
}
}
pointGrid.Content = points;
if (score.HitEvents == null || score.HitEvents.Count == 0)
return;
// Todo: This should probably not be done like this.
float radius = OsuHitObject.OBJECT_RADIUS * (1.0f - 0.7f * (playableBeatmap.Difficulty.CircleSize - 5) / 5) / 2;
foreach (var e in score.HitEvents.Where(e => e.HitObject is HitCircle && !(e.HitObject is SliderTailCircle)))
{
if (e.LastHitObject == null || e.Position == null)
continue;
AddPoint(((OsuHitObject)e.LastHitObject).StackedEndPosition, ((OsuHitObject)e.HitObject).StackedEndPosition, e.Position.Value, radius);
}
}
protected void AddPoint(Vector2 start, Vector2 end, Vector2 hitPoint, float radius)
{
if (pointGrid.Content.Count == 0)
return;
double angle1 = Math.Atan2(end.Y - hitPoint.Y, hitPoint.X - end.X); // Angle between the end point and the hit point.
double angle2 = Math.Atan2(end.Y - start.Y, start.X - end.X); // Angle between the end point and the start point.
double finalAngle = angle2 - angle1; // Angle between start, end, and hit points.
float normalisedDistance = Vector2.Distance(hitPoint, end) / radius;
// Consider two objects placed horizontally, with the start on the left and the end on the right.
// The above calculated the angle between {end, start}, and the angle between {end, hitPoint}, in the form:
// +pi | 0
// O --------- O -----> Note: Math.Atan2 has a range (-pi <= theta <= +pi)
// -pi | 0
// E.g. If the hit point was directly above end, it would have an angle pi/2.
//
// It also calculated the angle separating hitPoint from the line joining {start, end}, that is anti-clockwise in the form:
// 0 | pi
// O --------- O ----->
// 2pi | pi
//
// However keep in mind that cos(0)=1 and cos(2pi)=1, whereas we actually want these values to appear on the left, so the x-coordinate needs to be inverted.
// Likewise sin(pi/2)=1 and sin(3pi/2)=-1, whereas we actually want these values to appear on the bottom/top respectively, so the y-coordinate also needs to be inverted.
//
// We also need to apply the anti-clockwise rotation.
var rotatedAngle = finalAngle - MathUtils.DegreesToRadians(rotation);
var rotatedCoordinate = -1 * new Vector2((float)Math.Cos(rotatedAngle), (float)Math.Sin(rotatedAngle));
Vector2 localCentre = new Vector2(points_per_dimension - 1) / 2;
float localRadius = localCentre.X * inner_portion * normalisedDistance; // The radius inside the inner portion which of the heatmap which the closest point lies.
Vector2 localPoint = localCentre + localRadius * rotatedCoordinate;
// Find the most relevant hit point.
int r = Math.Clamp((int)Math.Round(localPoint.Y), 0, points_per_dimension - 1);
int c = Math.Clamp((int)Math.Round(localPoint.X), 0, points_per_dimension - 1);
PeakValue = Math.Max(PeakValue, ((HitPoint)pointGrid.Content[r][c]).Increment());
bufferedGrid.ForceRedraw();
}
private class HitPoint : Circle
{
/// <summary>
/// The base colour which will be lightened/darkened depending on the value of this <see cref="HitPoint"/>.
/// </summary>
public Color4 BaseColour;
private readonly HitPointType pointType;
private readonly AccuracyHeatmap heatmap;
public override bool IsPresent => count > 0;
public HitPoint(HitPointType pointType, AccuracyHeatmap heatmap)
{
this.pointType = pointType;
this.heatmap = heatmap;
RelativeSizeAxes = Axes.Both;
Alpha = 1;
}
private int count;
/// <summary>
/// Increment the value of this point by one.
/// </summary>
/// <returns>The value after incrementing.</returns>
public int Increment()
{
return ++count;
}
protected override void Update()
{
base.Update();
// the point at which alpha is saturated and we begin to adjust colour lightness.
const float lighten_cutoff = 0.95f;
// the amount of lightness to attribute regardless of relative value to peak point.
const float non_relative_portion = 0.2f;
float amount = 0;
// give some amount of alpha regardless of relative count
amount += non_relative_portion * Math.Min(1, count / 10f);
// add relative portion
amount += (1 - non_relative_portion) * (count / heatmap.PeakValue);
// apply easing
amount = (float)Interpolation.ApplyEasing(Easing.OutQuint, Math.Min(1, amount));
Debug.Assert(amount <= 1);
Alpha = Math.Min(amount / lighten_cutoff, 1);
if (pointType == HitPointType.Hit)
Colour = BaseColour.Lighten(Math.Max(0, amount - lighten_cutoff));
}
}
private enum HitPointType
{
Hit,
Miss
}
}
}
| |
using UnityEngine;
using UnityEngine.Rendering;
namespace Kvant
{
//[ExecuteInEditMode]
[RequireComponent(typeof(MeshRenderer))]
[AddComponentMenu("Kvant/Wig Controller")]
public class WigController : MonoBehaviour
{
#region Editable properties
// Foundation settings
[SerializeField] Transform _target;
public Transform target {
get { return _target; }
set { _target = value; }
}
[SerializeField] WigTemplate _template;
public WigTemplate template {
get { return _template; }
set {
if (_template != value) {
_template = value;
_reconfigured = true;
}
}
}
// Constants
[SerializeField] float _maxTimeStep = 0.006f;
public float maxTimeStep {
get { return _maxTimeStep; }
set { _maxTimeStep = value; }
}
[SerializeField] float _randomSeed;
public float randomSeed {
get { return _randomSeed; }
set {
if (_randomSeed != value) {
_randomSeed = value;
_needsReset = true;
}
}
}
// Filament length
[SerializeField, Range(0.01f, 100)] float _length = 1;
public float length {
get { return _length; }
set { _length = value; }
}
[SerializeField, Range(0, 1)] float _lengthRandomness = 0.5f;
public float lengthRandomness {
get { return _lengthRandomness; }
set { _lengthRandomness = value; }
}
// Dynamics
[SerializeField] float _spring = 600;
public float spring {
get { return _spring; }
set { _spring = value; }
}
[SerializeField] float _damping = 30;
public float damping {
get { return _damping; }
set { _damping = value; }
}
[SerializeField] Vector3 _gravity = new Vector3(0, -8, 2);
public Vector3 gravity {
get { return _gravity; }
set { _gravity = value; }
}
// Noise field
[SerializeField] float _noiseAmplitude = 5;
public float noiseAmplitude {
get { return _noiseAmplitude; }
set { _noiseAmplitude = value; }
}
[SerializeField] float _noiseFrequency = 1;
public float noiseFrequency {
get { return _noiseFrequency; }
set { _noiseFrequency = value; }
}
[SerializeField] float _noiseSpeed = 0.1f;
public float noiseSpeed {
get { return _noiseSpeed; }
set { _noiseSpeed = value; }
}
#endregion
#region Public functions
public void ResetSimulation()
{
_needsReset = true;
}
#if UNITY_EDITOR
public void RequestReconfigurationFromEditor()
{
_reconfigured = true;
}
#endif
#endregion
#region Private members
// Just used to have references to the shader asset.
[SerializeField, HideInInspector] Shader _kernels;
// Temporary objects for simulation
Material _material;
RenderTexture _positionBuffer1;
RenderTexture _positionBuffer2;
RenderTexture _velocityBuffer1;
RenderTexture _velocityBuffer2;
RenderTexture _basisBuffer1;
RenderTexture _basisBuffer2;
// Custom properties applied to the mesh renderer.
MaterialPropertyBlock _propertyBlock;
// Previous position/rotation of the target transform.
Vector3 _targetPosition;
Quaternion _targetRotation;
// Reset flags
bool _reconfigured = true;
bool _needsReset;
// Create a buffer for simulation.
public RenderTexture CreateSimulationBuffer()
{
var format = RenderTextureFormat.ARGBFloat;
var width = _template.filamentCount;
var buffer = new RenderTexture(width, _template.segmentCount, 0, format);
buffer.hideFlags = HideFlags.HideAndDontSave;
buffer.filterMode = FilterMode.Point;
buffer.wrapMode = TextureWrapMode.Clamp;
return buffer;
}
// Try to release a temporary object.
void ReleaseObject(Object o)
{
if (o != null)
if (Application.isPlaying)
Destroy(o);
else
DestroyImmediate(o);
}
// Create and initialize internal temporary objects.
void SetUpTemporaryObjects()
{
if (_material == null)
{
var shader = Shader.Find("Hidden/Kvant/Wig/Kernels");
_material = new Material(shader);
_material.hideFlags = HideFlags.HideAndDontSave;
}
_material.SetTexture("_FoundationData", _template.foundation);
_material.SetFloat("_RandomSeed", _randomSeed);
if (_positionBuffer1 == null) _positionBuffer1 = CreateSimulationBuffer();
if (_positionBuffer2 == null) _positionBuffer2 = CreateSimulationBuffer();
if (_velocityBuffer1 == null) _velocityBuffer1 = CreateSimulationBuffer();
if (_velocityBuffer2 == null) _velocityBuffer2 = CreateSimulationBuffer();
if (_basisBuffer1 == null) _basisBuffer1 = CreateSimulationBuffer();
if (_basisBuffer2 == null) _basisBuffer2 = CreateSimulationBuffer();
}
// Release internal temporary objects.
void ReleaseTemporaryObjects()
{
ReleaseObject(_material); _material = null;
ReleaseObject(_positionBuffer1); _positionBuffer1 = null;
ReleaseObject(_positionBuffer2); _positionBuffer2 = null;
ReleaseObject(_velocityBuffer1); _velocityBuffer1 = null;
ReleaseObject(_velocityBuffer2); _velocityBuffer2 = null;
ReleaseObject(_basisBuffer1); _basisBuffer1 = null;
ReleaseObject(_basisBuffer2); _basisBuffer2 = null;
}
// Reset the simulation state.
void ResetSimulationState()
{
_targetPosition = _target.position;
_targetRotation = _target.rotation;
UpdateSimulationParameters(_targetPosition, _targetRotation, 0);
// This is needed to give the texel size for the shader.
_material.SetTexture("_PositionBuffer", _positionBuffer1);
Graphics.Blit(null, _positionBuffer2, _material, 0);
Graphics.Blit(null, _velocityBuffer2, _material, 1);
Graphics.Blit(null, _basisBuffer2, _material, 2);
}
// Update the parameters in the simulation kernels.
void UpdateSimulationParameters(Vector3 pos, Quaternion rot, float dt)
{
_material.SetMatrix("_FoundationTransform",
Matrix4x4.TRS(pos, rot, Vector3.one)
);
_material.SetFloat("_DeltaTime", dt);
_material.SetVector("_SegmentLength", new Vector2(
_length / _template.segmentCount, _lengthRandomness
));
_material.SetFloat("_Spring", _spring);
_material.SetFloat("_Damping", _damping);
_material.SetVector("_Gravity", _gravity);
_material.SetVector("_NoiseParams", new Vector3(
_noiseAmplitude, _noiseFrequency, _noiseSpeed
));
}
// Invoke the simulation kernels.
void InvokeSimulationKernels(Vector3 pos, Quaternion rot, float dt)
{
// Swap the buffers.
var pb = _positionBuffer1;
var vb = _velocityBuffer1;
var nb = _basisBuffer1;
_positionBuffer1 = _positionBuffer2;
_velocityBuffer1 = _velocityBuffer2;
_basisBuffer1 = _basisBuffer2;
_positionBuffer2 = pb;
_velocityBuffer2 = vb;
_basisBuffer2 = nb;
// Update the velocity buffer.
UpdateSimulationParameters(pos, rot, dt);
_material.SetTexture("_PositionBuffer", _positionBuffer1);
_material.SetTexture("_VelocityBuffer", _velocityBuffer1);
Graphics.Blit(null, _velocityBuffer2, _material, 4);
// Update the position buffer.
_material.SetTexture("_VelocityBuffer", _velocityBuffer2);
Graphics.Blit(null, _positionBuffer2, _material, 3);
// Update the basis buffer.
_material.SetTexture("_PositionBuffer", _positionBuffer2);
_material.SetTexture("_BasisBuffer", _basisBuffer1);
Graphics.Blit(null, _basisBuffer2, _material, 5);
}
// Do simulation.
int Simulate(float deltaTime)
{
var newTargetPosition = _target.position;
var newTargetRotation = _target.rotation;
var steps = Mathf.CeilToInt(deltaTime / _maxTimeStep);
steps = Mathf.Clamp(steps, 1, 100);
var dt = deltaTime / steps;
for (var i = 0; i < steps; i++)
{
var p = (float)i / steps;
var pos = Vector3.Lerp(_targetPosition, newTargetPosition, p);
var rot = Quaternion.Lerp(_targetRotation, newTargetRotation, p);
InvokeSimulationKernels(pos, rot, dt);
}
_targetPosition = newTargetPosition;
_targetRotation = newTargetRotation;
return steps;
}
// Update external components: mesh filter.
void UpdateMeshFilter()
{
var meshFilter = GetComponent<MeshFilter>();
// Add a new mesh filter if missing.
if (meshFilter == null)
{
meshFilter = gameObject.AddComponent<MeshFilter>();
meshFilter.hideFlags = HideFlags.NotEditable;
}
if (meshFilter.sharedMesh != _template.mesh)
meshFilter.sharedMesh = _template.mesh;
}
// Update external components: mesh renderer.
void UpdateMeshRenderer(float motionScale)
{
var meshRenderer = GetComponent<MeshRenderer>();
if (_propertyBlock == null)
_propertyBlock = new MaterialPropertyBlock();
_propertyBlock.SetTexture("_PositionBuffer", _positionBuffer2);
_propertyBlock.SetTexture("_PreviousPositionBuffer", _positionBuffer1);
_propertyBlock.SetTexture("_BasisBuffer", _basisBuffer2);
_propertyBlock.SetTexture("_PreviousBasisBuffer", _basisBuffer1);
_propertyBlock.SetFloat("_RandomSeed", _randomSeed);
_propertyBlock.SetFloat("_MotionScale", motionScale);
meshRenderer.SetPropertyBlock(_propertyBlock);
}
#endregion
#region MonoBehaviour functions
public void Reset()
{
_reconfigured = true;
}
void OnDestroy()
{
ReleaseTemporaryObjects();
}
void LateUpdate()
{
var motionScale = 1.0f;
// Do nothing if something is missing.
if (_template == null || _target == null) return;
// - Initialize temporary objects at the first frame.
// - Re-initialize temporary objects on configuration changes.
if (_reconfigured)
{
ReleaseTemporaryObjects();
SetUpTemporaryObjects();
}
// Reset simulation state when it's requested.
// This also happens when configuration changed.
if (_needsReset || _reconfigured)
{
ResetSimulationState();
// Editor: do warmup before the first frame.
if (!Application.isPlaying) motionScale = Simulate(0.4f);
_needsReset = _reconfigured = false;
}
// Advance simulation time.
if (Application.isPlaying) motionScale = Simulate(Time.deltaTime);
// Update external components (mesh filter and renderer).
UpdateMeshFilter();
UpdateMeshRenderer(motionScale);
}
#endregion
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for Additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Created on May 23, 2005
*
*/
namespace TestCases.SS.Formula.Functions
{
using System;
using NUnit.Framework;
using NPOI.SS.Formula.Functions;
/**
* @author Amol S. Deshmukh < amolweb at ya hoo dot com >
*
*/
[TestFixture]
public class TestMathX : AbstractNumericTestCase
{
[Test]
public void TestAcosh()
{
double d = 0;
d = MathX.Acosh(0);
Assert.IsTrue(Double.IsNaN(d), "Acosh 0 is NaN");
d = MathX.Acosh(1);
AssertEquals("Acosh 1 ",0, d);
d = MathX.Acosh(-1);
Assert.IsTrue(Double.IsNaN(d), "Acosh -1 is NaN");
d = MathX.Acosh(100);
AssertEquals("Acosh 100 ", 5.298292366d, d);
d = MathX.Acosh(101.001);
AssertEquals("Acosh 101.001 ",5.308253091d, d);
d = MathX.Acosh(200000);
AssertEquals("Acosh 200000 ",12.89921983d, d);
}
[Test]
public void TestAsinh()
{
double d = 0;
d = MathX.Asinh(0);
AssertEquals("asinh 0",d, 0);
d = MathX.Asinh(1);
AssertEquals("asinh 1 ",0.881373587, d);
d = MathX.Asinh(-1);
AssertEquals("asinh -1 ",-0.881373587, d);
d = MathX.Asinh(-100);
AssertEquals("asinh -100 ",-5.298342366, d);
d = MathX.Asinh(100);
AssertEquals("asinh 100 ",5.298342366, d);
d = MathX.Asinh(200000);
AssertEquals("asinh 200000",12.899219826096400, d);
d = MathX.Asinh(-200000);
AssertEquals("asinh -200000 ",-12.899223853137, d);
}
[Test]
public void TestAtanh()
{
double d = 0;
d = MathX.Atanh(0);
AssertEquals("atanh 0", d, 0);
d = MathX.Atanh(1);
AssertEquals("atanh 1 ", Double.PositiveInfinity, d);
d = MathX.Atanh(-1);
AssertEquals("atanh -1 ", Double.NegativeInfinity, d);
d = MathX.Atanh(-100);
AssertEquals("atanh -100 ", Double.NaN, d);
d = MathX.Atanh(100);
AssertEquals("atanh 100 ", Double.NaN, d);
d = MathX.Atanh(200000);
AssertEquals("atanh 200000", Double.NaN, d);
d = MathX.Atanh(-200000);
AssertEquals("atanh -200000 ", Double.NaN, d);
d = MathX.Atanh(0.1);
AssertEquals("atanh 0.1", 0.100335348, d);
d = MathX.Atanh(-0.1);
AssertEquals("atanh -0.1 ", -0.100335348, d);
}
[Test]
public void TestCosh()
{
double d = 0;
d = MathX.Cosh(0);
AssertEquals("cosh 0", 1, d);
d = MathX.Cosh(1);
AssertEquals("cosh 1 ", 1.543080635, d);
d = MathX.Cosh(-1);
AssertEquals("cosh -1 ", 1.543080635, d);
d = MathX.Cosh(-100);
AssertEquals("cosh -100 ", 1.344058570908070E+43, d);
d = MathX.Cosh(100);
AssertEquals("cosh 100 ", 1.344058570908070E+43, d);
d = MathX.Cosh(15);
AssertEquals("cosh 15", 1634508.686, d);
d = MathX.Cosh(-15);
AssertEquals("cosh -15 ", 1634508.686, d);
d = MathX.Cosh(0.1);
AssertEquals("cosh 0.1", 1.005004168, d);
d = MathX.Cosh(-0.1);
AssertEquals("cosh -0.1 ", 1.005004168, d);
}
[Test]
public void TestTanh()
{
double d = 0;
d = MathX.Tanh(0);
AssertEquals("tanh 0", 0, d);
d = MathX.Tanh(1);
AssertEquals("tanh 1 ", 0.761594156, d);
d = MathX.Tanh(-1);
AssertEquals("tanh -1 ", -0.761594156, d);
d = MathX.Tanh(-100);
AssertEquals("tanh -100 ", -1, d);
d = MathX.Tanh(100);
AssertEquals("tanh 100 ", 1, d);
d = MathX.Tanh(15);
AssertEquals("tanh 15", 1, d);
d = MathX.Tanh(-15);
AssertEquals("tanh -15 ", -1, d);
d = MathX.Tanh(0.1);
AssertEquals("tanh 0.1", 0.099667995, d);
d = MathX.Tanh(-0.1);
AssertEquals("tanh -0.1 ", -0.099667995, d);
}
[Test]
public void TestMax()
{
double[] d = new double[100];
d[0] = 1.1; d[1] = 2.1; d[2] = 3.1; d[3] = 4.1;
d[4] = 5.1; d[5] = 6.1; d[6] = 7.1; d[7] = 8.1;
d[8] = 9.1; d[9] = 10.1; d[10] = 11.1; d[11] = 12.1;
d[12] = 13.1; d[13] = 14.1; d[14] = 15.1; d[15] = 16.1;
d[16] = 17.1; d[17] = 18.1; d[18] = 19.1; d[19] = 20.1;
double m = MathX.Max(d);
AssertEquals("Max ", 20.1, m);
d = new double[1000];
m = MathX.Max(d);
AssertEquals("Max ", 0, m);
d[0] = -1.1; d[1] = 2.1; d[2] = -3.1; d[3] = 4.1;
d[4] = -5.1; d[5] = 6.1; d[6] = -7.1; d[7] = 8.1;
d[8] = -9.1; d[9] = 10.1; d[10] = -11.1; d[11] = 12.1;
d[12] = -13.1; d[13] = 14.1; d[14] = -15.1; d[15] = 16.1;
d[16] = -17.1; d[17] = 18.1; d[18] = -19.1; d[19] = 20.1;
m = MathX.Max(d);
AssertEquals("Max ", 20.1, m);
d = new double[20];
d[0] = -1.1; d[1] = -2.1; d[2] = -3.1; d[3] = -4.1;
d[4] = -5.1; d[5] = -6.1; d[6] = -7.1; d[7] = -8.1;
d[8] = -9.1; d[9] = -10.1; d[10] = -11.1; d[11] = -12.1;
d[12] = -13.1; d[13] = -14.1; d[14] = -15.1; d[15] = -16.1;
d[16] = -17.1; d[17] = -18.1; d[18] = -19.1; d[19] = -20.1;
m = MathX.Max(d);
AssertEquals("Max ", -1.1, m);
}
[Test]
public void TestMin()
{
double[] d = new double[100];
d[0] = 1.1; d[1] = 2.1; d[2] = 3.1; d[3] = 4.1;
d[4] = 5.1; d[5] = 6.1; d[6] = 7.1; d[7] = 8.1;
d[8] = 9.1; d[9] = 10.1; d[10] = 11.1; d[11] = 12.1;
d[12] = 13.1; d[13] = 14.1; d[14] = 15.1; d[15] = 16.1;
d[16] = 17.1; d[17] = 18.1; d[18] = 19.1; d[19] = 20.1;
double m = MathX.Min(d);
AssertEquals("Min ", 0, m);
d = new double[20];
d[0] = 1.1; d[1] = 2.1; d[2] = 3.1; d[3] = 4.1;
d[4] = 5.1; d[5] = 6.1; d[6] = 7.1; d[7] = 8.1;
d[8] = 9.1; d[9] = 10.1; d[10] = 11.1; d[11] = 12.1;
d[12] = 13.1; d[13] = 14.1; d[14] = 15.1; d[15] = 16.1;
d[16] = 17.1; d[17] = 18.1; d[18] = 19.1; d[19] = 20.1;
m = MathX.Min(d);
AssertEquals("Min ", 1.1, m);
d = new double[1000];
m = MathX.Min(d);
AssertEquals("Min ", 0, m);
d[0] = -1.1; d[1] = 2.1; d[2] = -3.1; d[3] = 4.1;
d[4] = -5.1; d[5] = 6.1; d[6] = -7.1; d[7] = 8.1;
d[8] = -9.1; d[9] = 10.1; d[10] = -11.1; d[11] = 12.1;
d[12] = -13.1; d[13] = 14.1; d[14] = -15.1; d[15] = 16.1;
d[16] = -17.1; d[17] = 18.1; d[18] = -19.1; d[19] = 20.1;
m = MathX.Min(d);
AssertEquals("Min ", -19.1, m);
d = new double[20];
d[0] = -1.1; d[1] = -2.1; d[2] = -3.1; d[3] = -4.1;
d[4] = -5.1; d[5] = -6.1; d[6] = -7.1; d[7] = -8.1;
d[8] = -9.1; d[9] = -10.1; d[10] = -11.1; d[11] = -12.1;
d[12] = -13.1; d[13] = -14.1; d[14] = -15.1; d[15] = -16.1;
d[16] = -17.1; d[17] = -18.1; d[18] = -19.1; d[19] = -20.1;
m = MathX.Min(d);
AssertEquals("Min ", -20.1, m);
}
[Test]
public void TestProduct()
{
Assert.AreEqual(0, MathX.Product(null), "Product ");
Assert.AreEqual(0, MathX.Product(new double[] { }), "Product ");
Assert.AreEqual(0, MathX.Product(new double[] { 1, 0 }), "Product ");
Assert.AreEqual(1, MathX.Product(new double[] { 1 }), "Product ");
Assert.AreEqual(1, MathX.Product(new double[] { 1, 1 }), "Product ");
Assert.AreEqual(10, MathX.Product(new double[] { 10, 1 }), "Product ");
Assert.AreEqual(-2, MathX.Product(new double[] { 2, -1 }), "Product ");
Assert.AreEqual(99988000209999d, MathX.Product(new double[] { 99999, 99999, 9999 }), "Product ");
double[] d = new double[100];
d[0] = 1.1; d[1] = 2.1; d[2] = 3.1; d[3] = 4.1;
d[4] = 5.1; d[5] = 6.1; d[6] = 7.1; d[7] = 8.1;
d[8] = 9.1; d[9] = 10.1; d[10] = 11.1; d[11] = 12.1;
d[12] = 13.1; d[13] = 14.1; d[14] = 15.1; d[15] = 16.1;
d[16] = 17.1; d[17] = 18.1; d[18] = 19.1; d[19] = 20.1;
double m = MathX.Product(d);
AssertEquals("Product", 0, m);
d = new double[20];
d[0] = 1.1; d[1] = 2.1; d[2] = 3.1; d[3] = 4.1;
d[4] = 5.1; d[5] = 6.1; d[6] = 7.1; d[7] = 8.1;
d[8] = 9.1; d[9] = 10.1; d[10] = 11.1; d[11] = 12.1;
d[12] = 13.1; d[13] = 14.1; d[14] = 15.1; d[15] = 16.1;
d[16] = 17.1; d[17] = 18.1; d[18] = 19.1; d[19] = 20.1;
m = MathX.Product(d);
AssertEquals("Product ", 3459946360003355534d, m);
d = new double[1000];
m = MathX.Product(d);
AssertEquals("Product ", 0, m);
d = new double[20];
d[0] = -1.1; d[1] = -2.1; d[2] = -3.1; d[3] = -4.1;
d[4] = -5.1; d[5] = -6.1; d[6] = -7.1; d[7] = -8.1;
d[8] = -9.1; d[9] = -10.1; d[10] = -11.1; d[11] = -12.1;
d[12] = -13.1; d[13] = -14.1; d[14] = -15.1; d[15] = -16.1;
d[16] = -17.1; d[17] = -18.1; d[18] = -19.1; d[19] = -20.1;
m = MathX.Product(d);
AssertEquals("Product ", 3459946360003355534d, m);
}
[Test]
public void TestMod()
{
//example from Excel help
Assert.AreEqual(1.0, MathX.Mod(3, 2));
Assert.AreEqual(1.0, MathX.Mod(-3, 2));
Assert.AreEqual(-1.0, MathX.Mod(3, -2));
Assert.AreEqual(-1.0, MathX.Mod(-3, -2));
Assert.AreEqual(0.0, MathX.Mod(0, 2));
Assert.AreEqual(Double.NaN, MathX.Mod(3, 0));
Assert.AreEqual((double)1.4, MathX.Mod(3.4, 2));
Assert.AreEqual((double)-1.4, MathX.Mod(-3.4, -2));
Assert.AreEqual((double)0.6000000000000001, MathX.Mod(-3.4, 2.0));// should actually be 0.6
Assert.AreEqual((double)-0.6000000000000001, MathX.Mod(3.4, -2.0));// should actually be -0.6
Assert.AreEqual(3.0, MathX.Mod(3, Double.MaxValue));
Assert.AreEqual(2.0, MathX.Mod(Double.MaxValue, 3));
// Bugzilla 50033
Assert.AreEqual(1.0, MathX.Mod(13, 12));
}
[Test]
public void TestNChooseK()
{
int n = 100;
int k = 50;
double d = MathX.NChooseK(n, k);
AssertEquals("NChooseK ", 1.00891344545564E29, d);
n = -1; k = 1;
d = MathX.NChooseK(n, k);
AssertEquals("NChooseK ", Double.NaN, d);
n = 1; k = -1;
d = MathX.NChooseK(n, k);
AssertEquals("NChooseK ", Double.NaN, d);
n = 0; k = 1;
d = MathX.NChooseK(n, k);
AssertEquals("NChooseK ", Double.NaN, d);
n = 1; k = 0;
d = MathX.NChooseK(n, k);
AssertEquals("NChooseK ", 1, d);
n = 10; k = 9;
d = MathX.NChooseK(n, k);
AssertEquals("NChooseK ", 10, d);
n = 10; k = 10;
d = MathX.NChooseK(n, k);
AssertEquals("NChooseK ", 1, d);
n = 10; k = 1;
d = MathX.NChooseK(n, k);
AssertEquals("NChooseK ", 10, d);
n = 1000; k = 1;
d = MathX.NChooseK(n, k);
AssertEquals("NChooseK ", 1000, d); // awesome ;)
n = 1000; k = 2;
d = MathX.NChooseK(n, k);
AssertEquals("NChooseK ", 499500, d); // awesome ;)
n = 13; k = 7;
d = MathX.NChooseK(n, k);
AssertEquals("NChooseK ", 1716, d);
}
[Test]
public void TestSign()
{
short minus = -1;
short zero = 0;
short plus = 1;
double d = 0;
AssertEquals("Sign ", minus, MathX.Sign(minus));
AssertEquals("Sign ", plus, MathX.Sign(plus));
AssertEquals("Sign ", zero, MathX.Sign(zero));
d = 0;
AssertEquals("Sign ", zero, MathX.Sign(d));
d = -1.000001;
AssertEquals("Sign ", minus, MathX.Sign(d));
d = -.000001;
AssertEquals("Sign ", minus, MathX.Sign(d));
d = -1E-200;
AssertEquals("Sign ", minus, MathX.Sign(d));
d = Double.NegativeInfinity;
AssertEquals("Sign ", minus, MathX.Sign(d));
d = -200.11;
AssertEquals("Sign ", minus, MathX.Sign(d));
d = -2000000000000.11;
AssertEquals("Sign ", minus, MathX.Sign(d));
d = 1.000001;
AssertEquals("Sign ", plus, MathX.Sign(d));
d = .000001;
AssertEquals("Sign ", plus, MathX.Sign(d));
d = 1E-200;
AssertEquals("Sign ", plus, MathX.Sign(d));
d = Double.PositiveInfinity;
AssertEquals("Sign ", plus, MathX.Sign(d));
d = 200.11;
AssertEquals("Sign ", plus, MathX.Sign(d));
d = 2000000000000.11;
AssertEquals("Sign ", plus, MathX.Sign(d));
}
[Test]
public void TestSinh()
{
double d = 0;
d = MathX.Sinh(0);
AssertEquals("sinh 0", 0, d);
d = MathX.Sinh(1);
AssertEquals("sinh 1 ", 1.175201194, d);
d = MathX.Sinh(-1);
AssertEquals("sinh -1 ", -1.175201194, d);
d = MathX.Sinh(-100);
AssertEquals("sinh -100 ", -1.344058570908070E+43, d);
d = MathX.Sinh(100);
AssertEquals("sinh 100 ", 1.344058570908070E+43, d);
d = MathX.Sinh(15);
AssertEquals("sinh 15", 1634508.686, d);
d = MathX.Sinh(-15);
AssertEquals("sinh -15 ", -1634508.686, d);
d = MathX.Sinh(0.1);
AssertEquals("sinh 0.1", 0.10016675, d);
d = MathX.Sinh(-0.1);
AssertEquals("sinh -0.1 ", -0.10016675, d);
}
[Test]
public void TestSum()
{
double[] d = new double[100];
d[0] = 1.1; d[1] = 2.1; d[2] = 3.1; d[3] = 4.1;
d[4] = 5.1; d[5] = 6.1; d[6] = 7.1; d[7] = 8.1;
d[8] = 9.1; d[9] = 10.1; d[10] = 11.1; d[11] = 12.1;
d[12] = 13.1; d[13] = 14.1; d[14] = 15.1; d[15] = 16.1;
d[16] = 17.1; d[17] = 18.1; d[18] = 19.1; d[19] = 20.1;
double s = MathX.Sum(d);
AssertEquals( "Sum ", 212, s );
d = new double[1000];
s = MathX.Sum(d);
AssertEquals("Sum ", 0d, s);
d[0] = -1.1; d[1] = 2.1; d[2] = -3.1; d[3] = 4.1;
d[4] = -5.1; d[5] = 6.1; d[6] = -7.1; d[7] = 8.1;
d[8] = -9.1; d[9] = 10.1; d[10] = -11.1; d[11] = 12.1;
d[12] = -13.1; d[13] = 14.1; d[14] = -15.1; d[15] = 16.1;
d[16] = -17.1; d[17] = 18.1; d[18] = -19.1; d[19] = 20.1;
s = MathX.Sum(d);
AssertEquals("Sum ", 10d, s);
d[0] = -1.1; d[1] = -2.1; d[2] = -3.1; d[3] = -4.1;
d[4] = -5.1; d[5] = -6.1; d[6] = -7.1; d[7] = -8.1;
d[8] = -9.1; d[9] = -10.1; d[10] = -11.1; d[11] = -12.1;
d[12] = -13.1; d[13] = -14.1; d[14] = -15.1; d[15] = -16.1;
d[16] = -17.1; d[17] = -18.1; d[18] = -19.1; d[19] = -20.1;
s = MathX.Sum(d);
AssertEquals("Sum ", -212d, s);
}
[Test]
public void TestSumsq()
{
double[] d = new double[100];
d[0] = 1.1; d[1] = 2.1; d[2] = 3.1; d[3] = 4.1;
d[4] = 5.1; d[5] = 6.1; d[6] = 7.1; d[7] = 8.1;
d[8] = 9.1; d[9] = 10.1; d[10] = 11.1; d[11] = 12.1;
d[12] = 13.1; d[13] = 14.1; d[14] = 15.1; d[15] = 16.1;
d[16] = 17.1; d[17] = 18.1; d[18] = 19.1; d[19] = 20.1;
double s = MathX.Sumsq(d);
AssertEquals("Sumsq ", 2912.2, s);
d = new double[1000];
s = MathX.Sumsq(d);
AssertEquals("Sumsq ", 0, s);
d[0] = -1.1; d[1] = 2.1; d[2] = -3.1; d[3] = 4.1;
d[4] = -5.1; d[5] = 6.1; d[6] = -7.1; d[7] = 8.1;
d[8] = -9.1; d[9] = 10.1; d[10] = -11.1; d[11] = 12.1;
d[12] = -13.1; d[13] = 14.1; d[14] = -15.1; d[15] = 16.1;
d[16] = -17.1; d[17] = 18.1; d[18] = -19.1; d[19] = 20.1;
s = MathX.Sumsq(d);
AssertEquals("Sumsq ", 2912.2, s);
d[0] = -1.1; d[1] = -2.1; d[2] = -3.1; d[3] = -4.1;
d[4] = -5.1; d[5] = -6.1; d[6] = -7.1; d[7] = -8.1;
d[8] = -9.1; d[9] = -10.1; d[10] = -11.1; d[11] = -12.1;
d[12] = -13.1; d[13] = -14.1; d[14] = -15.1; d[15] = -16.1;
d[16] = -17.1; d[17] = -18.1; d[18] = -19.1; d[19] = -20.1;
s = MathX.Sumsq(d);
AssertEquals("Sumsq ", 2912.2, s);
}
[Test]
public void TestFactorial()
{
int n = 0;
double s = 0;
n = 0;
s = MathX.Factorial(n);
AssertEquals("Factorial ", 1, s);
n = 1;
s = MathX.Factorial(n);
AssertEquals("Factorial ", 1, s);
n = 10;
s = MathX.Factorial(n);
AssertEquals("Factorial ", 3628800, s);
n = 99;
s = MathX.Factorial(n);
AssertEquals("Factorial ", 9.33262154439E+155, s);
n = -1;
s = MathX.Factorial(n);
AssertEquals("Factorial ", Double.NaN, s);
n = Int32.MaxValue;
s = MathX.Factorial(n);
AssertEquals("Factorial ", Double.PositiveInfinity, s);
}
[Test]
public void TestSumx2my2()
{
double[] xarr = null;
double[] yarr = null;
xarr = new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
yarr = new double[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
ConfirmSumx2my2(xarr, yarr, 100);
xarr = new double[] { -1, -2, -3, -4, -5, -6, -7, -8, -9, -10 };
yarr = new double[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
ConfirmSumx2my2(xarr, yarr, 100);
xarr = new double[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
yarr = new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
ConfirmSumx2my2(xarr, yarr, -100);
xarr = new double[] { 10 };
yarr = new double[] { 9 };
ConfirmSumx2my2(xarr, yarr, 19);
xarr = new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
yarr = new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
ConfirmSumx2my2(xarr, yarr, 0);
}
[Test]
public void TestSumx2py2()
{
double[] xarr = null;
double[] yarr = null;
xarr = new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
yarr = new double[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
ConfirmSumx2py2(xarr, yarr, 670);
xarr = new double[] { -1, -2, -3, -4, -5, -6, -7, -8, -9, -10 };
yarr = new double[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
ConfirmSumx2py2(xarr, yarr, 670);
xarr = new double[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
yarr = new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
ConfirmSumx2py2(xarr, yarr, 670);
xarr = new double[] { 10 };
yarr = new double[] { 9 };
ConfirmSumx2py2(xarr, yarr, 181);
xarr = new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
yarr = new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
ConfirmSumx2py2(xarr, yarr, 770);
}
[Test]
public void TestSumxmy2()
{
double[] xarr = null;
double[] yarr = null;
xarr = new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
yarr = new double[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
ConfirmSumxmy2(xarr, yarr, 10);
xarr = new double[] { -1, -2, -3, -4, -5, -6, -7, -8, -9, -10 };
yarr = new double[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
ConfirmSumxmy2(xarr, yarr, 1330);
xarr = new double[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
yarr = new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
ConfirmSumxmy2(xarr, yarr, 10);
xarr = new double[] { 10 };
yarr = new double[] { 9 };
ConfirmSumxmy2(xarr, yarr, 1);
xarr = new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
yarr = new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
ConfirmSumxmy2(xarr, yarr, 0);
}
private static void ConfirmSumx2my2(double[] xarr, double[] yarr, double expectedResult)
{
ConfirmXY(new Sumx2my2().CreateAccumulator(), xarr, yarr, expectedResult);
}
private static void ConfirmSumx2py2(double[] xarr, double[] yarr, double expectedResult)
{
ConfirmXY(new Sumx2py2().CreateAccumulator(), xarr, yarr, expectedResult);
}
private static void ConfirmSumxmy2(double[] xarr, double[] yarr, double expectedResult)
{
ConfirmXY(new Sumxmy2().CreateAccumulator(), xarr, yarr, expectedResult);
}
private static void ConfirmXY(Accumulator acc, double[] xarr, double[] yarr,
double expectedResult)
{
double result = 0.0;
for (int i = 0; i < xarr.Length; i++)
{
result += acc.Accumulate(xarr[i], yarr[i]);
}
Assert.AreEqual(expectedResult, result, 0.0);
}
[Test]
public void TestRound()
{
double d = 0;
int p = 0;
d = 0; p = 0;
AssertEquals("round ", 0, MathX.Round(d, p));
d = 10; p = 0;
AssertEquals("round ", 10, MathX.Round(d, p));
d = 123.23; p = 0;
AssertEquals("round ", 123, MathX.Round(d, p));
d = -123.23; p = 0;
AssertEquals("round ", -123, MathX.Round(d, p));
d = 123.12; p = 2;
AssertEquals("round ", 123.12, MathX.Round(d, p));
d = 88.123459; p = 5;
AssertEquals("round ", 88.12346, MathX.Round(d, p));
d = 0; p = 2;
AssertEquals("round ", 0, MathX.Round(d, p));
d = 0; p = -1;
AssertEquals("round ", 0, MathX.Round(d, p));
d = 0.01; p = -1;
AssertEquals("round ", 0, MathX.Round(d, p));
d = 123.12; p = -2;
AssertEquals("round ", 100, MathX.Round(d, p));
d = 88.123459; p = -3;
AssertEquals("round ", 0, MathX.Round(d, p));
d = 49.00000001; p = -1;
AssertEquals("round ", 50, MathX.Round(d, p));
d = 149.999999; p = -2;
AssertEquals("round ", 100, MathX.Round(d, p));
d = 150.0; p = -2;
AssertEquals("round ", 200, MathX.Round(d, p));
d = 2162.615d; p = 2;
AssertEquals("round ", 2162.62d, MathX.Round(d, p));
d = 0.049999999999999975d; p = 2;
AssertEquals("round ", 0.05d, MathX.Round(d, p));
d = 0.049999999999999975d; p = 1;
AssertEquals("round ", 0.1d, MathX.Round(d, p));
d = Double.NaN; p = 1;
AssertEquals("round ", Double.NaN, MathX.Round(d, p));
d = Double.PositiveInfinity; p = 1;
AssertEquals("round ", Double.NaN, MathX.Round(d, p));
d = Double.NegativeInfinity; p = 1;
AssertEquals("round ", Double.NaN, MathX.Round(d, p));
d = Double.MaxValue; p = 1;
AssertEquals("round ", Double.MaxValue, MathX.Round(d, p));
d = Double.MinValue; p = 1;
AssertEquals("round ", 0.0d, MathX.Round(d, p));
d = 481.75478; p = 2;
AssertEquals("round ", 481.75d, MathX.Round(d, p));
}
[Test]
public void TestRoundDown()
{
double d = 0;
int p = 0;
d = 0; p = 0;
AssertEquals("roundDown ", 0, MathX.RoundDown(d, p));
d = 10; p = 0;
AssertEquals("roundDown ", 10, MathX.RoundDown(d, p));
d = 123.99; p = 0;
AssertEquals("roundDown ", 123, MathX.RoundDown(d, p));
d = -123.99; p = 0;
AssertEquals("roundDown ", -123, MathX.RoundDown(d, p));
d = 123.99; p = 2;
AssertEquals("roundDown ", 123.99, MathX.RoundDown(d, p));
d = 88.123459; p = 5;
AssertEquals("roundDown ", 88.12345, MathX.RoundDown(d, p));
d = 0; p = 2;
AssertEquals("roundDown ", 0, MathX.RoundDown(d, p));
d = 0; p = -1;
AssertEquals("roundDown ", 0, MathX.RoundDown(d, p));
d = 0.01; p = -1;
AssertEquals("roundDown ", 0, MathX.RoundDown(d, p));
d = 199.12; p = -2;
AssertEquals("roundDown ", 100, MathX.RoundDown(d, p));
d = 88.123459; p = -3;
AssertEquals("roundDown ", 0, MathX.RoundDown(d, p));
d = 99.00000001; p = -1;
AssertEquals("roundDown ", 90, MathX.RoundDown(d, p));
d = 100.00001; p = -2;
AssertEquals("roundDown ", 100, MathX.RoundDown(d, p));
d = 150.0; p = -2;
AssertEquals("roundDown ", 100, MathX.RoundDown(d, p));
d = 0.049999999999999975d; p = 2;
AssertEquals("roundDown ", 0.04d, MathX.RoundDown(d, p));
d = 0.049999999999999975d; p = 1;
AssertEquals("roundDown ", 0.0d, MathX.RoundDown(d, p));
d = Double.NaN; p = 1;
AssertEquals("roundDown ", Double.NaN, MathX.RoundDown(d, p));
d = Double.PositiveInfinity; p = 1;
AssertEquals("roundDown ", Double.NaN, MathX.RoundDown(d, p));
d = Double.NegativeInfinity; p = 1;
AssertEquals("roundDown ", Double.NaN, MathX.RoundDown(d, p));
d = Double.MaxValue; p = 1;
AssertEquals("roundDown ", Double.MaxValue, MathX.RoundDown(d, p));
d = Double.MinValue; p = 1;
AssertEquals("roundDown ", 0.0d, MathX.RoundDown(d, p));
}
[Test]
public void TestRoundUp()
{
double d = 0;
int p = 0;
d = 0; p = 0;
AssertEquals("roundUp ", 0, MathX.RoundUp(d, p));
d = 10; p = 0;
AssertEquals("roundUp ", 10, MathX.RoundUp(d, p));
d = 123.23; p = 0;
AssertEquals("roundUp ", 124, MathX.RoundUp(d, p));
d = -123.23; p = 0;
AssertEquals("roundUp ", -124, MathX.RoundUp(d, p));
d = 123.12; p = 2;
AssertEquals("roundUp ", 123.12, MathX.RoundUp(d, p));
d = 88.123459; p = 5;
AssertEquals("roundUp ", 88.12346, MathX.RoundUp(d, p));
d = 0; p = 2;
AssertEquals("roundUp ", 0, MathX.RoundUp(d, p));
d = 0; p = -1;
AssertEquals("roundUp ", 0, MathX.RoundUp(d, p));
d = 0.01; p = -1;
AssertEquals("roundUp ", 10, MathX.RoundUp(d, p));
d = 123.12; p = -2;
AssertEquals("roundUp ", 200, MathX.RoundUp(d, p));
d = 88.123459; p = -3;
AssertEquals("roundUp ", 1000, MathX.RoundUp(d, p));
d = 49.00000001; p = -1;
AssertEquals("roundUp ", 50, MathX.RoundUp(d, p));
d = 149.999999; p = -2;
AssertEquals("roundUp ", 200, MathX.RoundUp(d, p));
d = 150.0; p = -2;
AssertEquals("roundUp ", 200, MathX.RoundUp(d, p));
d = 0.049999999999999975d; p = 2;
AssertEquals("round ", 0.05d, MathX.RoundUp(d, p));
d = 0.049999999999999975d; p = 1;
AssertEquals("round ", 0.1d, MathX.RoundUp(d, p));
d = Double.NaN; p = 1;
AssertEquals("round ", Double.NaN, MathX.RoundUp(d, p));
d = Double.PositiveInfinity; p = 1;
AssertEquals("round ", Double.NaN, MathX.RoundUp(d, p));
d = Double.NegativeInfinity; p = 1;
AssertEquals("round ", Double.NaN, MathX.RoundUp(d, p));
d = Double.MaxValue; p = 1;
AssertEquals("round ", Double.MaxValue, MathX.RoundUp(d, p));
d = Double.MinValue; p = 1;
AssertEquals("round ", 0.1d, MathX.RoundUp(d, p));
d = 20.44; p = 2;
AssertEquals("round ", 20.44d, MathX.RoundUp(d, p));
d = 20.445; p = 2;
AssertEquals("round ", 20.45d, MathX.RoundUp(d, p));
}
[Test]
public void TestCeiling()
{
double d = 0;
double s = 0;
d = 0; s = 0;
AssertEquals("ceiling ", 0, MathX.Ceiling(d, s));
d = 1; s = 0;
AssertEquals("ceiling ", 0, MathX.Ceiling(d, s));
d = 0; s = 1;
AssertEquals("ceiling ", 0, MathX.Ceiling(d, s));
d = -1; s = 0;
AssertEquals("ceiling ", 0, MathX.Ceiling(d, s));
d = 0; s = -1;
AssertEquals("ceiling ", 0, MathX.Ceiling(d, s));
d = 10; s = 1.11;
AssertEquals("ceiling ", 11.1, MathX.Ceiling(d, s));
d = 11.12333; s = 0.03499;
AssertEquals("ceiling ", 11.12682, MathX.Ceiling(d, s));
d = -11.12333; s = 0.03499;
AssertEquals("ceiling ", Double.NaN, MathX.Ceiling(d, s));
d = 11.12333; s = -0.03499;
AssertEquals("ceiling ", Double.NaN, MathX.Ceiling(d, s));
d = -11.12333; s = -0.03499;
AssertEquals("ceiling ", -11.12682, MathX.Ceiling(d, s));
d = 100; s = 0.001;
AssertEquals("ceiling ", 100, MathX.Ceiling(d, s));
d = -0.001; s = -9.99;
AssertEquals("ceiling ", -9.99, MathX.Ceiling(d, s));
d = 4.42; s = 0.05;
AssertEquals("ceiling ", 4.45, MathX.Ceiling(d, s));
d = 0.05; s = 4.42;
AssertEquals("ceiling ", 4.42, MathX.Ceiling(d, s));
d = 0.6666; s = 3.33;
AssertEquals("ceiling ", 3.33, MathX.Ceiling(d, s));
d = 2d / 3; s = 3.33;
AssertEquals("ceiling ", 3.33, MathX.Ceiling(d, s));
// samples from http://www.excelfunctions.net/Excel-Ceiling-Function.html
// and https://support.office.com/en-us/article/CEILING-function-0a5cd7c8-0720-4f0a-bd2c-c943e510899f
d = 22.25; s = 0.1;
AssertEquals("ceiling ", 22.3, MathX.Ceiling(d, s));
d = 22.25; s = 0.5;
AssertEquals("ceiling ", 22.5, MathX.Ceiling(d, s));
d = 22.25; s = 1;
AssertEquals("ceiling ", 23, MathX.Ceiling(d, s));
d = 22.25; s = 10;
AssertEquals("ceiling ", 30, MathX.Ceiling(d, s));
d = 22.25; s = 20;
AssertEquals("ceiling ", 40, MathX.Ceiling(d, s));
d = -22.25; s = -0.1;
AssertEquals("ceiling ", -22.3, MathX.Ceiling(d, s));
d = -22.25; s = -1;
AssertEquals("ceiling ", -23, MathX.Ceiling(d, s));
d = -22.25; s = -5;
AssertEquals("ceiling ", -25, MathX.Ceiling(d, s));
d = 22.25; s = 1;
AssertEquals("ceiling ", 23, MathX.Ceiling(d, s));
d = 22.25; s = -1;
AssertEquals("ceiling ", Double.NaN, MathX.Ceiling(d, s));
d = -22.25; s = 1;
AssertEquals("ceiling ", -22, MathX.Ceiling(d, s)); // returns an error in Excel 2007 & earlier
d = -22.25; s = -1;
AssertEquals("ceiling ", -23, MathX.Ceiling(d, s));
// test cases for newer versions of Excel where d can be negative for
d = -11.12333; s = 0.03499;
AssertEquals("ceiling ", -11.09183, MathX.Ceiling(d, s));
}
[Test]
public void TestFloor()
{
double d = 0;
double s = 0;
d = 0; s = 0;
AssertEquals("floor ", 0, MathX.Floor(d, s));
d = 1; s = 0;
AssertEquals("floor ", Double.NaN, MathX.Floor(d, s));
d = 0; s = 1;
AssertEquals("floor ", 0, MathX.Floor(d, s));
d = -1; s = 0;
AssertEquals("floor ", Double.NaN, MathX.Floor(d, s));
d = 0; s = -1;
AssertEquals("floor ", 0, MathX.Floor(d, s));
d = 10; s = 1.11;
AssertEquals("floor ", 9.99, MathX.Floor(d, s));
d = 11.12333; s = 0.03499;
AssertEquals("floor ", 11.09183, MathX.Floor(d, s));
d = -11.12333; s = 0.03499;
AssertEquals("floor ", Double.NaN, MathX.Floor(d, s));
d = 11.12333; s = -0.03499;
AssertEquals("floor ", Double.NaN, MathX.Floor(d, s));
d = -11.12333; s = -0.03499;
AssertEquals("floor ", -11.09183, MathX.Floor(d, s));
d = 100; s = 0.001;
AssertEquals("floor ", 100, MathX.Floor(d, s));
d = -0.001; s = -9.99;
AssertEquals("floor ", 0, MathX.Floor(d, s));
d = 4.42; s = 0.05;
AssertEquals("floor ", 4.4, MathX.Floor(d, s));
d = 0.05; s = 4.42;
AssertEquals("floor ", 0, MathX.Floor(d, s));
d = 0.6666; s = 3.33;
AssertEquals("floor ", 0, MathX.Floor(d, s));
d = 2d / 3; s = 3.33;
AssertEquals("floor ", 0, MathX.Floor(d, s));
// samples from http://www.excelfunctions.net/Excel-Ceiling-Function.html
// and https://support.office.com/en-us/article/CEILING-function-0a5cd7c8-0720-4f0a-bd2c-c943e510899f
d = 3.7; s = 2;
AssertEquals("floor ", 2, MathX.Floor(d, s));
d = -2.5; s = -2;
AssertEquals("floor ", -2, MathX.Floor(d, s));
d = 2.5; s = -2;
AssertEquals("floor ", Double.NaN, MathX.Floor(d, s));
d = 1.58; s = 0.1;
AssertEquals("floor ", 1.5, MathX.Floor(d, s));
d = 0.234; s = 0.01;
AssertEquals("floor ", 0.23, MathX.Floor(d, s));
}
[Ignore("not implement")]
[Test]
public void TestCoverage()
{
//// get the default constructor
//final Constructor<MathX> c = MathX.class.getDeclaredConstructor(new Class[] {});
//// make it callable from the outside
//c.setAccessible(true);
//// call it
//c.newInstance((Object[]) null);
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Logging;
namespace QuantConnect.Scheduling
{
/// <summary>
/// Real time self scheduling event
/// </summary>
public class ScheduledEvent : IDisposable
{
/// <summary>
/// Gets the default time before market close end of trading day events will fire
/// </summary>
public static readonly TimeSpan SecurityEndOfDayDelta = TimeSpan.FromMinutes(10);
/// <summary>
/// Gets the default time before midnight end of day events will fire
/// </summary>
public static readonly TimeSpan AlgorithmEndOfDayDelta = TimeSpan.FromMinutes(2);
private bool _needsMoveNext;
private bool _endOfScheduledEvents;
private readonly string _name;
private readonly Action<string, DateTime> _callback;
private readonly IEnumerator<DateTime> _orderedEventUtcTimes;
/// <summary>
/// Event that fires each time this scheduled event happens
/// </summary>
public event Action<string, DateTime> EventFired;
/// <summary>
/// Gets or sets whether this event is enabled
/// </summary>
public bool Enabled
{
get; set;
}
/// <summary>
/// Gets or sets whether this event will log each time it fires
/// </summary>
internal bool IsLoggingEnabled
{
get; set;
}
/// <summary>
/// Gets the next time this scheduled event will fire in UTC
/// </summary>
public DateTime NextEventUtcTime
{
get { return _endOfScheduledEvents ? DateTime.MaxValue : _orderedEventUtcTimes.Current; }
}
/// <summary>
/// Gets an identifier for this event
/// </summary>
public string Name
{
get { return _name; }
}
/// <summary>
/// Initalizes a new instance of the <see cref="ScheduledEvent"/> class
/// </summary>
/// <param name="name">An identifier for this event</param>
/// <param name="eventUtcTime">The date time the event should fire</param>
/// <param name="callback">Delegate to be called when the event time passes</param>
public ScheduledEvent(string name, DateTime eventUtcTime, Action<string, DateTime> callback = null)
: this(name, new[] { eventUtcTime }.AsEnumerable().GetEnumerator(), callback)
{
}
/// <summary>
/// Initalizes a new instance of the <see cref="ScheduledEvent"/> class
/// </summary>
/// <param name="name">An identifier for this event</param>
/// <param name="orderedEventUtcTimes">An enumerable that emits event times</param>
/// <param name="callback">Delegate to be called each time an event passes</param>
public ScheduledEvent(string name, IEnumerable<DateTime> orderedEventUtcTimes, Action<string, DateTime> callback = null)
: this(name, orderedEventUtcTimes.GetEnumerator(), callback)
{
}
/// <summary>
/// Initalizes a new instance of the <see cref="ScheduledEvent"/> class
/// </summary>
/// <param name="name">An identifier for this event</param>
/// <param name="orderedEventUtcTimes">An enumerator that emits event times</param>
/// <param name="callback">Delegate to be called each time an event passes</param>
public ScheduledEvent(string name, IEnumerator<DateTime> orderedEventUtcTimes, Action<string, DateTime> callback = null)
{
_name = name;
_callback = callback;
_orderedEventUtcTimes = orderedEventUtcTimes;
// prime the pump
_endOfScheduledEvents = !_orderedEventUtcTimes.MoveNext();
Enabled = true;
}
/// <summary>Serves as the default hash function. </summary>
/// <returns>A hash code for the current object.</returns>
/// <filterpriority>2</filterpriority>
public override int GetHashCode()
{
return Name.GetHashCode();
}
/// <summary>Determines whether the specified object is equal to the current object.</summary>
/// <returns>true if the specified object is equal to the current object; otherwise, false.</returns>
/// <param name="obj">The object to compare with the current object. </param>
/// <filterpriority>2</filterpriority>
public override bool Equals(object obj)
{
return !ReferenceEquals(null, obj) && ReferenceEquals(this, obj);
}
/// <summary>
/// Scans this event and fires the callback if an event happened
/// </summary>
/// <param name="utcTime">The current time in UTC</param>
internal void Scan(DateTime utcTime)
{
if (_endOfScheduledEvents)
{
return;
}
do
{
if (_needsMoveNext)
{
// if we've passed an event or are just priming the pump, we need to move next
if (!_orderedEventUtcTimes.MoveNext())
{
if (IsLoggingEnabled)
{
Log.Trace(string.Format("ScheduledEvent.{0}: Completed scheduled events.", Name));
}
_endOfScheduledEvents = true;
return;
}
if (IsLoggingEnabled)
{
Log.Trace(string.Format("ScheduledEvent.{0}: Next event: {1} UTC", Name, _orderedEventUtcTimes.Current.ToString(DateFormat.UI)));
}
}
// if time has passed our event
if (utcTime >= _orderedEventUtcTimes.Current)
{
if (IsLoggingEnabled)
{
Log.Trace(string.Format("ScheduledEvent.{0}: Firing at {1} UTC Scheduled at {2} UTC", Name,
utcTime.ToString(DateFormat.UI),
_orderedEventUtcTimes.Current.ToString(DateFormat.UI))
);
}
// fire the event
OnEventFired(_orderedEventUtcTimes.Current);
_needsMoveNext = true;
}
else
{
// we haven't passed the event time yet, so keep waiting on this Current
_needsMoveNext = false;
}
}
// keep checking events until we pass the current time, this will fire
// all 'skipped' events back to back in order, perhaps this should be handled
// in the real time handler
while (_needsMoveNext);
}
/// <summary>
/// Fast forwards this schedule to the specified time without invoking the events
/// </summary>
/// <param name="utcTime">Frontier time</param>
internal void SkipEventsUntil(DateTime utcTime)
{
// check if our next event is in the past
if (utcTime < _orderedEventUtcTimes.Current) return;
while (_orderedEventUtcTimes.MoveNext())
{
// zoom through the enumerator until we get to the desired time
if (utcTime <= _orderedEventUtcTimes.Current)
{
// pump is primed and ready to go
_needsMoveNext = false;
if (IsLoggingEnabled)
{
Log.Trace(string.Format("ScheduledEvent.{0}: Skipped events before {1}. Next event: {2}", Name,
utcTime.ToString(DateFormat.UI),
_orderedEventUtcTimes.Current.ToString(DateFormat.UI)
));
}
return;
}
}
if (IsLoggingEnabled)
{
Log.Trace(string.Format("ScheduledEvent.{0}: Exhausted event stream during skip until {1}", Name,
utcTime.ToString(DateFormat.UI)
));
}
_endOfScheduledEvents = true;
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <filterpriority>2</filterpriority>
void IDisposable.Dispose()
{
_orderedEventUtcTimes.Dispose();
}
/// <summary>
/// Event invocator for the <see cref="EventFired"/> event
/// </summary>
/// <param name="triggerTime">The event's time in UTC</param>
protected void OnEventFired(DateTime triggerTime)
{
try
{
// don't fire the event if we're turned off
if (!Enabled) return;
if (_callback != null)
{
_callback(_name, _orderedEventUtcTimes.Current);
}
var handler = EventFired;
if (handler != null) handler(_name, triggerTime);
}
catch (Exception ex)
{
Log.Error($"ScheduledEvent.Scan(): Exception was thrown in OnEventFired: {ex}");
// This scheduled event failed, so don't repeat the same event
_needsMoveNext = true;
throw new ScheduledEventException(_name, ex.Message, ex);
}
}
}
/// <summary>
/// Throw this if there is an exception in the callback function of the scheduled event
/// </summary>
public class ScheduledEventException : Exception
{
/// <summary>
/// Gets the name of the scheduled event
/// </summary>
public string ScheduledEventName { get; }
/// <summary>
/// ScheduledEventException constructor
/// </summary>
/// <param name="name">The name of the scheduled event</param>
/// <param name="message">The exception as a string</param>
/// <param name="innerException">The exception that is the cause of the current exception</param>
public ScheduledEventException(string name, string message, Exception innerException) : base(message, innerException)
{
ScheduledEventName = name;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Data;
using System.IO;
using System.Globalization;
using Trionic5Tools;
namespace T5Suite2
{
public class ECUConnection
{
public delegate void SymbolDataReceived(object sender, RealtimeDataEventArgs e);
public event ECUConnection.SymbolDataReceived onSymbolDataReceived;
public delegate void CycleCompleted(object sender, EventArgs e);
public event ECUConnection.CycleCompleted onCycleCompleted;
public delegate void WriteDataToECU(object sender, ProgressEventArgs e);
public event ECUConnection.WriteDataToECU onWriteDataToECU;
public delegate void ReadDataFromECU(object sender, ProgressEventArgs e);
public event ECUConnection.ReadDataFromECU onReadDataFromECU;
public delegate void CanBusInfo(object sender, CanInfoEventArgs e);
public event ECUConnection.CanBusInfo onCanBusInfo;
private Random ran = new Random(DateTime.Now.Millisecond);
private bool m_RunInEmulationMode = false;
public bool RunInEmulationMode
{
get { return m_RunInEmulationMode; }
set { m_RunInEmulationMode = value; }
}
private bool _stallReading = false;
public bool StallReading
{
get { return _stallReading; }
set { _stallReading = value; }
}
private bool _isT52 = false;
public bool IsT52
{
get { return _isT52; }
set { _isT52 = value; }
}
private Engine m_Engine = new Engine();
private Trionic5Tools.MapSensorType _mapSensorType = MapSensorType.MapSensor25;
public Trionic5Tools.MapSensorType MapSensorType
{
get { return _mapSensorType; }
set { _mapSensorType = value; }
}
private T5CANLib.T5CAN _tcan = null;
private T5CANLib.CAN.ICANDevice _usbcandevice = null;
private string _swversion = string.Empty;
private System.Timers.Timer m_MonitorECUTimer = new System.Timers.Timer();
private bool _prohibitRead = false;
private Trionic5SymbolConverter _symConverter = new Trionic5SymbolConverter();
private bool _engineRunning = false;
public bool EngineRunning
{
get { return _engineRunning; }
set { _engineRunning = value; }
}
private string _sramDumpFile = string.Empty;
public string SramDumpFile
{
get { return _sramDumpFile; }
set { _sramDumpFile = value; }
}
public bool ProhibitRead
{
get { return _prohibitRead; }
set { _prohibitRead = value; }
}
private SymbolCollection m_SymbolsToMonitor;
public SymbolCollection SymbolsToMonitor
{
get { return m_SymbolsToMonitor; }
set { m_SymbolsToMonitor = value; }
}
public void StartECUMonitoring()
{
//_prohibitRead = false;
_stallReading = false;
}
public void StopECUMonitoring()
{
//_prohibitRead = true;
_stallReading = true;
}
public void AddSymbolToWatchlist(string symbolname, Int32 sramaddress, Int32 length, bool systemSymbol)
{
_stallReading = true;
if (symbolname != "")
{
SymbolHelper sh = new SymbolHelper();
sh.Varname = symbolname;
sh.Start_address = sramaddress;
sh.Length = length;
sh.IsSystemSymbol = systemSymbol;
if (!CollectionContains(symbolname)) // maybe use systemSymbol as well <GS-11042011>
{
m_SymbolsToMonitor.Add(sh);
}
}
_stallReading = false;
}
public void AddSymbolToWatchlist(SymbolHelper shuser, bool systemSymbol)
{
_stallReading = true;
if (shuser.Varname != "")
{
SymbolHelper sh = new SymbolHelper();
sh.Varname = shuser.Varname;
sh.Start_address = shuser.Start_address;
sh.Length = shuser.Length;
sh.UserCorrectionFactor = shuser.UserCorrectionFactor;
sh.UserCorrectionOffset = shuser.UserCorrectionOffset;
sh.UseUserCorrection = shuser.UseUserCorrection;
sh.IsSystemSymbol = systemSymbol;
if (!CollectionContains(shuser.Varname)) // maybe use systemSymbol as well <GS-11042011>
{
m_SymbolsToMonitor.Add(sh);
}
}
_stallReading = false;
}
private bool CollectionContains(string symbolname)
{
foreach (SymbolHelper sh in m_SymbolsToMonitor)
{
if (sh.Varname == symbolname) return true;
}
return false;
}
private bool CollectionContains(string symbolname, bool systemSymbol)
{
foreach (SymbolHelper sh in m_SymbolsToMonitor)
{
if (sh.Varname == symbolname && sh.IsSystemSymbol == systemSymbol) return true;
}
return false;
}
public void RemoveSymbolFromWatchlist(string symbolname)
{
_stallReading = true;
foreach (SymbolHelper sh in m_SymbolsToMonitor)
{
if (sh.Varname == symbolname && !sh.IsSystemSymbol)
{
m_SymbolsToMonitor.Remove(sh);
return;
}
}
_stallReading = false;
}
public string Swversion
{
get { return _swversion; }
set { _swversion = value; }
}
private bool _opened = false;
public bool Opened
{
get { return _opened; }
set { _opened = value; }
}
public void DumpSRAM(string filename)
{
if(_tcan != null)
{
_prohibitRead = true;
Thread.Sleep(100);
_tcan.DumpSRAMContent(filename);
_prohibitRead = false;
}
}
public void SetWidebandvalues(double lowvoltage, double highvoltage, double lowafr, double highafr)
{
_symConverter.WidebandHighAFR = highafr;
_symConverter.WidebandLowAFR = lowafr;
_symConverter.WidebandHighVoltage = highvoltage;
_symConverter.WidebandLowVoltage = lowvoltage;
}
public ECUConnection()
{
_sramDumpFile = string.Empty;
m_Engine.onEngineRunning += new Engine.NotifyEngineState(m_Engine_onEngineRunning);
m_MonitorECUTimer.AutoReset = true;
m_MonitorECUTimer.Interval = 10;
m_MonitorECUTimer.Elapsed += new System.Timers.ElapsedEventHandler(m_MonitorECUTimer_Elapsed);
m_MonitorECUTimer.Start();
m_SymbolsToMonitor = new SymbolCollection();
/*if (_tcan == null)
{
_tcan = new T5CANLib.T5CAN();
_usbcandevice = new T5CANLib.CAN.CANUSBDevice();
_tcan.onWriteProgress += new T5CANLib.T5CAN.WriteProgress(OnWriteProgress);
_tcan.onCanInfo +=new T5CANLib.T5CAN.CanInfo(_tcan_onCanInfo);
_tcan.onReadProgress += new T5CANLib.T5CAN.ReadProgress(_tcan_onReadProgress);
_tcan.setCANDevice(_usbcandevice);
_opened = false;
Thread.Sleep(500);
}*/
}
void m_Engine_onEngineRunning(object sender, Engine.EngineStateEventArgs e)
{
if (m_RunInEmulationMode)
{
// convert value and handle result
//e.EngineLoad
//onSymbolDataReceived(this, new RealtimeDataEventArgs("P_medel", (double)e.EngineLoad));
onSymbolDataReceived(this, new RealtimeDataEventArgs("AD_EGR", (double)e.AirFuelRatio));
onSymbolDataReceived(this, new RealtimeDataEventArgs("Kyl_temp", (double)e.CoolantTemperature));
onSymbolDataReceived(this, new RealtimeDataEventArgs("Insptid_ms10", (double)e.InjectionTime));
onSymbolDataReceived(this, new RealtimeDataEventArgs("Lufttemp", (double)e.IntakeAitTemperature));
onSymbolDataReceived(this, new RealtimeDataEventArgs("Rpm", (double)e.RPM));
onSymbolDataReceived(this, new RealtimeDataEventArgs("Bil_hast", (double)e.Speed));
onSymbolDataReceived(this, new RealtimeDataEventArgs("Medeltrot", (double)e.ThrottlePosition));
onSymbolDataReceived(this, new RealtimeDataEventArgs("P_medel", (double)e.TurboPressure));
onSymbolDataReceived(this, new RealtimeDataEventArgs("Pgm_status", (double)0));
onCycleCompleted(this, EventArgs.Empty);
/*if (onSymbolDataReceived != null)
{
foreach (SymbolHelper sh in m_SymbolsToMonitor)
{
if (sh.Varname == "Rpm")
{
int symbolvalue = 900 + ran.Next(6000);
onSymbolDataReceived(this, new RealtimeDataEventArgs(sh.Varname, symbolvalue));
}
else if (sh.Varname == "P_medel")
{
double symbolvalue = (ran.NextDouble() - 0.5) * 2;
onSymbolDataReceived(this, new RealtimeDataEventArgs(sh.Varname, symbolvalue));
}
else if (sh.Varname == "AD_EGR")
{
int symbolvalue = 10 + ran.Next(10);
onSymbolDataReceived(this, new RealtimeDataEventArgs(sh.Varname, symbolvalue));
}
else if (sh.Length == 1)
{
int symbolvalue = ran.Next(255);
onSymbolDataReceived(this, new RealtimeDataEventArgs(sh.Varname, symbolvalue));
}
else if (sh.Length == 2)
{
int symbolvalue = ran.Next(65535);
onSymbolDataReceived(this, new RealtimeDataEventArgs(sh.Varname, symbolvalue));
}
}
//m_Engine.Throttleposition = 40;
onCycleCompleted(this, EventArgs.Empty);
}*/
}
}
public DateTime GetMemorySyncDate()
{
DateTime dt_sync = new DateTime(2000, 1, 1, 0, 0, 0); // testvalue
int year = 2000;
int month = 1;
int day = 1;
int hour = 0;
int minute = 0;
int second = 0;
if (m_RunInEmulationMode) return DateTime.Now;
//if (_sramDumpFile == string.Empty)
//{
byte[] result = _tcan.readRAM((ushort)0x7FC0, 1);
year = (Int32)result[0] * 256;
result = _tcan.readRAM((ushort)0x7FC1, 1);
year += (Int32)result[0];
result = _tcan.readRAM((ushort)0x7FC2, 1);
month = (Int32)result[0];
result = _tcan.readRAM((ushort)0x7FC3, 1);
day = (Int32)result[0];
result = _tcan.readRAM((ushort)0x7FC4, 1);
hour = (Int32)result[0];
result = _tcan.readRAM((ushort)0x7FC5, 1);
minute = (Int32)result[0];
result = _tcan.readRAM((ushort)0x7FC6, 1);
second = (Int32)result[0];
if (year != -1)
{
try
{
dt_sync = new DateTime(year, month, day, hour, minute, second);
}
catch (Exception E)
{
Console.WriteLine(E.Message);
foreach (byte b in result)
{
Console.Write(b.ToString("X2") + " ");
}
Console.WriteLine();
result = _tcan.readRAM((ushort)0x7FC0, 1);
year = (Int32)result[0] * 256;
result = _tcan.readRAM((ushort)0x7FC1, 1);
year += (Int32)result[0];
result = _tcan.readRAM((ushort)0x7FC2, 1);
month = (Int32)result[0];
result = _tcan.readRAM((ushort)0x7FC3, 1);
day = (Int32)result[0];
result = _tcan.readRAM((ushort)0x7FC4, 1);
hour = (Int32)result[0];
result = _tcan.readRAM((ushort)0x7FC5, 1);
minute = (Int32)result[0];
result = _tcan.readRAM((ushort)0x7FC6, 1);
second = (Int32)result[0];
foreach (byte b in result)
{
Console.Write(b.ToString("X2") + " ");
}
Console.WriteLine();
try
{
dt_sync = new DateTime(year, month, day, hour, minute, second);
}
catch (Exception E2)
{
Console.WriteLine(E2.Message);
}
}
}
/* }
else
{
byte[] result = ReadData((uint)0x7FC0, 8);
year = (Int32)result[0] * 256;
year += (Int32)result[1];
month = (Int32)result[2];
day = (Int32)result[3];
hour = (Int32)result[4];
minute = (Int32)result[5];
second = (Int32)result[6];
if (year != -1)
{
try
{
dt_sync = new DateTime(year, month, day, hour, minute, second);
}
catch (Exception E)
{
Console.WriteLine(E.Message);
}
}
}*/
Console.WriteLine("ECU: " + dt_sync.ToString("dd/MM/yyyy HH:mm:ss"));
return dt_sync;
}
public void SetMemorySyncDate(DateTime syncdt)
{
byte[] buf = new byte[7];
_prohibitRead = true;
buf[0] = Convert.ToByte((syncdt.Year >> 8) & 0x0000000000000000FF);
buf[1] = Convert.ToByte((syncdt.Year) & 0x0000000000000000FF);
buf[2] = Convert.ToByte((syncdt.Month) & 0x0000000000000000FF);
buf[3] = Convert.ToByte((syncdt.Day) & 0x0000000000000000FF);
buf[4] = Convert.ToByte((syncdt.Hour) & 0x0000000000000000FF);
buf[5] = Convert.ToByte((syncdt.Minute) & 0x0000000000000000FF);
buf[6] = Convert.ToByte((syncdt.Second) & 0x0000000000000000FF);
// if (_sramDumpFile == string.Empty)
//{
_tcan.writeRam(0x7FC0, buf);
/*}
else
{
WriteData(buf, 0x7FC0);
}*/
_prohibitRead = false;
//WriteDataNoCounterIncrease(buf, (uint)(m_fileInfo.Filelength - 0x1E0));
}
public Int64 GetMemorySyncCounter()
{
// read a specific portion of the sram memory for this
// 0x7FD0 maybe (doing for test)
Int64 countervalue = 0;
//if (_sramDumpFile == string.Empty)
//{
byte[] result = _tcan.readRAM((ushort)0x7FD0, 8);
countervalue = (Int64)result[0] * 256 * 256 * 256 * 256 * 256 * 256 * 256;
countervalue += (Int64)result[1] * 256 * 256 * 256 * 256 * 256 * 256;
countervalue += (Int64)result[2] * 256 * 256 * 256 * 256 * 256;
countervalue += (Int64)result[3] * 256 * 256 * 256 * 256;
countervalue += (Int64)result[4] * 256 * 256 * 256;
countervalue += (Int64)result[5] * 256 * 256;
countervalue += (Int64)result[6] * 256;
countervalue += (Int64)result[7];
/*}
else
{
byte[] result = ReadData((uint)0x7FD0, 8);
countervalue = (Int64)result[0] * 256 * 256 * 256 * 256 * 256 * 256 * 256;
countervalue += (Int64)result[1] * 256 * 256 * 256 * 256 * 256 * 256;
countervalue += (Int64)result[2] * 256 * 256 * 256 * 256 * 256;
countervalue += (Int64)result[3] * 256 * 256 * 256 * 256;
countervalue += (Int64)result[4] * 256 * 256 * 256;
countervalue += (Int64)result[5] * 256 * 256;
countervalue += (Int64)result[6] * 256;
countervalue += (Int64)result[7];
}*/
return countervalue;
}
public void SetMemorySyncCounter(Int64 countervalue)
{
byte[] buf = new byte[8];
_prohibitRead = true;
buf[0] = Convert.ToByte((countervalue >> 56) & 0x0000000000000000FF);
buf[1] = Convert.ToByte((countervalue >> 48) & 0x0000000000000000FF);
buf[2] = Convert.ToByte((countervalue >> 40) & 0x0000000000000000FF);
buf[3] = Convert.ToByte((countervalue >> 32) & 0x0000000000000000FF);
buf[4] = Convert.ToByte((countervalue >> 24) & 0x0000000000000000FF);
buf[5] = Convert.ToByte((countervalue >> 16) & 0x0000000000000000FF);
buf[6] = Convert.ToByte((countervalue >> 8) & 0x0000000000000000FF);
buf[7] = Convert.ToByte((countervalue) & 0x0000000000000000FF);
//if (_sramDumpFile == string.Empty)
//{
_tcan.writeRam(0x7FD0, buf);
/*}
else
{
WriteData(buf, 0x7FD0);
}*/
_prohibitRead = false;
}
void _tcan_onReadProgress(object sender, T5CANLib.ReadProgressEventArgs e)
{
// cast read progress event
if (onReadDataFromECU != null)
{
onReadDataFromECU(this, new ProgressEventArgs(e.Percentage, 0, 0));
}
}
private AppSettings m_appSettings;
public AppSettings AppSettings
{
get { return m_appSettings; }
set { m_appSettings = value; }
}
private double ConvertADCValue(int channel, float value)
{
double retval = value;
double m_HighVoltage = 5;
double m_LowVoltage = 0;
double m_HighValue = 1;
double m_LowValue = 0;
switch (channel)
{
case 0:
m_HighVoltage = m_appSettings.Adc1highvoltage;
m_LowVoltage = m_appSettings.Adc1lowvoltage;
m_LowValue = m_appSettings.Adc1lowvalue;
m_HighValue = m_appSettings.Adc1highvalue;
//Console.WriteLine("highV = " + m_HighVoltage.ToString() + " lowV = " + m_LowVoltage.ToString() + " highVal = " + m_HighValue.ToString() + " lowVal = " + m_LowValue.ToString());
break;
case 1:
m_HighVoltage = m_appSettings.Adc2highvoltage;
m_LowVoltage = m_appSettings.Adc2lowvoltage;
m_LowValue = m_appSettings.Adc2lowvalue;
m_HighValue = m_appSettings.Adc2highvalue;
break;
case 2:
m_HighVoltage = m_appSettings.Adc3highvoltage;
m_LowVoltage = m_appSettings.Adc3lowvoltage;
m_LowValue = m_appSettings.Adc3lowvalue;
m_HighValue = m_appSettings.Adc3highvalue;
break;
case 3:
m_HighVoltage = m_appSettings.Adc4highvoltage;
m_LowVoltage = m_appSettings.Adc4lowvoltage;
m_LowValue = m_appSettings.Adc4lowvalue;
m_HighValue = m_appSettings.Adc4highvalue;
break;
case 4:
m_HighVoltage = m_appSettings.Adc5highvoltage;
m_LowVoltage = m_appSettings.Adc5lowvoltage;
m_LowValue = m_appSettings.Adc5lowvalue;
m_HighValue = m_appSettings.Adc5highvalue;
break;
default:
break;
}
// convert using the known math
// convert to AFR value using wideband lambda sensor settings
// ranges 0 - 255 will be default for 0-5 volt
double voltage = value;//<GS-12042011> Combiadapter seems to generate voltage in stead of 0-255 values ((value) / 255) * (m_HighVoltage / 1000 - m_LowVoltage / 1000);
//Console.WriteLine("Voltage: " + voltage.ToString());
// now convert to AFR using user settings
if (voltage < m_LowVoltage / 1000) voltage = m_LowVoltage / 1000;
if (voltage > m_HighVoltage / 1000) voltage = m_HighVoltage / 1000;
//Console.WriteLine("Voltage (after clipping): " + voltage.ToString());
double steepness = ((m_HighValue / 1000) - (m_LowValue / 1000)) / ((m_HighVoltage / 1000) - (m_LowVoltage / 1000));
//Console.WriteLine("Steepness: " + steepness.ToString());
retval = (m_LowValue / 1000) + (steepness * (voltage - (m_LowVoltage / 1000)));
//Console.WriteLine("retval: " + retval.ToString());
return retval;
}
void m_MonitorECUTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (_stallReading) return;
m_MonitorECUTimer.Stop();
if (_opened && !_prohibitRead && !m_RunInEmulationMode)
{
if (_tcan != null)
{
try
{
foreach (SymbolHelper sh in m_SymbolsToMonitor)
{
if (_prohibitRead || _stallReading) break;
//if (_sramDumpFile == string.Empty)
//{
if (sh.Varname.StartsWith("Knock_count_cyl")) sh.Length = 2;
byte[] result = _tcan.readRAM((ushort)sh.Start_address, (uint)sh.Length);
// convert resultvalue to a usable format (doubles)
HandleResult(result, sh.Varname, sh.UserCorrectionFactor, sh.UserCorrectionOffset, sh.UseUserCorrection);
/*}
else
{
if (sh.Varname.StartsWith("Knock_count_cyl")) sh.Length = 2;
byte[] result = ReadData((uint)sh.Start_address, (uint)sh.Length);
HandleResult(result, sh.Varname);
}*/
}
if (_canusbDevice == "Multiadapter" || _canusbDevice == "CombiAdapter")
{
if (m_appSettings.Useadc1)
{
//_tcan.geta
float adc = _usbcandevice.GetADCValue(0);
//Console.WriteLine("ADC1: " + adc.ToString());
double convertedADvalue = ConvertADCValue(0, adc);
//Console.WriteLine("ADC1 converted: " + convertedADvalue.ToString());
string channelName = m_appSettings.Adc1channelname;
if (onSymbolDataReceived != null)
{
onSymbolDataReceived(this, new RealtimeDataEventArgs(channelName, convertedADvalue));
}
}
if (m_appSettings.Useadc2)
{
float adc = _usbcandevice.GetADCValue(1);
double convertedADvalue = ConvertADCValue(1, adc);
string channelName = m_appSettings.Adc2channelname;
if (onSymbolDataReceived != null)
{
onSymbolDataReceived(this, new RealtimeDataEventArgs(channelName, convertedADvalue));
}
}
if (m_appSettings.Useadc3)
{
float adc = _usbcandevice.GetADCValue(2);
double convertedADvalue = ConvertADCValue(2, adc);
string channelName = m_appSettings.Adc3channelname;
if (onSymbolDataReceived != null)
{
onSymbolDataReceived(this, new RealtimeDataEventArgs(channelName, convertedADvalue));
}
}
if (m_appSettings.Useadc4)
{
float adc = _usbcandevice.GetADCValue(3);
double convertedADvalue = ConvertADCValue(3, adc);
string channelName = m_appSettings.Adc4channelname;
if (onSymbolDataReceived != null)
{
onSymbolDataReceived(this, new RealtimeDataEventArgs(channelName, convertedADvalue));
}
}
if (m_appSettings.Useadc5)
{
float adc = _usbcandevice.GetADCValue(4);
double convertedADvalue = ConvertADCValue(4, adc);
string channelName = m_appSettings.Adc5channelname;
if (onSymbolDataReceived != null)
{
onSymbolDataReceived(this, new RealtimeDataEventArgs(channelName, convertedADvalue));
}
}
if (m_appSettings.Usethermo)
{
float temperature = _usbcandevice.GetThermoValue();
string channelName = m_appSettings.Thermochannelname;
Console.WriteLine(channelName + " = " + temperature.ToString());
if (onSymbolDataReceived != null)
{
onSymbolDataReceived(this, new RealtimeDataEventArgs(channelName, temperature));
}
}
}
// cast cycle completed event
if (onCycleCompleted != null)
{
onCycleCompleted(this, EventArgs.Empty);
}
}
catch (Exception E)
{
Console.WriteLine("m_MonitorECUTimer_Elapsed: "+ E.Message);
}
}
}
m_MonitorECUTimer.Start();
}
private byte[] ReadData(uint offset, uint length)
{
if (File.Exists(_sramDumpFile))
{
return readdatafromfile(_sramDumpFile, (int)offset, (int)length);
}
byte[] b = new byte[1];
b.SetValue((byte)0x00, 0);
return b;
}
public bool WriteData(byte[] data, uint offset)
{
if (File.Exists(_sramDumpFile))
{
for (int i = 0; i < data.Length; i++)
{
writebyteinfile(_sramDumpFile, (int)offset + i, (byte)data.GetValue(i));
}
return true;
}
return false;
}
public void writebyteinfile(string filename, int address, byte value)
{
if (address <= 0) return;
FileStream fsi1 = File.OpenWrite(filename);
while (address > fsi1.Length) address -= (int)fsi1.Length;
BinaryWriter br1 = new BinaryWriter(fsi1);
fsi1.Position = address;
br1.Write(value);
fsi1.Flush();
br1.Close();
fsi1.Close();
fsi1.Dispose();
}
private byte[] readdatafromfile(string filename, int address, int length)
{
byte[] retval = new byte[length];
FileStream fsi1 = File.OpenRead(filename);
while (address > fsi1.Length) address -= (int)fsi1.Length;
BinaryReader br1 = new BinaryReader(fsi1);
fsi1.Position = address;
string temp = string.Empty;
for (int i = 0; i < length; i++)
{
retval.SetValue(br1.ReadByte(), i);
}
fsi1.Flush();
br1.Close();
fsi1.Close();
fsi1.Dispose();
return retval;
}
private void HandleResult(byte[] ECUData, string symbolname, double _userCorrectionFactor, double _userCorrectionOffset, bool UseUserCorrection)
{
// let a subclass convert the data to useable stuff
double symbolvalue = _symConverter.ConvertSymbol(symbolname, ECUData, _mapSensorType, _userCorrectionFactor, _userCorrectionOffset, UseUserCorrection);
//Console.WriteLine("Handling: " + symbolname + " " + symbolvalue.ToString());
if (symbolname == "Rpm")
{
if (symbolvalue > 0) _engineRunning = true;
else _engineRunning = false;
}
// cast a delegate to toplevel
if (onSymbolDataReceived != null)
{
//<GS-09082010>
/*if (m_appSettings.DebugMode)
{
if (symbolname == "Rpm") symbolvalue = 2000;
else if (symbolname == "Kyl_temp") symbolvalue = 80;
else if (symbolname == "AD_EGR") symbolvalue = 17;
else if (symbolname == "P_Medel") symbolvalue = 1.2F;
else if (symbolname == "P_medel") symbolvalue = 1.2F;
else if (symbolname == "P_Manifold10") symbolvalue = 1.2F;
}*/
onSymbolDataReceived(this, new RealtimeDataEventArgs(symbolname, symbolvalue));
//Console.WriteLine(symbolname + " " + symbolvalue.ToString());
}
}
private string _canusbDevice = "Lawicel";
public string CanusbDevice
{
get { return _canusbDevice; }
set { _canusbDevice = value; }
}
public void OpenECUConnection()
{
if (m_RunInEmulationMode)
{
m_Engine.InitializeEngine();
m_Engine.StartEngine();
_opened = true;
}
if (!_opened)
{
_opened = true;
//if (_sramDumpFile == string.Empty)
//{
if (_tcan == null)
{
_tcan = new T5CANLib.T5CAN();
if (_canusbDevice == "Multiadapter" || _canusbDevice == "CombiAdapter")
{
_usbcandevice = new T5CANLib.CAN.LPCCANDevice_T5();
}
else if (_canusbDevice == "DIY")
{
_usbcandevice = new T5CANLib.CAN.MctCanDevice();
}
else if (_canusbDevice == "Just4Trionic")
{
_usbcandevice = new T5CANLib.CAN.Just4TrionicDevice();
}
else // default = Lawicel
{
_usbcandevice = new T5CANLib.CAN.CANUSBDevice();
}
_tcan.onWriteProgress += new T5CANLib.T5CAN.WriteProgress(OnWriteProgress);
_tcan.onCanInfo += new T5CANLib.T5CAN.CanInfo(_tcan_onCanInfo);
_tcan.onReadProgress +=new T5CANLib.T5CAN.ReadProgress(_tcan_onReadProgress);
_tcan.setCANDevice(_usbcandevice);
}
if (!_tcan.openDevice(out _swversion))
{
_opened = false;
}
/*if (_opened) // if can adapter opened successfully, try to contact the ECU
{
byte[] testbyte = _tcan.readRAM(0x1000, 2);
if (testbyte.Length != 2) _opened = false;
Console.WriteLine(testbyte.Length.ToString() + " as result");
}*/
Console.WriteLine("OpenECUConnection: " + _swversion);
//}
}
_stallReading = false;
}
void _tcan_onCanInfo(object sender, T5CANLib.CanInfoEventArgs e)
{
if (onCanBusInfo != null)
{
onCanBusInfo(this, new CanInfoEventArgs(e.Info));
}
}
public string GetSoftwareVersion()
{
string swversion = string.Empty;
if (m_RunInEmulationMode) return "DEBUG.MODE";
if (_opened)
{
//if (_sramDumpFile == string.Empty)
//{
if (_isT52)
{
swversion = _tcan.getSWVersionT52(false);
}
else
{
swversion = _tcan.getSWVersion(false);
}
/*}
else
{
swversion = "DUMMY.SRAM";
}*/
}
return swversion;
}
public void CloseECUConnection(bool forceClose)
{
if (m_RunInEmulationMode)
{
m_Engine.StopEngine();
}
if (_opened && forceClose)
{
_opened = false;
//if (_sramDumpFile == string.Empty)
{
if(_tcan != null) _tcan.Cleanup();
}
} // <GS-22032010> never close the connection
else if (_opened)
{
// should we slow down on the connection here?
//explore options <GS-22032010>
_stallReading = true;
}
}
public bool IsConnectedECUT52()
{
bool retval = false;
if (_opened)
{
retval = _tcan.isT52ECU();
}
return retval;
}
public DataTable GetSymbolTable()
{
DataTable _symtable = new DataTable();
_symtable.Columns.Add("Symbol");
_symtable.Columns.Add("Address", Type.GetType("System.Int32"));
_symtable.Columns.Add("Length", Type.GetType("System.Int32"));
//if (_sramDumpFile != string.Empty) return _symtable;
if (_opened)
{
_prohibitRead = true;
Thread.Sleep(100);
if (_swversion == string.Empty)
{
if (m_RunInEmulationMode) _swversion = "DEBUG.MODE";
else _swversion = _tcan.getSWVersion(false);
}
string symbols = string.Empty;
if (!m_RunInEmulationMode)
{
if (!File.Exists(System.Windows.Forms.Application.StartupPath + "\\" + _swversion + ".symbollist"))
{
symbols = string.Join(Environment.NewLine, _tcan.getSymbolTable().Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries));
try
{
System.IO.File.WriteAllText(System.Windows.Forms.Application.StartupPath + "\\" + _swversion + ".symbollist", symbols);
}
catch
{
System.IO.File.WriteAllText(System.Windows.Forms.Application.StartupPath + "\\" + "bad_name" + ".symbollist", symbols);
}
}
else
{
symbols = File.ReadAllText(System.Windows.Forms.Application.StartupPath + "\\" + _swversion + ".symbollist");
}
foreach (string symbol in symbols.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
{
if (!symbol.StartsWith(">") && symbol != "END")
{
try
{
ushort address = ushort.Parse(symbol.Substring(0, 4), NumberStyles.AllowHexSpecifier);
uint length = uint.Parse(symbol.Substring(4, 4), NumberStyles.AllowHexSpecifier);
string symname = symbol.Substring(8);
_symtable.Rows.Add(symname, Convert.ToInt32(address), Convert.ToInt32(length));
}
catch { }
}
}
}
_prohibitRead = false;
}
return _symtable;
}
void OnWriteProgress(object sender, T5CANLib.WriteProgressEventArgs e)
{
if (onWriteDataToECU != null)
{
onWriteDataToECU(this, new ProgressEventArgs(e.Percentage, 0, 0));
}
}
public void ProgramFlash(string flashfile, T5CANLib.ECUType type)
{
_prohibitRead = true;
Thread.Sleep(100);
_tcan.UpgradeECU(flashfile, T5CANLib.FileType.BinaryFile, type);
_prohibitRead = false;
}
public void EnableLogging(string path2log)
{
if (_usbcandevice != null)
{
_usbcandevice.EnableLogging(path2log);
}
}
internal void DisableLogging()
{
if (_usbcandevice != null)
{
_usbcandevice.DisableLogging();
}
}
public class RealtimeDataEventArgs : System.EventArgs
{
private string _symbol;
public string Symbol
{
get { return _symbol; }
set { _symbol = value; }
}
private double _value;
public double Value
{
get { return _value; }
set { _value = value; }
}
public RealtimeDataEventArgs(string symbol, double value)
{
this._symbol = symbol;
this._value = value;
}
}
public class CanInfoEventArgs : System.EventArgs
{
private string _info = string.Empty;
public string Info
{
get { return _info; }
set { _info = value; }
}
public CanInfoEventArgs(string info)
{
this._info = info;
}
}
public class ProgressEventArgs : System.EventArgs
{
private int _percentage;
public int Percentage
{
get { return _percentage; }
set { _percentage = value; }
}
private int _byteswritten;
public int Byteswritten
{
get { return _byteswritten; }
set { _byteswritten = value; }
}
private int _bytestowrite;
public int Bytestowrite
{
get { return _bytestowrite; }
set { _bytestowrite = value; }
}
public ProgressEventArgs(int percentage, int byteswritten, int bytestowrite)
{
this._bytestowrite = bytestowrite;
this._byteswritten = byteswritten;
this._percentage = percentage;
}
}
internal void RemoveAllSymbolsFromWatchlist()
{
_stallReading = true;
m_SymbolsToMonitor.Clear();
bool found = true;
while (found)
{
found = false;
foreach (SymbolHelper sh in m_SymbolsToMonitor)
{
if (!sh.IsSystemSymbol)
{
m_SymbolsToMonitor.Remove(sh);
found = true;
break;
}
}
}
_stallReading = false;
}
internal byte[] ReadSymbolData(string symbolname, uint address, uint length)
{
byte[] retval = new byte[1];
retval.SetValue((byte)0, 0);
if (_opened && _tcan != null) //<GS-17032011>
{
_prohibitRead = true;
//if (_sramDumpFile == string.Empty)
//{
retval = _tcan.readRAM((ushort)address, length); //<GS-17032011> Should be the only line here
//}
//else
//{
//retval = ReadData(address, length);
//}
_prohibitRead = false;
}
return retval;
}
internal byte[] ReadSymbolDataNoProhibitRead(string symbolname, uint address, uint length)
{
byte[] retval = new byte[1];
retval.SetValue((byte)0, 0);
if (_opened && _tcan != null) //<GS-17032011>
{
//if (_sramDumpFile == string.Empty)
//{
retval = _tcan.readRAM((ushort)address, length);//<GS-17032011> Should be the only line here
//}
//else
//{
//retval = ReadData(address, length);
//}
}
return retval;
}
private bool MoreThanHalfDiffers(byte[] buf1, byte[] buf2)
{
int diffcount = 0;
if (buf1.Length != buf2.Length) return true;
else
{
for (int _bytetel = 0; _bytetel < buf1.Length; _bytetel++)
{
if (buf1[_bytetel] != buf2[_bytetel])
{
diffcount++;
}
}
}
if ((diffcount * 2) > buf1.Length) return true;
return false;
}
private void ConvertRealtimeValuesForUseInMapviewers()
{
// float requested_boost = GetBoostRequest(engine_status.Throttle_position, engine_status.Rpm, out tpsindex, out rpmindex);
// UpdateBoostRequestmap(requested_boost, tpsindex, rpmindex);
}
internal void WriteSymbolDataForced(int address, int length, byte[] data)
{
if (_opened && _tcan != null) //<GS-17032011>
{
// hold reading until writing is done!
_prohibitRead = true;
//if (_sramDumpFile == string.Empty)
//{
_tcan.writeRamForced((ushort)address, data); //<GS-17032011> Should be the only line here
Thread.Sleep(20); //<GS-17032011> Should be the only line here
//}
//else
//{
//WriteData(data, (uint)address);
//}
_prohibitRead = false;
}
}
internal void WriteSymbolData(int address, int length, byte[] data)
{
if (_opened && _tcan != null) //<GS-17032011>
{
// hold reading until writing is done!
_prohibitRead = true;
//if (_sramDumpFile == string.Empty)
//{
_tcan.writeRam((ushort)address, data); //<GS-17032011> Should be the only line here
Thread.Sleep(20); //<GS-17032011> Should be the only line here
//}
//else
//{
// WriteData(data, (uint)address);
//}
//Thread.Sleep(20);
//SetMemorySyncCounter(GetMemorySyncCounter() + 1);
SetMemorySyncDate(DateTime.Now);
Thread.Sleep(20);
_prohibitRead = false;
}
}
internal void ReadFlash(string filename)
{
_prohibitRead = true;
Thread.Sleep(100);
_tcan.DumpECU(filename);
_prohibitRead = false;
}
}
}
| |
#if UNITY_EDITOR
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;
using Object = UnityEngine.Object;
namespace PrimitiveEngine.Unity
{
internal class ReorderableListOfSubassets : ReorderableListOfStructures
{
private readonly SerializedObjectCache m_SerializedObjectCache =
new SerializedObjectCache();
private readonly Type[] m_SubassetTypes;
public bool hasSingleSubassetType
{
get { return m_SubassetTypes.Length == 1; }
}
public bool hasMultipleSubassetTypes
{
get { return m_SubassetTypes.Length > 1; }
}
private readonly bool m_UseFullSubassetTypeNames;
public override bool showElementHeader
{
get
{
return base.showElementHeader ||
hasMultipleSubassetTypes;
}
}
//----------------------------------------------------------------------
public ReorderableListOfSubassets(
ReorderableListAttribute attribute,
SerializedProperty property,
Type listType,
Type elementType,
Type[] subassetTypes)
: base(attribute, property, listType, elementType)
{
m_SubassetTypes = subassetTypes;
m_UseFullSubassetTypeNames = SubassetTypeNamesAreAmbiguous();
onCanAddCallback = OnCanAddCallback;
if (hasSingleSubassetType)
onAddCallback = OnAddCallback;
else if (hasMultipleSubassetTypes)
onAddDropdownCallback = OnAddDropdownCallback;
}
//----------------------------------------------------------------------
public override void DoGUI(Rect position)
{
base.DoGUI(position);
EvictObsoleteSerializedObjectsFromCache();
}
//----------------------------------------------------------------------
protected override float GetElementHeight(
SerializedProperty element,
int elementIndex)
{
var subasset = element.objectReferenceValue;
if (subasset == null)
return EditorGUIUtility.singleLineHeight;
var serializedObject = GetSerializedObjectFromCache(subasset);
var properties = serializedObject.EnumerateChildProperties();
return base.GetElementHeight(properties);
}
//----------------------------------------------------------------------
protected override void DrawElement(
Rect position,
SerializedProperty element,
int elementIndex,
bool isActive)
{
var subasset = element.objectReferenceValue;
if (subasset == null)
return;
var serializedObject = GetSerializedObjectFromCache(subasset);
serializedObject.Update();
var properties = serializedObject.EnumerateChildProperties();
base.DrawElement(position, properties, elementIndex, isActive);
serializedObject.ApplyModifiedProperties();
}
//----------------------------------------------------------------------
protected override void PopulateElementContextMenu(
GenericMenu menu,
int elementIndex)
{
foreach (var mutableElementType in m_SubassetTypes)
{
var elementType = mutableElementType;
var elementTypeName =
m_UseFullSubassetTypeNames
? elementType.FullName
: elementType.Name;
var insertAbove = "Insert Above/" + elementTypeName;
var insertBelow = "Insert Below/" + elementTypeName;
menu.AddItem(new GUIContent(insertAbove), false, () =>
OnNextGUIFrame(() => InsertSubasset(elementType, elementIndex)));
menu.AddItem(new GUIContent(insertBelow), false, () =>
OnNextGUIFrame(() => InsertSubasset(elementType, elementIndex + 1)));
}
menu.AddSeparator("");
menu.AddItem(new GUIContent("Remove"), false, () =>
OnNextGUIFrame(() => DeleteElement(elementIndex)));
}
//----------------------------------------------------------------------
private void DrawElementHeader(
Rect position,
Object subasset,
bool isActive)
{
var subassetType = subasset != null ? subasset.GetType() : typeof(Object);
position.height = headerHeight;
var titleContent = m_TitleContent;
titleContent.text =
ObjectNames
.NicifyVariableName(subasset.name);
titleContent.image =
EditorGUIUtility
.ObjectContent(subasset, subassetType)
.image;
var titleStyle = EditorStyles.boldLabel;
var titleWidth = titleStyle.CalcSize(titleContent).x;
var scriptRect = position;
scriptRect.yMin -= 1;
scriptRect.yMax -= 1;
scriptRect.width = titleWidth + 16;
using (ColorAlphaScope(0))
{
EditorGUI.BeginDisabledGroup(disabled: true);
EditorGUI.ObjectField(
scriptRect,
subasset,
subassetType,
allowSceneObjects: false);
EditorGUI.EndDisabledGroup();
}
if (IsRepaint())
{
var fillRect = position;
fillRect.xMin -= draggable ? 18 : 4;
fillRect.xMax += 4;
fillRect.y -= 2;
var fillStyle = HeaderBackgroundStyle;
using (ColorAlphaScope(0.5f))
{
fillStyle.Draw(fillRect, false, false, false, false);
}
var titleRect = position;
titleRect.xMin -= 4;
titleRect.yMin -= 2;
titleRect.yMax += 1;
titleRect.width = titleWidth;
titleStyle.Draw(titleRect, titleContent, false, false, false, false);
}
}
//----------------------------------------------------------------------
private bool OnCanAddCallback(ReorderableList list)
{
return m_SubassetTypes.Length > 0;
}
private void OnAddCallback(ReorderableList list)
{
serializedProperty.isExpanded = true;
AddSubasset(m_SubassetTypes[0]);
}
private void OnAddDropdownCallback(Rect position, ReorderableList list)
{
serializedProperty.isExpanded = true;
var menu = new GenericMenu();
foreach (var mutableElementType in m_SubassetTypes)
{
var elementType = mutableElementType;
var elementTypeName =
m_UseFullSubassetTypeNames
? elementType.FullName
: elementType.Name;
var content = new GUIContent();
content.text = ObjectNames.NicifyVariableName(elementTypeName);
menu.AddItem(
content,
on: false,
func: () => AddSubasset(elementType)
);
}
position.x -= 2;
position.y += 1;
menu.DropDown(position);
}
//----------------------------------------------------------------------
private void AddSubasset(Type subassetType)
{
var array = serializedProperty;
var elementIndex = array.arraySize;
InsertSubasset(subassetType, elementIndex);
}
private void InsertSubasset(Type subassetType, int elementIndex)
{
var array = serializedProperty;
array.InsertArrayElementAtIndex(elementIndex);
index = elementIndex;
GUI.changed = true;
var subasset = default(Object);
if (typeof(ScriptableObject).IsAssignableFrom(subassetType))
{
subasset = ScriptableObject.CreateInstance(subassetType);
}
else if (typeof(Object).IsAssignableFrom(subassetType))
{
subasset = (Object)Activator.CreateInstance(subassetType);
}
if (subasset == null)
{
Debug.LogErrorFormat(
"Failed to create subasset of type {0}",
subassetType.FullName
);
return;
}
subasset.name = subassetType.Name;
var serializedObject = array.serializedObject;
serializedObject.targetObject.AddSubasset(subasset);
var element = array.GetArrayElementAtIndex(elementIndex);
var oldSubassets = element.FindReferencedSubassets();
element.objectReferenceValue = subasset;
if (oldSubassets.Any())
{
serializedObject.ApplyModifiedPropertiesWithoutUndo();
serializedObject.DestroyUnreferencedSubassets(oldSubassets);
}
else
{
serializedObject.ApplyModifiedProperties();
}
}
protected override void DeleteElement(int elementIndex)
{
if (elementIndex < 0)
return;
var array = serializedProperty;
if (elementIndex < array.arraySize)
{
var serializedObject = array.serializedObject;
var element = array.GetArrayElementAtIndex(elementIndex);
var oldSubassets = element.FindReferencedSubassets();
element.objectReferenceValue = null;
array.DeleteArrayElementAtIndex(elementIndex);
if (oldSubassets.Any())
{
serializedObject.ApplyModifiedPropertiesWithoutUndo();
serializedObject.DestroyUnreferencedSubassets(oldSubassets);
}
else
{
serializedObject.ApplyModifiedProperties();
}
var length = array.arraySize;
if (index > length - 1)
index = length - 1;
}
}
//----------------------------------------------------------------------
private bool SubassetTypeNamesAreAmbiguous()
{
var elementTypeNames = m_SubassetTypes.Select(t => t.Name);
var elementTypeNamesAreAmbiguous =
elementTypeNames.Count() >
elementTypeNames.Distinct().Count();
return elementTypeNamesAreAmbiguous;
}
//----------------------------------------------------------------------
class SerializedObjectCache : Dictionary<Object, SerializedObject> { }
private SerializedObject GetSerializedObjectFromCache(Object @object)
{
var cache = m_SerializedObjectCache;
var serializedObject = default(SerializedObject);
if (!cache.TryGetValue(@object, out serializedObject))
{
serializedObject = new SerializedObject(@object);
cache.Add(@object, serializedObject);
}
return serializedObject;
}
private void EvictObsoleteSerializedObjectsFromCache()
{
var cache = m_SerializedObjectCache;
var destroyedObjects = cache.Keys.Where(key => key == null);
if (destroyedObjects.Any())
{
foreach (var @object in destroyedObjects.ToArray())
{
cache.Remove(@object);
}
}
}
}
}
#endif // UNITY_EDITOR
| |
// 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.Diagnostics.CodeAnalysis;
using System.Dynamic.Utils;
namespace System.Linq.Expressions
{
/// <summary>
/// Emits or clears a sequence point for debug information.
///
/// This allows the debugger to highlight the correct source code when
/// debugging.
/// </summary>
[DebuggerTypeProxy(typeof(Expression.DebugInfoExpressionProxy))]
public class DebugInfoExpression : Expression
{
private readonly SymbolDocumentInfo _document;
internal DebugInfoExpression(SymbolDocumentInfo document)
{
_document = document;
}
/// <summary>
/// Gets the static type of the expression that this <see cref="Expression" /> represents. (Inherited from <see cref="Expression"/>.)
/// </summary>
/// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
public sealed override Type Type
{
get { return typeof(void); }
}
/// <summary>
/// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.)
/// </summary>
/// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns>
public sealed override ExpressionType NodeType
{
get { return ExpressionType.DebugInfo; }
}
/// <summary>
/// Gets the start line of this <see cref="DebugInfoExpression" />.
/// </summary>
[ExcludeFromCodeCoverage] // Unreachable
public virtual int StartLine
{
get { throw ContractUtils.Unreachable; }
}
/// <summary>
/// Gets the start column of this <see cref="DebugInfoExpression" />.
/// </summary>
[ExcludeFromCodeCoverage] // Unreachable
public virtual int StartColumn
{
get { throw ContractUtils.Unreachable; }
}
/// <summary>
/// Gets the end line of this <see cref="DebugInfoExpression" />.
/// </summary>
[ExcludeFromCodeCoverage] // Unreachable
public virtual int EndLine
{
get { throw ContractUtils.Unreachable; }
}
/// <summary>
/// Gets the end column of this <see cref="DebugInfoExpression" />.
/// </summary>
[ExcludeFromCodeCoverage] // Unreachable
public virtual int EndColumn
{
get { throw ContractUtils.Unreachable; }
}
/// <summary>
/// Gets the <see cref="SymbolDocumentInfo"/> that represents the source file.
/// </summary>
public SymbolDocumentInfo Document
{
get { return _document; }
}
/// <summary>
/// Gets the value to indicate if the <see cref="DebugInfoExpression"/> is for clearing a sequence point.
/// </summary>
[ExcludeFromCodeCoverage] // Unreachable
public virtual bool IsClear
{
get { throw ContractUtils.Unreachable; }
}
/// <summary>
/// Dispatches to the specific visit method for this node type.
/// </summary>
protected internal override Expression Accept(ExpressionVisitor visitor)
{
return visitor.VisitDebugInfo(this);
}
}
#region Specialized subclasses
internal sealed class SpanDebugInfoExpression : DebugInfoExpression
{
private readonly int _startLine, _startColumn, _endLine, _endColumn;
internal SpanDebugInfoExpression(SymbolDocumentInfo document, int startLine, int startColumn, int endLine, int endColumn)
: base(document)
{
_startLine = startLine;
_startColumn = startColumn;
_endLine = endLine;
_endColumn = endColumn;
}
public override int StartLine
{
get
{
return _startLine;
}
}
public override int StartColumn
{
get
{
return _startColumn;
}
}
public override int EndLine
{
get
{
return _endLine;
}
}
public override int EndColumn
{
get
{
return _endColumn;
}
}
public override bool IsClear
{
get
{
return false;
}
}
protected internal override Expression Accept(ExpressionVisitor visitor)
{
return visitor.VisitDebugInfo(this);
}
}
internal sealed class ClearDebugInfoExpression : DebugInfoExpression
{
internal ClearDebugInfoExpression(SymbolDocumentInfo document)
: base(document)
{
}
public override bool IsClear
{
get
{
return true;
}
}
public override int StartLine
{
get
{
return 0xfeefee;
}
}
public override int StartColumn
{
get
{
return 0;
}
}
public override int EndLine
{
get
{
return 0xfeefee;
}
}
public override int EndColumn
{
get
{
return 0;
}
}
}
#endregion
public partial class Expression
{
/// <summary>
/// Creates a <see cref="DebugInfoExpression"/> with the specified span.
/// </summary>
/// <param name="document">The <see cref="SymbolDocumentInfo"/> that represents the source file.</param>
/// <param name="startLine">The start line of this <see cref="DebugInfoExpression" />. Must be greater than 0.</param>
/// <param name="startColumn">The start column of this <see cref="DebugInfoExpression" />. Must be greater than 0.</param>
/// <param name="endLine">The end line of this <see cref="DebugInfoExpression" />. Must be greater or equal than the start line.</param>
/// <param name="endColumn">The end column of this <see cref="DebugInfoExpression" />. If the end line is the same as the start line, it must be greater or equal than the start column. In any case, must be greater than 0.</param>
/// <returns>An instance of <see cref="DebugInfoExpression"/>.</returns>
public static DebugInfoExpression DebugInfo(SymbolDocumentInfo document, int startLine, int startColumn, int endLine, int endColumn)
{
ContractUtils.RequiresNotNull(document, nameof(document));
if (startLine == 0xfeefee && startColumn == 0 && endLine == 0xfeefee && endColumn == 0)
{
return new ClearDebugInfoExpression(document);
}
ValidateSpan(startLine, startColumn, endLine, endColumn);
return new SpanDebugInfoExpression(document, startLine, startColumn, endLine, endColumn);
}
/// <summary>
/// Creates a <see cref="DebugInfoExpression"/> for clearing a sequence point.
/// </summary>
/// <param name="document">The <see cref="SymbolDocumentInfo"/> that represents the source file.</param>
/// <returns>An instance of <see cref="DebugInfoExpression"/> for clearning a sequence point.</returns>
public static DebugInfoExpression ClearDebugInfo(SymbolDocumentInfo document)
{
ContractUtils.RequiresNotNull(document, nameof(document));
return new ClearDebugInfoExpression(document);
}
private static void ValidateSpan(int startLine, int startColumn, int endLine, int endColumn)
{
if (startLine < 1)
{
throw Error.OutOfRange("startLine", 1);
}
if (startColumn < 1)
{
throw Error.OutOfRange("startColumn", 1);
}
if (endLine < 1)
{
throw Error.OutOfRange("endLine", 1);
}
if (endColumn < 1)
{
throw Error.OutOfRange("endColumn", 1);
}
if (startLine > endLine)
{
throw Error.StartEndMustBeOrdered();
}
if (startLine == endLine && startColumn > endColumn)
{
throw Error.StartEndMustBeOrdered();
}
}
}
}
| |
using System;
using System.Configuration;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;
using EtoTest.IO;
using EtoTest.Model;
using EtoTest.Serialisation;
namespace EtoTest.Encrypt
{
public static class AesBasedFileEncryption
{
private static void SetupDataName(string dataFileName)
{
if (!DoesSaltExist(dataFileName) && !DoesIVExist(dataFileName))
{
GenerateAndStoreSalt(dataFileName);
GenerateAndStoreIv(dataFileName);
}
}
private static DisposableAes CreateCrypto(SecureStringOrArray password, String dataFileName)
{
String ivPath = GetIVPath(dataFileName);
return new DisposableAes(GenerateKey(password, dataFileName), File.ReadAllBytes(ivPath));
}
public static void BinarySerializeObjectEncrypted(String dataFileName, SecureStringOrArray password, object objectValue)
{
SetupDataName(dataFileName);
String dataFilePath = GetDataFilePath(dataFileName);
String tempDataFilePath = SwapExtension(dataFilePath, ".tmp");
using (var stream = File.Open(tempDataFilePath, FileMode.Create))
using (DisposableAes aes = CreateCrypto(password, dataFileName))
using (CryptoStream cryptoStream = new CryptoStream(
stream,
aes.EncryptorTransform,
CryptoStreamMode.Write))
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(cryptoStream, objectValue);
}
SafeFileMove(dataFilePath, tempDataFilePath);
}
public static void WcfBinaryCompressedSerializeEncrypted<T1>(String dataFileName, SecureStringOrArray password, T1 objectValue)
{
SetupDataName(dataFileName);
String dataFilePath = GetDataFilePath(dataFileName);
String tempDataFilePath = SwapExtension(dataFilePath, ".tmp");
using (var stream = File.Open(tempDataFilePath, FileMode.Create))
using (DisposableAes aes = CreateCrypto(password, dataFileName))
using (CryptoStream cryptoStream = new CryptoStream(
stream,
aes.EncryptorTransform,
CryptoStreamMode.Write))
{
ServiceIo.WcfBinaryCompressedSerialize(cryptoStream, objectValue);
}
SafeFileMove(dataFilePath, tempDataFilePath);
}
public static void SafeFileMove(String dataFilePath, String tempDataFilePath)
{
if (File.Exists(dataFilePath))
{
string oldDataFilePath = SwapExtension(dataFilePath, ".old");
DeleteIfExists(oldDataFilePath);
File.Move(dataFilePath, oldDataFilePath);
File.Move(tempDataFilePath, dataFilePath);
File.Delete(oldDataFilePath);
}
else
{
File.Move(tempDataFilePath, dataFilePath);
}
}
public static string SwapExtension(string dataFilePath, string newExtension)
{
if (Path.HasExtension(dataFilePath))
{
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(dataFilePath);
var directoryName = Path.GetDirectoryName(dataFilePath);
var newFileName = Path.Combine(directoryName, $"{fileNameWithoutExtension}{newExtension}");
return newFileName;
}
else
{
string newFileName = $"{dataFilePath}{newExtension}";
return newFileName;
}
}
private static void DeleteIfExists(String oldDataFilePath)
{
if (File.Exists(oldDataFilePath))
{
File.Delete(oldDataFilePath);
}
}
public static T1 BinaryDeserializeEncryptedObject<T1>(String dataFileName, SecureStringOrArray password)
{
ConvertToDCStyle(dataFileName, password);
String dataFilePath = GetDataFilePath(dataFileName);
using (var stream = File.Open(dataFilePath, FileMode.Open))
using (DisposableAes aes = CreateCrypto(password, dataFileName))
using (CryptoStream cryptoStream = new CryptoStream(
stream,
aes.DecryptorTransform,
CryptoStreamMode.Read))
{
BinaryFormatter formatter = new BinaryFormatter();
var result = (T1)formatter.Deserialize(cryptoStream);
return result;
}
}
public static T1 WcfBinaryCompressedDeserializeEncrypted<T1>(String dataFileName, SecureStringOrArray password)
{
var dataFilePath = GetDataFilePath(dataFileName);
using (var stream = File.Open(dataFilePath, FileMode.Open))
using (var aes = CreateCrypto(password, dataFileName))
using (var cryptoStream = new CryptoStream(
stream,
aes.DecryptorTransform,
CryptoStreamMode.Read))
{
var result = ServiceIo.WcfBinaryCompressedDeserialize<T1>(cryptoStream);
return result;
}
}
private static void ConvertToDCStyle(String dataFileName, SecureStringOrArray password)
{
var oldStyleSet = BinaryDeserializeEncryptedObject<CredentialSet>(dataFileName, password);
WcfBinaryCompressedSerializeEncrypted(dataFileName + "new", password, oldStyleSet);
//MtomSerializeEncryptedObject<M.UI.Model.NoString.CredentialSet>(newDataFileName, password, newCredentials);
//var newSet = MtomDeserializeEncryptedObject<M.UI.Model.NoString.CredentialSet>(newDataFileName, password);
}
private static byte[] GenerateKey(SecureStringOrArray password, String saltName)
{
var filePath = GetSaltFilePath(saltName);
return GenerateKey(password, File.ReadAllBytes(filePath));
}
public static byte[] GenerateKey(SecureStringOrArray password, byte[] salt)
{
var passwordBytes2 = password.ByteArray;
try
{
//the recommended number of iterations is 1000, lets just chose something random that is near to that.
var foo = new Rfc2898DeriveBytes(passwordBytes2, salt, 1076);
var finalBytes = foo.GetBytes(32);
return finalBytes;
}
finally
{
password.ZeroBytesIfRecreatable(passwordBytes2);
}
}
private static byte[] GenerateAndStoreIv(String ivName)
{
return StoreRandomData(ivName, GetIVPath(ivName), 16);
}
private static byte[] GenerateAndStoreSalt(String saltName)
{
return StoreRandomData(saltName, GetSaltFilePath(saltName), 8);
}
private static byte[] StoreRandomData(String dataName, String dataPath, int length)
{
var array = GenerateRandomData(length);
if (File.Exists(dataPath))
{
throw new ApplicationException("RandomData already exists: " + dataName);
}
using (var stream = File.OpenWrite(dataPath))
{
stream.Write(array, 0, array.Length);
}
return array;
}
private static byte[] GenerateRandomData(int length)
{
var randomNumberGenerator = new RNGCryptoServiceProvider();
return randomNumberGenerator.GenerateRandomData(length);
}
/// <summary>
/// Generate IV - store this within profile and backup somewhere it wont get lost
/// </summary>
private static string GetIVPath(String ivName)
{
return GetSpecialPath(Environment.SpecialFolder.LocalApplicationData, "{0}.iv", ivName);
}
public static string GetVersionFilePath(String ivName)
{
return GetSpecialPath(Environment.SpecialFolder.LocalApplicationData, "{0}.ver", ivName);
}
private static string GetDataFilePath(String dataFileName)
{
return GetSpecialPath(Environment.SpecialFolder.MyDocuments, "{0}.enc", dataFileName);
}
private static string GetSaltFilePath(String saltName)
{
return GetSpecialPath(Environment.SpecialFolder.LocalApplicationData, "{0}.salt", saltName);
}
private static bool DoesSaltExist(string saltName)
{
return File.Exists(GetSaltFilePath(saltName));
}
private static bool DoesIVExist(string saltName)
{
return File.Exists(GetIVPath(saltName));
}
private static bool DoesDataFileExist(string saltName)
{
return File.Exists(GetDataFilePath(saltName));
}
private static string GetSpecialPath(Environment.SpecialFolder specialFolder, string fileNameFormat, string ivName)
{
var userSpecificHiddenDataFolderPath = Environment.GetFolderPath(specialFolder);
var dataFilePath = Path.Combine(userSpecificHiddenDataFolderPath, string.Format(fileNameFormat, ivName));
var alternatePathConfig = ConfigurationManager.AppSettings["AlternatePath"];
if (alternatePathConfig != null)
{
var alternatePath = ExtensionMethods.EnsureSlashSuffix(alternatePathConfig);
var alternateDataFilePath = Path.Combine(alternatePath, String.Format(fileNameFormat, ivName));
if (File.Exists(Path.Combine(alternatePath, "63643784855")) && File.Exists(dataFilePath))
{
File.Copy(dataFilePath, alternateDataFilePath, true);
}
if (Directory.Exists(alternatePath) && !File.Exists(dataFilePath))
{
dataFilePath = alternateDataFilePath;
}
}
return dataFilePath;
}
}
}
| |
// This file was contributed to the RDL Project under the MIT License. It was
// modified as part of merging into the RDL Project.
/*
The MIT License
Copyright (c) 2006 Christian Cunlif and Lionel Cuir of Aulofee
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.Specialized;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using RdlEngine.Resources;
namespace fyiReporting.RDL
{
/// <summary>
/// represents an external file referenced in our parent HTML at the target URL
/// </summary>
class MhtWebFile
{
#region Fields
MhtBuilder _Builder;
string _ContentLocation;
string _ContentType;
byte[] _DownloadedBytes;
Exception _DownloadException = null;
string _DownloadExtension = "";
string _DownloadFilename = "";
string _DownloadFolder = "";
NameValueCollection _ExternalFileCollection;
bool _IsBinary;
Encoding _TextEncoding;
string _Url;
string _UrlFolder;
string _UrlRoot;
string _UrlUnmodified;
bool _UseHtmlFilename = false;
bool _WasDownloaded = false;
public bool WasAppended;
#endregion Fields
#region Constructor
public MhtWebFile(MhtBuilder parent)
{
_Builder = parent;
}
public MhtWebFile(MhtBuilder parent, string url)
{
_Builder = parent;
if (url != "")
this.Url = url;
}
#endregion Constructor
#region Properties
/// <summary>
/// The Content-Type of this file as returned by the server
/// </summary>
public string ContentType
{
get
{
return _ContentType;
}
}
/// <summary>
/// The raw bytes returned from the server for this file
/// </summary>
public byte[] DownloadedBytes
{
get
{
return _DownloadedBytes;
}
}
/// <summary>
/// If not .WasDownloaded, the exception that prevented download is stored here
/// </summary>
public Exception DownloadException
{
get
{
return _DownloadException;
}
}
/// <summary>
/// file type extension to use on downloaded file
/// this property is only used if the DownloadFilename property does not
/// already contain a file extension
/// </summary>
public string DownloadExtension
{
get
{
if (_DownloadExtension == "" && this.WasDownloaded)
_DownloadExtension = this.ExtensionFromContentType();
return _DownloadExtension;
}
set
{
_DownloadExtension = value;
}
}
/// <summary>
/// filename to download this file as
/// if no filename is provided, a filename will be auto-generated based on
/// the URL; if the UseHtmlTitleAsFilename property is true, then the
/// title tag will be used to generate the filename
/// </summary>
public string DownloadFilename
{
get
{
if (_DownloadFilename == "")
{
if (this._UseHtmlFilename && this.WasDownloaded && this.IsHtml)
{
string htmlTitle = this.HtmlTitle;
if (htmlTitle != "")
_DownloadFilename = MakeValidFilename(htmlTitle, false) + ".htm";
}
else
_DownloadFilename = this.FilenameFromUrl();
}
return _DownloadFilename;
}
set
{
_DownloadFilename = value;
}
}
/// <summary>
/// folder to download this file to
/// if no folder is provided, the current application folder will be used
/// </summary>
public string DownloadFolder
{
get
{
if (_DownloadFolder == "")
_DownloadFolder = AppDomain.CurrentDomain.BaseDirectory;
return _DownloadFolder;
}
set
{
this._DownloadFolder = value;
}
}
/// <summary>
/// the folder name used in the DownloadFolder
/// </summary>
public string DownloadFolderName
{
get
{
return Regex.Match(this.DownloadFolder, @"(?<Folder>[^\\]+)\\*$").Groups["Folder"].Value;
}
}
/// <summary>
/// fully qualified path and filename to download this file to
/// </summary>
public string DownloadPath
{
get
{
if (Path.GetExtension(this.DownloadFilename) == "")
return Path.Combine(this.DownloadFolder, this.DownloadFilename + this.DownloadExtension);
return Path.Combine(this.DownloadFolder, this.DownloadFilename);
}
set
{
this._DownloadFilename = Path.GetFileName(value);
if (_DownloadFilename == "")
_DownloadFolder = value;
else
_DownloadFolder = value.Replace(_DownloadFilename, "");
}
}
/// <summary>
/// If this file has external dependencies, the folder they will be stored on disk
/// </summary>
public string ExternalFilesFolder
{
get
{
return (Path.Combine(this.DownloadFolder, Path.GetFileNameWithoutExtension(this.DownloadFilename)) + "_files");
}
}
/// <summary>
/// If this file is HTML, retrieve the <TITLE> tag from the HTML
/// (maximum of 50 characters)
/// </summary>
public string HtmlTitle
{
get
{
// if (!this.IsHtml)
// throw new Exception("This file isn't HTML, so it has no HTML <TITLE> tag.");
string remp = this.ToString();
string s = Regex.Match(this.ToString(), "<title[^>]*?>(?<text>[^<]+)</title>", RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups["text"].Value;
if (s.Length > 50)
return s.Substring(0, 50);
return s;
}
}
/// <summary>
/// Does this file contain binary data? If not, it must be text data.
/// </summary>
public bool IsBinary
{
get
{
return _IsBinary;
}
}
/// <summary>
/// Is this file CSS content?
/// </summary>
public bool IsCss
{
get
{
return Regex.IsMatch(_ContentType, "text/css", RegexOptions.IgnoreCase);
}
}
/// <summary>
/// Is this file HTML content?
/// </summary>
public bool IsHtml
{
get
{
return Regex.IsMatch(_ContentType, "text/html", RegexOptions.IgnoreCase);
}
}
/// <summary>
/// If this file is text (eg, it isn't binary), the type of text encoding used
/// </summary>
public Encoding TextEncoding
{
get
{
return _TextEncoding;
}
}
/// <summary>
/// The URL target for this file
/// </summary>
public string Url
{
get
{
return this._Url;
}
set
{
_UrlUnmodified = value;
SetUrl(value, true);
_DownloadedBytes = new byte[1];
_ExternalFileCollection = null;
_DownloadException = null;
_TextEncoding = null;
_ContentType = "";
_ContentLocation = "";
_IsBinary = false;
_WasDownloaded = false;
}
}
/// <summary>
/// The Content-Location of this URL as provided by the server,
/// only if the URL was not fully qualified;
/// eg, http://mywebsite.com/ actually maps to http://mywebsite.com/default.htm
/// </summary>
public string UrlContentLocation
{
get
{
return _ContentLocation;
}
}
/// <summary>
/// The root and folder of the URL, eg, http://mywebsite.com/myfolder
/// </summary>
public string UrlFolder
{
get
{
return this._UrlFolder;
}
}
/// <summary>
/// The root of the URL, eg, http://mywebsite.com/
/// </summary>
public string UrlRoot
{
get
{
return this._UrlRoot;
}
}
/// <summary>
/// The unmodified "raw" URL as originally provided
/// </summary>
public string UrlUnmodified
{
get
{
return _UrlUnmodified;
}
}
/// <summary>
/// If enabled, will use the first 50 characters of the TITLE tag
/// to form the filename when saved to disk
/// </summary>
public bool UseHtmlTitleAsFilename
{
get
{
return this._UseHtmlFilename;
}
set
{
this._UseHtmlFilename = value;
}
}
/// <summary>
/// Was this file successfully downloaded via HTTP?
/// </summary>
public bool WasDownloaded
{
get
{
return _WasDownloaded;
}
}
#endregion Properties
#region Public methods
/// <summary>
/// converts all external Html files (gif, jpg, css, etc) to local refs
/// external ref:
/// <img src="http://mywebsite/myfolder/myimage.gif">
/// into local refs:
/// <img src="mypage_files/myimage.gif">
/// </summary>
public void ConvertReferencesToLocal()
{
if (!IsHtml && !IsCss)
throw new Exception(string.Format(Strings.MhtWebFile_Error_ConvertOnlyHTMLOrCSS, ContentType));
// get a list of all external references
string html = this.ToString();
NameValueCollection fileCollection = this.ExternalHtmlFiles();
// no external refs? nothing to do
if (fileCollection.Count == 0)
return;
string[] keys = fileCollection.AllKeys;
for (int idx = 0; idx < keys.Length; idx++)
{
string delimitedUrl = keys[idx];
string fileUrl = fileCollection[delimitedUrl];
if (_Builder.WebFiles.Contains(fileUrl))
{
MhtWebFile wf = (MhtWebFile) _Builder.WebFiles[fileUrl];
string newPath = this.ExternalFilesFolder + "/" + wf.DownloadFilename;
string delimitedReplacement = Regex.Replace(delimitedUrl,
@"^(?<StartDelim>""|'|\()*(?<Value>[^'"")]*)(?<EndDelim>""|'|\))*$",
"${StartDelim}" + newPath + "${EndDelim}");
// correct original Url references in Html so they point to our local files
html = html.Replace(delimitedUrl, delimitedReplacement);
}
}
_DownloadedBytes = _TextEncoding.GetBytes(html);
}
/// <summary>
/// Download this file from the target URL
/// </summary>
public void Download()
{
Debug.Write("Downloading " + this._Url + " ..");
DownloadBytes();
if (_DownloadException == null)
Debug.WriteLine("OK");
else
{
Debug.WriteLine("failed: ", "Error");
Debug.WriteLine(" " + _DownloadException.Message, "Error");
return;
}
if (this.IsHtml)
_DownloadedBytes = _TextEncoding.GetBytes(ProcessHtml(this.ToString()));
if (this.IsCss)
_DownloadedBytes = _TextEncoding.GetBytes(ProcessHtml(this.ToString()));
}
/// <summary>
/// download ALL externally referenced files in this file's html, not recursively,
/// to the default download path for this page
/// </summary>
public void DownloadExternalFiles()
{
this.DownloadExternalFiles(this.ExternalFilesFolder, false);
}
/// <summary>
/// download ALL externally referenced files in this file's html, potentially recursively,
/// to the default download path for this page
/// </summary>
public void DownloadExternalFiles(bool recursive)
{
this.DownloadExternalFiles(this.ExternalFilesFolder, recursive);
}
/// <summary>
/// Saves this file to disk as a plain text file
/// </summary>
public void SaveAsTextFile()
{
this.SaveToFile(Path.ChangeExtension(this.DownloadPath, ".txt"), true);
}
/// <summary>
/// Saves this file to disk as a plain text file, to an arbitrary path
/// </summary>
public void SaveAsTextFile(string filePath)
{
this.SaveToFile(filePath, true);
}
/// <summary>
/// writes contents of file to DownloadPath, using appropriate encoding as necessary
/// </summary>
public void SaveToFile()
{
this.SaveToFile(this.DownloadPath, false);
}
/// <summary>
/// writes contents of file to DownloadPath, using appropriate encoding as necessary
/// </summary>
public void SaveToFile(string filePath)
{
this.SaveToFile(filePath, false);
}
/// <summary>
/// Returns a string representation of the data downloaded for this file
/// </summary>
public override string ToString()
{
if (!_WasDownloaded)
Download();
if (!_WasDownloaded || _DownloadedBytes.Length <= 0)
return "";
if (_IsBinary)
return ("[" + _DownloadedBytes.Length.ToString() + " bytes of binary data]");
return this.TextEncoding.GetString(_DownloadedBytes);
}
/// <summary>
/// Returns the plain text representation of the data in this file,
/// stripping out any HTML tags and codes
/// </summary>
public string ToTextString(bool removeWhitespace /* = false */)
{
string html = this.ToString();
// get rid of <script> .. </script>
html = this.StripHtmlTag("script", html);
// get rid of <style> .. </style>
html = this.StripHtmlTag("style", html);
// get rid of all HTML tags
html = Regex.Replace(html,
@"<\w+(\s+[A-Za-z0-9_\-]+\s*=\s*(""([^""]*)""|'([^']*)'))*\s*(/)*>|<[^>]+>",
" ");
// convert escaped HTML to plaintext
html = HtmlDecode(html);
if (removeWhitespace)
{
// clean up whitespace (optional, depends what you want..)
html = Regex.Replace(html, @"[\n\r\f\t]", " ", RegexOptions.Multiline);
html = Regex.Replace(html, " {2,}", " ", RegexOptions.Multiline);
}
return html;
}
#endregion Public methods
#region Private methods
/// <summary>
/// appends key=value named matches in a regular expression
/// to a target NameValueCollection
/// </summary>
void AddMatchesToCollection(string s, Regex r, ref NameValueCollection nvc)
{
bool headerDisplayed = false;
// Regex urlRegex = new Regex(@"^https*://\w+", RegexOptions.IgnoreCase);
Regex urlRegex = new Regex(@"^files*:///\w+", RegexOptions.IgnoreCase);
foreach (Match match in r.Matches(s))
{
if (!headerDisplayed)
{
Debug.WriteLine("Matches added from regex:");
Debug.WriteLine("'" + match.ToString() + "'");
headerDisplayed = true;
}
string key = match.Groups["Key"].ToString();
string val = match.Groups["Value"].ToString();
if (nvc[key] == null)
{
Debug.WriteLine(" Match: " + match.ToString());
Debug.WriteLine(" Key: " + key);
Debug.WriteLine(" Value: " + val);
if (urlRegex.IsMatch(val))
nvc.Add(key, val);
else
Debug.WriteLine("Match discarded; does not appear to be valid fully qualified file:// Url", "Error");
// Debug.WriteLine("Match discarded; does not appear to be valid fully qualified http:// Url", "Error");
}
}
}
/// <summary>
/// converts all relative url references
/// href="myfolder/mypage.htm"
/// into absolute url references
/// href="http://mywebsite/myfolder/mypage.htm"
/// </summary>
string ConvertRelativeToAbsoluteRefs(string html)
{
string urlPattern =
@"(?<attrib>\shref|\ssrc|\sbackground)\s*?=\s*?" +
@"(?<delim1>[""'\\]{0,2})(?!\s*\+|#|http:|ftp:|mailto:|javascript:)" +
@"/(?<url>[^""'>\\]+)(?<delim2>[""'\\]{0,2})";
string cssPattern =
@"(?<attrib>@import\s|\S+-image:|background:)\s*?(url)*['""(]{1,2}" +
@"(?!http)\s*/(?<url>[^""')]+)['"")]{1,2}";
// href="/anything" to href="http://www.web.com/anything"
Regex r = new Regex(urlPattern, RegexOptions.Multiline | RegexOptions.IgnoreCase);
html = r.Replace(html, "${attrib}=${delim1}" + this._UrlRoot + "/${url}${delim2}");
// href="anything" to href="http://www.web.com/folder/anything"
r = new Regex(urlPattern.Replace("/", ""), RegexOptions.Multiline | RegexOptions.IgnoreCase);
html = r.Replace(html, "${attrib}=${delim1}" + this._UrlFolder + "/${url}${delim2}");
// @import(/anything) to @import url(http://www.web.com/anything)
r = new Regex(cssPattern, RegexOptions.Multiline | RegexOptions.IgnoreCase);
html = r.Replace(html, "${attrib} url(" + this._UrlRoot + "/${url})");
// @import(anything) to @import url(http://www.web.com/folder/anything)
r = new Regex(cssPattern.Replace("/", ""), RegexOptions.Multiline | RegexOptions.IgnoreCase);
html = r.Replace(html, "${attrib} url(" + this._UrlFolder + "/${url})");
return html;
}
/// <summary>
/// if the user passed in a directory, form the filename automatically using the Html title tag
/// if the user passed in a filename, make sure the extension matches our desired extension
/// </summary>
string DeriveFilename(string FilePath, string html, string fileExtension)
{
if (IsDirectory(FilePath))
{
string htmlTitle = this.HtmlTitle;
if (htmlTitle == "")
throw new Exception(Strings.MhtWebFile_Error_NoFilename);
return Path.Combine(Path.GetDirectoryName(FilePath), MakeValidFilename(htmlTitle, false) + fileExtension);
}
if (Path.GetExtension(FilePath) != fileExtension)
return Path.ChangeExtension(FilePath, fileExtension);
return FilePath;
}
/// <summary>
/// download this file from the target URL;
/// place the bytes downloaded in _DownloadedBytes
/// if an exception occurs, capture it in _DownloadException
/// </summary>
void DownloadBytes()
{
if (this.WasDownloaded)
return;
// always download to memory first
try
{
_DownloadedBytes = _Builder.WebClient.DownloadBytes(_Url);
_WasDownloaded = true;
}
catch (WebException ex)
{
_DownloadException = ex;
_Builder.WebClient.ClearDownload();
}
// necessary if the original client URL was imprecise;
// server location is always authoritatitve
if (_Builder.WebClient.ContentLocation != "")
{
_ContentLocation = _Builder.WebClient.ContentLocation;
SetUrl(_ContentLocation, false);
}
_IsBinary = _Builder.WebClient.ResponseIsBinary;
_ContentType = _Builder.WebClient.ResponseContentType;
_TextEncoding = _Builder.WebClient.DetectedEncoding;
_Builder.WebClient.ClearDownload();
}
/// <summary>
/// Download a single externally referenced file (if we haven't already downloaded it)
/// </summary>
void DownloadExternalFile(string url, string targetFolder, bool recursive)
{
bool isNew;
MhtWebFile wf;
// have we already downloaded (or attempted to) this file?
if (_Builder.WebFiles.Contains(url) || _Builder.Url == url)
{
wf = (MhtWebFile) _Builder.WebFiles[url];
isNew = false;
}
else
{
wf = new MhtWebFile(_Builder, url);
isNew = true;
}
wf.Download();
if (isNew)
{
// add this (possibly) downloaded file to our shared collection
_Builder.WebFiles.Add(wf.UrlUnmodified, wf);
// if this is an HTML file, it has dependencies of its own;
// download them into a subfolder
if ((wf.IsHtml || wf.IsCss) && recursive)
wf.DownloadExternalFiles(recursive);
}
}
/// <summary>
/// download ALL externally referenced files in this html, potentially recursively
/// to a specific download path
/// </summary>
void DownloadExternalFiles(string targetFolder, bool recursive)
{
NameValueCollection fileCollection = ExternalHtmlFiles();
if (!fileCollection.HasKeys())
return;
Debug.WriteLine("Downloading all external files collected from URL:");
Debug.WriteLine(" " + this.Url);
foreach (string key in fileCollection.Keys)
DownloadExternalFile(fileCollection[key], targetFolder, recursive);
}
/// <summary>
/// if we weren't given a filename extension, infer it from the download
/// Content-Type header
/// </summary>
/// <remarks>
/// http://www.utoronto.ca/webdocs/HTMLdocs/Book/Book-3ed/appb/mimetype.html
/// </remarks>
string ExtensionFromContentType()
{
switch (Regex.Match(this.ContentType, "^[^ ;]+").Value.ToLower())
{
case "text/html":
return ".htm";
case "image/gif":
return ".gif";
case "image/jpeg":
return ".jpg";
case "text/javascript":
case "application/x-javascript":
return ".js";
case "image/x-png":
return ".png";
case "text/css":
return ".css";
case "text/plain":
return ".txt";
default:
Debug.WriteLine("Unknown content-type '" + this.ContentType + "'", "Error");
return ".htm";
}
}
/// <summary>
/// returns a name/value collection of all external files referenced in HTML:
///
/// "/myfolder/blah.png"
/// 'http://mywebsite/blah.gif'
/// src=blah.jpg
///
/// note that the Key includes the delimiting quotes or parens (if present), but the Value does not
/// this is important because the delimiters are used for matching and replacement to make the
/// match more specific!
/// </summary>
NameValueCollection ExternalHtmlFiles()
{
// avoid doing this work twice, however, be careful that the HTML hasn't
// changed since the last time we called this function
if (_ExternalFileCollection != null)
return _ExternalFileCollection;
_ExternalFileCollection = new NameValueCollection();
string html = this.ToString();
Debug.WriteLine("Resolving all external HTML references from URL:");
Debug.WriteLine(" " + this.Url);
// src='filename.ext' ; background="filename.ext"
// note that we have to test 3 times to catch all quote styles: '', "", and none
Regex r = new Regex(
@"(\ssrc|\sbackground)\s*=\s*((?<Key>'(?<Value>[^']+)')|(?<Key>""(?<Value>[^""]+)"")|(?<Key>(?<Value>[^ \n\r\f]+)))",
RegexOptions.Multiline | RegexOptions.IgnoreCase);
AddMatchesToCollection(html, r, ref _ExternalFileCollection);
// @import "style.css" or @import url(style.css)
r = new Regex(
@"(@import\s|\S+-image:|background:)\s*?(url)*\s*?(?<Key>[""'(]{1,2}(?<Value>[^""')]+)[""')]{1,2})",
RegexOptions.Multiline | RegexOptions.IgnoreCase);
AddMatchesToCollection(html, r, ref _ExternalFileCollection);
// <link rel=stylesheet href="style.css">
r = new Regex(
@"<link[^>]+?href\s*=\s*(?<Key>('|"")*(?<Value>[^'"">]+)('|"")*)",
RegexOptions.Multiline | RegexOptions.IgnoreCase);
AddMatchesToCollection(html, r, ref _ExternalFileCollection);
// <iframe src="mypage.htm"> or <frame src="mypage.aspx">
r = new Regex(
@"<i*frame[^>]+?src\s*=\s*(?<Key>['""]{0,1}(?<Value>[^'""\\>]+)['""]{0,1})",
RegexOptions.Multiline | RegexOptions.IgnoreCase);
AddMatchesToCollection(html, r, ref _ExternalFileCollection);
return _ExternalFileCollection;
}
/// <summary>
/// attempt to get a coherent filename out of the Url
/// </summary>
string FilenameFromUrl()
{
// first, try to get a filename out of the URL itself;
// this means anything past the final slash that doesn't include another slash
// or a question mark, eg http://mywebsite/myfolder/crazy?param=1¶m=2
string filename = Regex.Match(this._Url, "/(?<Filename>[^/?]+)[^/]*$").Groups["Filename"].Value;
if (filename != "")
{
// that worked, but we need to make sure the filename is unique
// if query params were passed to the URL file
Uri u = new Uri(this._Url);
if (u.Query != "")
filename = Path.GetFileNameWithoutExtension(filename) + "_" + u.Query.GetHashCode().ToString() + this.DownloadExtension;
}
// ok, that didn't work; if this file is HTML try to get the TITLE tag
if (filename == "" && this.IsHtml)
{
filename = this.HtmlTitle;
if (filename != "")
filename = filename + ".htm";
}
// now we're really desperate. Hash the URL and make that the filename.
if (filename == "")
filename = _Url.GetHashCode().ToString() + this.DownloadExtension;
return this.MakeValidFilename(filename, false);
}
/// <summary>
/// returns true if this path refers to a directory (vs. a filename)
/// </summary>
bool IsDirectory(string FilePath)
{
return FilePath.EndsWith(@"\");
}
/// <summary>
/// removes all unsafe filesystem characters to form a valid filesystem filename
/// </summary>
string MakeValidFilename(string s, bool enforceLength /* = false */)
{
//if (enforceLength)
//{
//}
//// replace any invalid filesystem chars, plus leading/trailing/doublespaces
//return Regex.Replace(
// Regex.Replace(
// s,
// @"[\/\\\:\*\?\""""\<\>\|]|^\s+|\s+$",
// ""),
// @"\s{2,}",
// " ");
// Replaces any invalid filesystem chars, plus leading/trailing/doublespaces.
string name = Regex.Replace(
Regex.Replace(
s,
@"[\/\\\:\*\?\""""\<\>\|]|^\s+|\s+$",
""),
@"\s{2,}",
" ");
// Enforces the maximum length to 25 characters.
if (name.Length > 25)
{
string ext = Path.GetExtension(name);
name = name.Substring(0, 25 - ext.Length) + ext;
}
return name;
}
/// <summary>
/// Pre-process the CSS using global preference settings
/// </summary>
string ProcessCss(string css)
{
return this.ConvertRelativeToAbsoluteRefs(css);
}
/// <summary>
/// Pre-process the HTML using global preference settings
/// </summary>
string ProcessHtml(string html)
{
Debug.WriteLine("Downloaded content was HTML/CSS -- processing: resolving URLs, getting <base>, etc");
if (_Builder.AddWebMark)
{
// add "mark of the web":
// http://www.microsoft.com/technet/prodtechnol/winxppro/maintain/sp2brows.mspx#XSLTsection133121120120
html = "<!-- saved from url=(" + string.Format("{0:0000}", this._Url.Length) +
")" + this._Url + " -->" + Environment.NewLine + html;
}
// see if we need to strip elements from the HTML
if (_Builder.StripScripts)
html = this.StripHtmlTag("script", html);
if (_Builder.StripIframes)
html = this.StripHtmlTag("iframe", html);
// if we have a <base>, we must use it as the _UrlFolder,
// not what was parsed from the original _Url
string baseUrlFolder = Regex.Match(
html,
"<base[^>]+?href=['\"]{0,1}(?<BaseUrl>[^'\">]+)['\"]{0,1}",
RegexOptions.IgnoreCase).Groups["BaseUrl"].Value;
if (baseUrlFolder != "")
{
if (baseUrlFolder.EndsWith("/"))
_UrlFolder = baseUrlFolder.Substring(0, baseUrlFolder.Length - 1);
else
_UrlFolder = baseUrlFolder;
}
// remove the <base href=''> tag if present; causes problems when viewing locally.
html = Regex.Replace(html, "<base[^>]*?>", "");
// relative URLs are a PITA for the processing we're about to do,
// so convert them all to absolute up front
return this.ConvertRelativeToAbsoluteRefs(html);
}
/// <summary>
/// fully resolves any relative pathing inside the URL, and other URL oddities
/// </summary>
string ResolveUrl(string url)
{
// resolve any relative pathing
try
{
url = new Uri(url).AbsoluteUri;
}
catch (UriFormatException ex)
{
throw new ArgumentException("'" + url + "' does not appear to be a valid URL.", ex);
}
// remove any anchor tags from the end of URLs
if (url.IndexOf("#") > -1)
{
string jump = Regex.Match(url, "/[^/]*?(?<jump>#[^/?.]+$)").Groups["jump"].Value;
if (jump != "")
url = url.Replace(jump, "");
}
return url;
}
/// <summary>
/// sets the DownloadPath and writes contents of file, using appropriate encoding as necessary
/// </summary>
void SaveToFile(string filePath, bool asText)
{
Debug.WriteLine("Saving to file " + filePath);
using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))
{
using (BinaryWriter writer = new BinaryWriter(fs))
{
if (this.IsBinary)
writer.Write(_DownloadedBytes);
else if (asText)
writer.Write(this.ToTextString(false));
else
writer.Write(_DownloadedBytes);
}
}
}
void SetUrl(string url, bool validate)
{
if (validate)
this._Url = this.ResolveUrl(url);
else
this._Url = url;
// http://mywebsite
this._UrlRoot = Regex.Match(url, "http://[^/'\"]+", RegexOptions.IgnoreCase).ToString();
// http://mywebsite/myfolder
if (this._Url.LastIndexOf("/") > 7)
this._UrlFolder = this._Url.Substring(0, this._Url.LastIndexOf("/"));
else
this._UrlFolder = this._UrlRoot;
}
/// <summary>
/// perform the regex replacement of all <tagName> .. </tagName> blocks
/// </summary>
string StripHtmlTag(string tagName, string html)
{
Regex r = new Regex(
string.Format(@"<{0}[^>]*?>[\w|\t|\r|\W]*?</{0}>", tagName), RegexOptions.Multiline | RegexOptions.IgnoreCase);
return r.Replace(html, "");
}
#region Html decoding
string HtmlDecode(string s)
{
if (s == null)
return null;
if (s.IndexOf('&') < 0)
return s;
StringBuilder builder = new StringBuilder();
StringWriter writer = new StringWriter(builder);
for (int i = 0; i < s.Length; i++)
{
char currentChar = s[i];
if (currentChar != '&')
{
writer.Write(currentChar);
continue;
}
int pos = s.IndexOf(';', i + 1);
if (pos <= 0)
{
writer.Write(currentChar);
continue;
}
string subText = s.Substring(i + 1, (pos - i) - 1);
if (subText[0] == '#' && subText.Length > 1)
{
try
{
if ((subText[1] == 'x') || (subText[1] == 'X'))
writer.Write((char) ((ushort) int.Parse(subText.Substring(2),
System.Globalization.NumberStyles.AllowHexSpecifier)));
else
writer.Write((char) ((ushort) int.Parse(subText.Substring(1))));
i = pos;
}
catch (FormatException)
{
i++;
}
catch (ArgumentException)
{
i++;
}
}
else
{
i = pos;
currentChar = HtmlLookup(subText);
if (currentChar != '\0')
{
writer.Write(currentChar);
}
else
{
writer.Write('&');
writer.Write(subText);
writer.Write(';');
}
}
}
return builder.ToString();
}
static Hashtable htmlEntitiesTable = null;
char HtmlLookup(string entity)
{
if (htmlEntitiesTable == null)
{
lock (typeof(MhtWebFile))
{
if (htmlEntitiesTable == null)
{
htmlEntitiesTable = new Hashtable();
string[] htmlEntities = new string[]
{
"\"-quot", "&-amp", "<-lt", ">-gt", "\x00a0-nbsp", "\x00a1-iexcl", "\x00a2-cent", "\x00a3-pound", "\x00a4-curren", "\x00a5-yen", "\x00a6-brvbar", "\x00a7-sect", "\x00a8-uml", "\x00a9-copy", "\x00aa-ordf", "\x00ab-laquo",
"\x00ac-not", "\x00ad-shy", "\x00ae-reg", "\x00af-macr", "\x00b0-deg", "\x00b1-plusmn", "\x00b2-sup2", "\x00b3-sup3", "\x00b4-acute", "\x00b5-micro", "\x00b6-para", "\x00b7-middot", "\x00b8-cedil", "\x00b9-sup1", "\x00ba-ordm", "\x00bb-raquo",
"\x00bc-frac14", "\x00bd-frac12", "\x00be-frac34", "\x00bf-iquest", "\x00c0-Agrave", "\x00c1-Aacute", "\x00c2-Acirc", "\x00c3-Atilde", "\x00c4-Auml", "\x00c5-Aring", "\x00c6-AElig", "\x00c7-Ccedil", "\x00c8-Egrave", "\x00c9-Eacute", "\x00ca-Ecirc", "\x00cb-Euml",
"\x00cc-Igrave", "\x00cd-Iacute", "\x00ce-Icirc", "\x00cf-Iuml", "\x00d0-ETH", "\x00d1-Ntilde", "\x00d2-Ograve", "\x00d3-Oacute", "\x00d4-Ocirc", "\x00d5-Otilde", "\x00d6-Ouml", "\x00d7-times", "\x00d8-Oslash", "\x00d9-Ugrave", "\x00da-Uacute", "\x00db-Ucirc",
"\x00dc-Uuml", "\x00dd-Yacute", "\x00de-THORN", "\x00df-szlig", "\x00e0-agrave", "\x00e1-aacute", "\x00e2-acirc", "\x00e3-atilde", "\x00e4-auml", "\x00e5-aring", "\x00e6-aelig", "\x00e7-ccedil", "\x00e8-egrave", "\x00e9-eacute", "\x00ea-ecirc", "\x00eb-euml",
"\x00ec-igrave", "\x00ed-iacute", "\x00ee-icirc", "\x00ef-iuml", "\x00f0-eth", "\x00f1-ntilde", "\x00f2-ograve", "\x00f3-oacute", "\x00f4-ocirc", "\x00f5-otilde", "\x00f6-ouml", "\x00f7-divide", "\x00f8-oslash", "\x00f9-ugrave", "\x00fa-uacute", "\x00fb-ucirc",
"\x00fc-uuml", "\x00fd-yacute", "\x00fe-thorn", "\x00ff-yuml", "\u0152-OElig", "\u0153-oelig", "\u0160-Scaron", "\u0161-scaron", "\u0178-Yuml", "\u0192-fnof", "\u02c6-circ", "\u02dc-tilde", "\u0391-Alpha", "\u0392-Beta", "\u0393-Gamma", "\u0394-Delta",
"\u0395-Epsilon", "\u0396-Zeta", "\u0397-Eta", "\u0398-Theta", "\u0399-Iota", "\u039a-Kappa", "\u039b-Lambda", "\u039c-Mu", "\u039d-Nu", "\u039e-Xi", "\u039f-Omicron", "\u03a0-Pi", "\u03a1-Rho", "\u03a3-Sigma", "\u03a4-Tau", "\u03a5-Upsilon",
"\u03a6-Phi", "\u03a7-Chi", "\u03a8-Psi", "\u03a9-Omega", "\u03b1-alpha", "\u03b2-beta", "\u03b3-gamma", "\u03b4-delta", "\u03b5-epsilon", "\u03b6-zeta", "\u03b7-eta", "\u03b8-theta", "\u03b9-iota", "\u03ba-kappa", "\u03bb-lambda", "\u03bc-mu",
"\u03bd-nu", "\u03be-xi", "\u03bf-omicron", "\u03c0-pi", "\u03c1-rho", "\u03c2-sigmaf", "\u03c3-sigma", "\u03c4-tau", "\u03c5-upsilon", "\u03c6-phi", "\u03c7-chi", "\u03c8-psi", "\u03c9-omega", "\u03d1-thetasym", "\u03d2-upsih", "\u03d6-piv",
"\u2002-ensp", "\u2003-emsp", "\u2009-thinsp", "\u200c-zwnj", "\u200d-zwj", "\u200e-lrm", "\u200f-rlm", "\u2013-ndash", "\u2014-mdash", "\u2018-lsquo", "\u2019-rsquo", "\u201a-sbquo", "\u201c-ldquo", "\u201d-rdquo", "\u201e-bdquo", "\u2020-dagger",
"\u2021-Dagger", "\u2022-bull", "\u2026-hellip", "\u2030-permil", "\u2032-prime", "\u2033-Prime", "\u2039-lsaquo", "\u203a-rsaquo", "\u203e-oline", "\u2044-frasl", "\u20ac-euro", "\u2111-image", "\u2118-weierp", "\u211c-real", "\u2122-trade", "\u2135-alefsym",
"\u2190-larr", "\u2191-uarr", "\u2192-rarr", "\u2193-darr", "\u2194-harr", "\u21b5-crarr", "\u21d0-lArr", "\u21d1-uArr", "\u21d2-rArr", "\u21d3-dArr", "\u21d4-hArr", "\u2200-forall", "\u2202-part", "\u2203-exist", "\u2205-empty", "\u2207-nabla",
"\u2208-isin", "\u2209-notin", "\u220b-ni", "\u220f-prod", "\u2211-sum", "\u2212-minus", "\u2217-lowast", "\u221a-radic", "\u221d-prop", "\u221e-infin", "\u2220-ang", "\u2227-and", "\u2228-or", "\u2229-cap", "\u222a-cup", "\u222b-int",
"\u2234-there4", "\u223c-sim", "\u2245-cong", "\u2248-asymp", "\u2260-ne", "\u2261-equiv", "\u2264-le", "\u2265-ge", "\u2282-sub", "\u2283-sup", "\u2284-nsub", "\u2286-sube", "\u2287-supe", "\u2295-oplus", "\u2297-otimes", "\u22a5-perp",
"\u22c5-sdot", "\u2308-lceil", "\u2309-rceil", "\u230a-lfloor", "\u230b-rfloor", "\u2329-lang", "\u232a-rang", "\u25ca-loz", "\u2660-spades", "\u2663-clubs", "\u2665-hearts", "\u2666-diams"
};
for (int i = 0; i < htmlEntities.Length; i++)
{
string current = htmlEntities[i];
htmlEntitiesTable[current.Substring(2)] = current[0];
}
}
}
}
object oChar = htmlEntitiesTable[entity];
if (oChar != null)
return (char) oChar;
return '\0';
}
#endregion Html decoding
#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.
/*============================================================
**
**
**
**
** Purpose: Read-only wrapper for another generic dictionary.
**
===========================================================*/
namespace System.Collections.ObjectModel
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
[Serializable]
[DebuggerTypeProxy(typeof(Mscorlib_DictionaryDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
public class ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue>
{
private readonly IDictionary<TKey, TValue> m_dictionary;
[NonSerialized]
private Object m_syncRoot;
[NonSerialized]
private KeyCollection m_keys;
[NonSerialized]
private ValueCollection m_values;
public ReadOnlyDictionary(IDictionary<TKey, TValue> dictionary) {
if (dictionary == null) {
throw new ArgumentNullException(nameof(dictionary));
}
Contract.EndContractBlock();
m_dictionary = dictionary;
}
protected IDictionary<TKey, TValue> Dictionary {
get { return m_dictionary; }
}
public KeyCollection Keys {
get {
Contract.Ensures(Contract.Result<KeyCollection>() != null);
if (m_keys == null) {
m_keys = new KeyCollection(m_dictionary.Keys);
}
return m_keys;
}
}
public ValueCollection Values {
get {
Contract.Ensures(Contract.Result<ValueCollection>() != null);
if (m_values == null) {
m_values = new ValueCollection(m_dictionary.Values);
}
return m_values;
}
}
#region IDictionary<TKey, TValue> Members
public bool ContainsKey(TKey key) {
return m_dictionary.ContainsKey(key);
}
ICollection<TKey> IDictionary<TKey, TValue>.Keys {
get {
return Keys;
}
}
public bool TryGetValue(TKey key, out TValue value) {
return m_dictionary.TryGetValue(key, out value);
}
ICollection<TValue> IDictionary<TKey, TValue>.Values {
get {
return Values;
}
}
public TValue this[TKey key] {
get {
return m_dictionary[key];
}
}
void IDictionary<TKey, TValue>.Add(TKey key, TValue value) {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
bool IDictionary<TKey, TValue>.Remove(TKey key) {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
return false;
}
TValue IDictionary<TKey, TValue>.this[TKey key] {
get {
return m_dictionary[key];
}
set {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
}
#endregion
#region ICollection<KeyValuePair<TKey, TValue>> Members
public int Count {
get { return m_dictionary.Count; }
}
bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item) {
return m_dictionary.Contains(item);
}
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) {
m_dictionary.CopyTo(array, arrayIndex);
}
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly {
get { return true; }
}
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item) {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
void ICollection<KeyValuePair<TKey, TValue>>.Clear() {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item) {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
return false;
}
#endregion
#region IEnumerable<KeyValuePair<TKey, TValue>> Members
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() {
return m_dictionary.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
return ((IEnumerable)m_dictionary).GetEnumerator();
}
#endregion
#region IDictionary Members
private static bool IsCompatibleKey(object key) {
if (key == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
return key is TKey;
}
void IDictionary.Add(object key, object value) {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
void IDictionary.Clear() {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
bool IDictionary.Contains(object key) {
return IsCompatibleKey(key) && ContainsKey((TKey)key);
}
IDictionaryEnumerator IDictionary.GetEnumerator() {
IDictionary d = m_dictionary as IDictionary;
if (d != null) {
return d.GetEnumerator();
}
return new DictionaryEnumerator(m_dictionary);
}
bool IDictionary.IsFixedSize {
get { return true; }
}
bool IDictionary.IsReadOnly {
get { return true; }
}
ICollection IDictionary.Keys {
get {
return Keys;
}
}
void IDictionary.Remove(object key) {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
ICollection IDictionary.Values {
get {
return Values;
}
}
object IDictionary.this[object key] {
get {
if (IsCompatibleKey(key)) {
return this[(TKey)key];
}
return null;
}
set {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
}
void ICollection.CopyTo(Array array, int index) {
if (array == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (array.Rank != 1) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
}
if (array.GetLowerBound(0) != 0) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
}
if (index < 0 || index > array.Length) {
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < Count) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
KeyValuePair<TKey, TValue>[] pairs = array as KeyValuePair<TKey, TValue>[];
if (pairs != null) {
m_dictionary.CopyTo(pairs, index);
}
else {
DictionaryEntry[] dictEntryArray = array as DictionaryEntry[];
if (dictEntryArray != null) {
foreach (var item in m_dictionary) {
dictEntryArray[index++] = new DictionaryEntry(item.Key, item.Value);
}
}
else {
object[] objects = array as object[];
if (objects == null) {
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
try {
foreach (var item in m_dictionary) {
objects[index++] = new KeyValuePair<TKey, TValue>(item.Key, item.Value);
}
}
catch (ArrayTypeMismatchException) {
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
}
}
bool ICollection.IsSynchronized {
get { return false; }
}
object ICollection.SyncRoot {
get {
if (m_syncRoot == null) {
ICollection c = m_dictionary as ICollection;
if (c != null) {
m_syncRoot = c.SyncRoot;
}
else {
System.Threading.Interlocked.CompareExchange<Object>(ref m_syncRoot, new Object(), null);
}
}
return m_syncRoot;
}
}
[Serializable]
private struct DictionaryEnumerator : IDictionaryEnumerator {
private readonly IDictionary<TKey, TValue> m_dictionary;
private IEnumerator<KeyValuePair<TKey, TValue>> m_enumerator;
public DictionaryEnumerator(IDictionary<TKey, TValue> dictionary) {
m_dictionary = dictionary;
m_enumerator = m_dictionary.GetEnumerator();
}
public DictionaryEntry Entry {
get { return new DictionaryEntry(m_enumerator.Current.Key, m_enumerator.Current.Value); }
}
public object Key {
get { return m_enumerator.Current.Key; }
}
public object Value {
get { return m_enumerator.Current.Value; }
}
public object Current {
get { return Entry; }
}
public bool MoveNext() {
return m_enumerator.MoveNext();
}
public void Reset() {
m_enumerator.Reset();
}
}
#endregion
#region IReadOnlyDictionary members
IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys {
get {
return Keys;
}
}
IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values {
get {
return Values;
}
}
#endregion IReadOnlyDictionary members
[DebuggerTypeProxy(typeof(Mscorlib_CollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
public sealed class KeyCollection : ICollection<TKey>, ICollection, IReadOnlyCollection<TKey> {
private readonly ICollection<TKey> m_collection;
[NonSerialized]
private Object m_syncRoot;
internal KeyCollection(ICollection<TKey> collection)
{
if (collection == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
}
m_collection = collection;
}
#region ICollection<T> Members
void ICollection<TKey>.Add(TKey item)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
void ICollection<TKey>.Clear()
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
bool ICollection<TKey>.Contains(TKey item)
{
return m_collection.Contains(item);
}
public void CopyTo(TKey[] array, int arrayIndex)
{
m_collection.CopyTo(array, arrayIndex);
}
public int Count {
get { return m_collection.Count; }
}
bool ICollection<TKey>.IsReadOnly {
get { return true; }
}
bool ICollection<TKey>.Remove(TKey item)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
return false;
}
#endregion
#region IEnumerable<T> Members
public IEnumerator<TKey> GetEnumerator()
{
return m_collection.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
return ((IEnumerable)m_collection).GetEnumerator();
}
#endregion
#region ICollection Members
void ICollection.CopyTo(Array array, int index) {
ReadOnlyDictionaryHelpers.CopyToNonGenericICollectionHelper<TKey>(m_collection, array, index);
}
bool ICollection.IsSynchronized {
get { return false; }
}
object ICollection.SyncRoot {
get {
if (m_syncRoot == null) {
ICollection c = m_collection as ICollection;
if (c != null) {
m_syncRoot = c.SyncRoot;
}
else {
System.Threading.Interlocked.CompareExchange<Object>(ref m_syncRoot, new Object(), null);
}
}
return m_syncRoot;
}
}
#endregion
}
[DebuggerTypeProxy(typeof(Mscorlib_CollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
public sealed class ValueCollection : ICollection<TValue>, ICollection, IReadOnlyCollection<TValue> {
private readonly ICollection<TValue> m_collection;
[NonSerialized]
private Object m_syncRoot;
internal ValueCollection(ICollection<TValue> collection)
{
if (collection == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
}
m_collection = collection;
}
#region ICollection<T> Members
void ICollection<TValue>.Add(TValue item)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
void ICollection<TValue>.Clear()
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
bool ICollection<TValue>.Contains(TValue item)
{
return m_collection.Contains(item);
}
public void CopyTo(TValue[] array, int arrayIndex)
{
m_collection.CopyTo(array, arrayIndex);
}
public int Count {
get { return m_collection.Count; }
}
bool ICollection<TValue>.IsReadOnly {
get { return true; }
}
bool ICollection<TValue>.Remove(TValue item)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
return false;
}
#endregion
#region IEnumerable<T> Members
public IEnumerator<TValue> GetEnumerator()
{
return m_collection.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
return ((IEnumerable)m_collection).GetEnumerator();
}
#endregion
#region ICollection Members
void ICollection.CopyTo(Array array, int index) {
ReadOnlyDictionaryHelpers.CopyToNonGenericICollectionHelper<TValue>(m_collection, array, index);
}
bool ICollection.IsSynchronized {
get { return false; }
}
object ICollection.SyncRoot {
get {
if (m_syncRoot == null) {
ICollection c = m_collection as ICollection;
if (c != null) {
m_syncRoot = c.SyncRoot;
}
else {
System.Threading.Interlocked.CompareExchange<Object>(ref m_syncRoot, new Object(), null);
}
}
return m_syncRoot;
}
}
#endregion ICollection Members
}
}
// To share code when possible, use a non-generic class to get rid of irrelevant type parameters.
internal static class ReadOnlyDictionaryHelpers
{
#region Helper method for our KeyCollection and ValueCollection
// Abstracted away to avoid redundant implementations.
internal static void CopyToNonGenericICollectionHelper<T>(ICollection<T> collection, Array array, int index)
{
if (array == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (array.Rank != 1) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
}
if (array.GetLowerBound(0) != 0) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
}
if (index < 0) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.arrayIndex, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - index < collection.Count) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
// Easy out if the ICollection<T> implements the non-generic ICollection
ICollection nonGenericCollection = collection as ICollection;
if (nonGenericCollection != null) {
nonGenericCollection.CopyTo(array, index);
return;
}
T[] items = array as T[];
if (items != null) {
collection.CopyTo(items, index);
}
else {
//
// Catch the obvious case assignment will fail.
// We can found all possible problems by doing the check though.
// For example, if the element type of the Array is derived from T,
// we can't figure out if we can successfully copy the element beforehand.
//
Type targetType = array.GetType().GetElementType();
Type sourceType = typeof(T);
if (!(targetType.IsAssignableFrom(sourceType) || sourceType.IsAssignableFrom(targetType))) {
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
//
// We can't cast array of value type to object[], so we don't support
// widening of primitive types here.
//
object[] objects = array as object[];
if (objects == null) {
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
try {
foreach (var item in collection) {
objects[index++] = item;
}
}
catch (ArrayTypeMismatchException) {
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
}
#endregion Helper method for our KeyCollection and ValueCollection
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using Microsoft.Build.Framework;
using Microsoft.Build.Shared;
using Microsoft.Build.Tasks;
using Microsoft.Build.Utilities;
using Shouldly;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.Build.UnitTests
{
sealed public class CreateVisualBasicManifestResourceName_Tests
{
private readonly ITestOutputHelper _testOutput;
public CreateVisualBasicManifestResourceName_Tests(ITestOutputHelper output)
{
_testOutput = output;
}
/// <summary>
/// Test the basic functionality.
/// </summary>
[Fact]
public void Basic()
{
string result =
CreateVisualBasicManifestResourceName.CreateManifestNameImpl
(
@"f:\myproject\SubFolder\MyForm.resx",
null, // Link file name
true,
null, // Root namespace
null,
null,
StreamHelpers.StringToStream(
@"
Namespace Nested.TestNamespace
Class TestClass
End Class
End Namespace
"),
null
);
Assert.Equal("Nested.TestNamespace.TestClass", result);
}
/// <summary>
/// Test a dependent with a relative path
/// </summary>
[Fact]
public void RelativeDependentUpon()
{
string result =
CreateVisualBasicManifestResourceName.CreateManifestNameImpl
(
@"f:\myproject\SubFolder\MyForm.resx",
null, // Link file name
true,
null, // Root namespace
null,
null,
StreamHelpers.StringToStream(
@"
Namespace TestNamespace
Class TestClass
End Class
End Namespace
"),
null
);
Assert.Equal("TestNamespace.TestClass", result);
}
/// <summary>
/// Test a dependent with a relative path
/// </summary>
[Fact]
public void AbsoluteDependentUpon()
{
string result =
CreateVisualBasicManifestResourceName.CreateManifestNameImpl
(
@"f:\myproject\SubFolder\MyForm.resx",
null, // Link file name
true,
null, // Root namespace
null,
null,
StreamHelpers.StringToStream(
@"
Namespace Nested.TestNamespace
Class TestClass
End Class
End Namespace
"),
null
);
Assert.Equal("Nested.TestNamespace.TestClass", result);
}
/// <summary>
/// A dependent class plus there is a culture.
/// </summary>
[Fact]
public void DependentWithCulture()
{
string result =
CreateVisualBasicManifestResourceName.CreateManifestNameImpl
(
@"f:\myproject\SubFolder\MyForm.en-GB.resx",
null, // Link file name
true,
null, // Root namespace
null,
null,
StreamHelpers.StringToStream(
@"
Namespace Nested.TestNamespace
Class TestClass
End Class
End Namespace
"),
null
);
Assert.Equal("Nested.TestNamespace.TestClass.en-GB", result);
}
/// <summary>
/// A dependent class plus there is a culture that was expressed in the metadata of the
/// item rather than the filename.
/// </summary>
[Fact]
public void DependentWithCultureMetadata()
{
string result =
CreateVisualBasicManifestResourceName.CreateManifestNameImpl
(
@"f:\myproject\SubFolder\MyForm.resx",
null, // Link file name
true,
null, // Root namespace
null,
"en-GB",
StreamHelpers.StringToStream(
@"
Namespace Nested.TestNamespace
Class TestClass
End Class
End Namespace
"),
null
);
Assert.Equal("Nested.TestNamespace.TestClass.en-GB", result);
}
/// <summary>
/// A dependent class plus there is a culture and a root namespace.
/// </summary>
[Fact]
public void DependentWithCultureAndRootNamespace()
{
string result =
CreateVisualBasicManifestResourceName.CreateManifestNameImpl
(
@"f:\myproject\SubFolder\MyForm.en-GB.resx",
null, // Link file name
true,
"RootNamespace",
null,
null,
StreamHelpers.StringToStream(
@"
Namespace Nested.TestNamespace
Class TestClass
End Class
End Namespace
"),
null
);
Assert.Equal("RootNamespace.Nested.TestNamespace.TestClass.en-GB", result);
}
/// <summary>
/// A dependent class plus there is a culture embedded in the .RESX filename.
/// </summary>
[Fact]
public void DependentWithEmbeddedCulture()
{
string result =
CreateVisualBasicManifestResourceName.CreateManifestNameImpl
(
@"f:\myproject\SubFolder\MyForm.fr-fr.resx",
null, // Link file name
true,
"RootNamespace", // Root namespace
null,
null,
StreamHelpers.StringToStream(
@"
Namespace Nested.TestNamespace
Class TestClass
End Class
End Namespace
"),
null
);
Assert.Equal("RootNamespace.Nested.TestNamespace.TestClass.fr-fr", result);
}
/// <summary>
/// No dependent class, but there is a root namespace place. Also, the .resx
/// extension contains some upper-case characters.
/// </summary>
[Fact]
public void RootnamespaceWithCulture()
{
string result =
CreateVisualBasicManifestResourceName.CreateManifestNameImpl(
FileUtilities.FixFilePath(@"SubFolder\MyForm.en-GB.ResX"),
null,
// Link file name
true,
"RootNamespace",
// Root namespace
null,
null,
null,
null);
Assert.Equal("RootNamespace.MyForm.en-GB", result);
}
/// <summary>
/// If there is a link file name then it is preferred over the main file name.
/// </summary>
[Fact]
public void Regress222308()
{
string result =
CreateVisualBasicManifestResourceName.CreateManifestNameImpl
(
@"..\..\XmlEditor\Setup\XmlEditor.rgs",
@"MyXmlEditor.rgs",
true,
"RootNamespace", // Root namespace
null,
null,
null,
null
);
Assert.Equal("RootNamespace.MyXmlEditor.rgs", result);
}
/// <summary>
/// A non-resx file in a subfolder, with a root namespace.
/// </summary>
[Fact]
public void BitmapWithRootNamespace()
{
string result =
CreateVisualBasicManifestResourceName.CreateManifestNameImpl(
FileUtilities.FixFilePath(@"SubFolder\SplashScreen.bmp"),
null, // Link file name
true,
"RootNamespace", // Root namespace
null,
null,
null,
null);
Assert.Equal("RootNamespace.SplashScreen.bmp", result);
}
/// <summary>
/// A culture-specific non-resx file in a subfolder, with a root namespace.
/// </summary>
[Fact]
public void CulturedBitmapWithRootNamespace()
{
string result =
CreateVisualBasicManifestResourceName.CreateManifestNameImpl(
FileUtilities.FixFilePath(@"SubFolder\SplashScreen.fr.bmp"),
null, // Link file name
true,
"RootNamespace", // Root namespace
null,
null,
null,
null);
Assert.Equal(FileUtilities.FixFilePath(@"fr\RootNamespace.SplashScreen.bmp"), result);
}
/// <summary>
/// A culture-specific non-resx file in a subfolder, with a root namespace, but no culture directory prefix
/// </summary>
[Fact]
public void CulturedBitmapWithRootNamespaceNoDirectoryPrefix()
{
string result =
CreateVisualBasicManifestResourceName.CreateManifestNameImpl(
FileUtilities.FixFilePath(@"SubFolder\SplashScreen.fr.bmp"),
null, // Link file name
false,
"RootNamespace", // Root namespace
null,
null,
null,
null);
Assert.Equal(@"RootNamespace.SplashScreen.bmp", result);
}
/// <summary>
/// If the filename passed in as the "DependentUpon" file doesn't end in .cs then
/// we want to fall back to the RootNamespace+FileName logic.
/// </summary>
[Fact]
public void Regress188319()
{
CreateVisualBasicManifestResourceName t = new CreateVisualBasicManifestResourceName();
t.BuildEngine = new MockEngine();
ITaskItem i = new TaskItem("SR1.resx");
i.SetMetadata("BuildAction", "EmbeddedResource");
i.SetMetadata("DependentUpon", "SR1.strings"); // Normally, this would be a C# file.
t.ResourceFiles = new ITaskItem[] { i };
t.RootNamespace = "CustomToolTest";
bool success = t.Execute(new Microsoft.Build.Tasks.CreateFileStream(CreateFileStream));
Assert.True(success); // "Expected the task to succeed."
ITaskItem[] resourceNames = t.ManifestResourceNames;
Assert.Single(resourceNames);
Assert.Equal(@"CustomToolTest.SR1", resourceNames[0].ItemSpec);
}
/// <summary>
/// If we have a resource file that has a culture within it's name (resourceFile.de.cs), find it by convention.
/// </summary>
[Fact]
public void CulturedResourceFileFindByConvention()
{
using (var env = TestEnvironment.Create(_testOutput))
{
var csFile = env.CreateFile("SR1.vb", @"
Namespace MyStuff
Class Class2
End Class
End Namespace");
var resXFile = env.CreateFile("SR1.de.resx", "");
ITaskItem i = new TaskItem(resXFile.Path);
i.SetMetadata("BuildAction", "EmbeddedResource");
// this data is set automatically through the AssignCulture task, so we manually set it here
i.SetMetadata("WithCulture", "true");
i.SetMetadata("Culture", "de");
env.SetCurrentDirectory(Path.GetDirectoryName(resXFile.Path));
CreateVisualBasicManifestResourceName t = new CreateVisualBasicManifestResourceName
{
BuildEngine = new MockEngine(_testOutput),
UseDependentUponConvention = true,
ResourceFiles = new ITaskItem[] { i },
};
t.Execute().ShouldBeTrue("Expected the task to succeed");
t.ManifestResourceNames.ShouldHaveSingleItem();
// CreateManifestNameImpl appends culture to the end of the convention
t.ManifestResourceNames[0].ItemSpec.ShouldBe("MyStuff.Class2.de", "Expected Namespace.Class.Culture");
}
}
/// <summary>
/// Given a file path, return a stream on top of that path.
/// </summary>
/// <param name="path">Path to the file</param>
/// <param name="mode">File mode</param>
/// <param name="access">Access type</param>
/// <returns>The Stream</returns>
private Stream CreateFileStream(string path, FileMode mode, FileAccess access)
{
if (String.Compare(path, "SR1.strings", StringComparison.OrdinalIgnoreCase) == 0)
{
return StreamHelpers.StringToStream(
@"
Namespace Nested.TestNamespace
Class TestClass
End Class
End Namespace
");
}
Assert.True(false, String.Format("Encountered a new path {0}, needs unittesting support", path));
return null;
}
/// <summary>
/// If the dependent upon filename and the resource filename both contain what looks like
/// a culture, do not treat it as a culture identifier. E.g.:
///
/// Form1.ro.resx == DependentUpon ==> Form1.ro.vb
///
/// In this case, we don't include "ro" as the culture because it's in both filenames. In
/// the case of:
///
/// Form1.ro.resx == DependentUpon ==> Form1.vb
///
/// we continue to treat "ro" as the culture.
/// </summary>
[Fact]
public void Regress419591()
{
string result =
CreateVisualBasicManifestResourceName.CreateManifestNameImpl
(
"MyForm.ro.resx",
null, // Link file name
true,
"RootNamespace", // Root namespace
"MyForm.ro.vb",
null,
StreamHelpers.StringToStream(
@"
Class MyForm
End Class
"),
null
);
Assert.Equal("RootNamespace.MyForm", result);
}
/// <summary>
/// If we encounter a class or namespace name within a conditional compilation directive,
/// we need to warn because we do not try to resolve the correct manifest name depending
/// on conditional compilation of code.
/// </summary>
[Fact]
public void Regress459265()
{
MockEngine m = new MockEngine();
CreateVisualBasicManifestResourceName c = new CreateVisualBasicManifestResourceName();
c.BuildEngine = m;
string result =
CreateVisualBasicManifestResourceName.CreateManifestNameImpl
(
"MyForm.resx",
null,
true,
"RootNamespace", // Root namespace (will be ignored because it's dependent)
"MyForm.vb",
null,
StreamHelpers.StringToStream(
@"Imports System
#if false
Namespace ClassLibrary1
#end if
#if Debug
Namespace ClassLibrary2
#else
Namespace ClassLibrary3
#end if
Class MyForm
End Class
End Namespace
"
),
c.Log
);
Assert.Contains(
String.Format(AssemblyResources.GetString("CreateManifestResourceName.DefinitionFoundWithinConditionalDirective"), "MyForm.vb", "MyForm.resx"),
m.Log
);
}
/// <summary>
/// Tests to ensure that the ResourceFilesWithManifestResourceNames contains everything that
/// the ResourceFiles property on the task contains, but with additional metadata called ManifestResourceName
/// </summary>
[Fact]
public void ResourceFilesWithManifestResourceNamesContainsAdditionalMetadata()
{
CreateVisualBasicManifestResourceName t = new CreateVisualBasicManifestResourceName();
t.BuildEngine = new MockEngine();
ITaskItem i = new TaskItem("strings.resx");
t.ResourceFiles = new ITaskItem[] { i };
t.RootNamespace = "ResourceRoot";
bool success = t.Execute();
Assert.True(success); // "Expected the task to succeed."
ITaskItem[] resourceFiles = t.ResourceFilesWithManifestResourceNames;
Assert.Single(resourceFiles);
Assert.Equal(@"strings.resx", resourceFiles[0].ItemSpec);
Assert.Equal(@"ResourceRoot.strings", resourceFiles[0].GetMetadata("ManifestResourceName"));
}
/// <summary>
/// Ensure that if no LogicalName is specified, that the same ManifestResourceName metadata
/// gets applied as LogicalName
/// </summary>
[Fact]
public void AddLogicalNameForNonResx()
{
CreateVisualBasicManifestResourceName t = new CreateVisualBasicManifestResourceName();
t.BuildEngine = new MockEngine();
ITaskItem i = new TaskItem("pic.bmp");
i.SetMetadata("Type", "Non-Resx");
t.ResourceFiles = new ITaskItem[] { i };
t.RootNamespace = "ResourceRoot";
bool success = t.Execute();
Assert.True(success); // "Expected the task to succeed."
ITaskItem[] resourceFiles = t.ResourceFilesWithManifestResourceNames;
Assert.Single(resourceFiles);
Assert.Equal(@"pic.bmp", resourceFiles[0].ItemSpec);
Assert.Equal(@"ResourceRoot.pic.bmp", resourceFiles[0].GetMetadata("LogicalName"));
}
/// <summary>
/// Ensure that a LogicalName that is already present is preserved during manifest name generation
/// </summary>
[Fact]
public void PreserveLogicalNameForNonResx()
{
CreateVisualBasicManifestResourceName t = new CreateVisualBasicManifestResourceName();
t.BuildEngine = new MockEngine();
ITaskItem i = new TaskItem("pic.bmp");
i.SetMetadata("LogicalName", "foo");
i.SetMetadata("Type", "Non-Resx");
t.ResourceFiles = new ITaskItem[] { i };
t.RootNamespace = "ResourceRoot";
bool success = t.Execute();
Assert.True(success); // "Expected the task to succeed."
ITaskItem[] resourceFiles = t.ResourceFilesWithManifestResourceNames;
Assert.Single(resourceFiles);
Assert.Equal(@"pic.bmp", resourceFiles[0].ItemSpec);
Assert.Equal(@"foo", resourceFiles[0].GetMetadata("LogicalName"));
}
/// <summary>
/// Resx resources should not get ManifestResourceName metadata copied to the LogicalName value
/// </summary>
[Fact]
public void NoLogicalNameAddedForResx()
{
CreateVisualBasicManifestResourceName t = new CreateVisualBasicManifestResourceName();
t.BuildEngine = new MockEngine();
ITaskItem i = new TaskItem("strings.resx");
i.SetMetadata("Type", "Resx");
t.ResourceFiles = new ITaskItem[] { i };
t.RootNamespace = "ResourceRoot";
bool success = t.Execute();
Assert.True(success); // "Expected the task to succeed."
ITaskItem[] resourceFiles = t.ResourceFilesWithManifestResourceNames;
Assert.Single(resourceFiles);
Assert.Equal(@"strings.resx", resourceFiles[0].ItemSpec);
Assert.Equal(String.Empty, resourceFiles[0].GetMetadata("LogicalName"));
}
/// <summary>
/// A culture-specific resources file in a subfolder, with a root namespace
/// </summary>
[Fact]
public void CulturedResourcesFileWithRootNamespaceWithinSubfolder()
{
string result =
CreateVisualBasicManifestResourceName.CreateManifestNameImpl(
FileUtilities.FixFilePath(@"SubFolder\MyResource.fr.resources"),
null, // Link file name
false,
"RootNamespace", // Root namespace
null,
null,
null,
null);
Assert.Equal(@"RootNamespace.MyResource.fr.resources", result);
}
/// <summary>
/// A culture-specific resources file with a root namespace
/// </summary>
[Fact]
public void CulturedResourcesFileWithRootNamespace()
{
string result =
CreateVisualBasicManifestResourceName.CreateManifestNameImpl
(
@"MyResource.fr.resources",
null, // Link file name
false,
"RootNamespace", // Root namespace
null,
null,
null,
null
);
Assert.Equal(@"RootNamespace.MyResource.fr.resources", result);
}
/// <summary>
/// A non-culture-specific resources file with a root namespace
/// </summary>
[Fact]
public void ResourcesFileWithRootNamespace()
{
string result =
CreateVisualBasicManifestResourceName.CreateManifestNameImpl
(
@"MyResource.resources",
null, // Link file name
false,
"RootNamespace", // Root namespace
null,
null,
null,
null
);
Assert.Equal(@"RootNamespace.MyResource.resources", result);
}
private void AssertSimpleCase(string code, string expected)
{
string result =
CreateVisualBasicManifestResourceName.CreateManifestNameImpl
(
"MyForm.resx",
null, // Link file name
true,
"RootNamespace", // Root namespace
"MyForm.vb",
null,
StreamHelpers.StringToStream(code),
null
);
Assert.Equal(expected, result);
}
}
}
| |
//
// 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.Collections.Generic;
using System.Linq;
using Hyak.Common;
using Microsoft.WindowsAzure.Management.Compute.Models;
namespace Microsoft.WindowsAzure.Management.Compute.Models
{
/// <summary>
/// Details of a role in a deployment.
/// </summary>
public partial class Role
{
private string _availabilitySetName;
/// <summary>
/// Optional. The name of the role.
/// </summary>
public string AvailabilitySetName
{
get { return this._availabilitySetName; }
set { this._availabilitySetName = value; }
}
private IList<ConfigurationSet> _configurationSets;
/// <summary>
/// Optional. A collection of values that represents system or
/// application configuration settings.
/// </summary>
public IList<ConfigurationSet> ConfigurationSets
{
get { return this._configurationSets; }
set { this._configurationSets = value; }
}
private IList<DataVirtualHardDisk> _dataVirtualHardDisks;
/// <summary>
/// Optional. Contains the parameters Azure uses to create a data disk
/// for a virtual machine.
/// </summary>
public IList<DataVirtualHardDisk> DataVirtualHardDisks
{
get { return this._dataVirtualHardDisks; }
set { this._dataVirtualHardDisks = value; }
}
private DebugSettings _debugSettings;
/// <summary>
/// Optional. This parameter can be used to set debug settings for a
/// VM. When boot diagnostics feature is enabled, console screenshot
/// or serial output is stored in blob storage. This property is only
/// returned with a version header of 2015-09-01 or newer.
/// </summary>
public DebugSettings DebugSettings
{
get { return this._debugSettings; }
set { this._debugSettings = value; }
}
private string _defaultWinRmCertificateThumbprint;
/// <summary>
/// Optional. The read-only thumbprint of the certificate that is used
/// with the HTTPS listener for WinRM.
/// </summary>
public string DefaultWinRmCertificateThumbprint
{
get { return this._defaultWinRmCertificateThumbprint; }
set { this._defaultWinRmCertificateThumbprint = value; }
}
private string _label;
/// <summary>
/// Optional. The friendly name for the role.
/// </summary>
public string Label
{
get { return this._label; }
set { this._label = value; }
}
private string _licenseType;
/// <summary>
/// Optional. Specifies that the image or disk that is being used was
/// licensed on-premises. This element is only used for images that
/// contain the Windows Server operating system. Possible values are:
/// Windows_Client, Windows_Server
/// </summary>
public string LicenseType
{
get { return this._licenseType; }
set { this._licenseType = value; }
}
private Uri _mediaLocation;
/// <summary>
/// Optional. Storage location where the VM Image VHDs should be
/// copied, for published VM Images.
/// </summary>
public Uri MediaLocation
{
get { return this._mediaLocation; }
set { this._mediaLocation = value; }
}
private string _migrationState;
/// <summary>
/// Optional. Specifies the IaaS Classic to ARM migration state of the
/// virtual machine.Possible values are: None, Preparing, Prepared,
/// PrepareFailed, Committing, Committed, CommitFailed, Aborting,
/// AbortFailed.None is treated as null value and it is not be visible.
/// </summary>
public string MigrationState
{
get { return this._migrationState; }
set { this._migrationState = value; }
}
private string _oSVersion;
/// <summary>
/// Optional. The version of the operating system on which the role
/// instances are running.
/// </summary>
public string OSVersion
{
get { return this._oSVersion; }
set { this._oSVersion = value; }
}
private OSVirtualHardDisk _oSVirtualHardDisk;
/// <summary>
/// Optional. Contains the parameters Azure uses to create the
/// operating system disk for the virtual machine.
/// </summary>
public OSVirtualHardDisk OSVirtualHardDisk
{
get { return this._oSVirtualHardDisk; }
set { this._oSVirtualHardDisk = value; }
}
private bool? _provisionGuestAgent;
/// <summary>
/// Optional. Indicates whether the WindowsAzureGuestAgent service is
/// installed on the Virtual Machine. To run a resource extension in a
/// Virtual Machine, this service must be installed.
/// </summary>
public bool? ProvisionGuestAgent
{
get { return this._provisionGuestAgent; }
set { this._provisionGuestAgent = value; }
}
private IList<ResourceExtensionReference> _resourceExtensionReferences;
/// <summary>
/// Optional. Contains a collection of resource extensions that are to
/// be installed on the Virtual Machine. This element is used if
/// ProvisionGuestAgent is set to true.
/// </summary>
public IList<ResourceExtensionReference> ResourceExtensionReferences
{
get { return this._resourceExtensionReferences; }
set { this._resourceExtensionReferences = value; }
}
private string _roleName;
/// <summary>
/// Optional. The name of the role.
/// </summary>
public string RoleName
{
get { return this._roleName; }
set { this._roleName = value; }
}
private string _roleSize;
/// <summary>
/// Optional. The size of the role instance.
/// </summary>
public string RoleSize
{
get { return this._roleSize; }
set { this._roleSize = value; }
}
private string _roleType;
/// <summary>
/// Optional. Specifies the type of the role. This element is only
/// listed for Virtual Machine deployments, and by default is
/// PersistentVMRole.
/// </summary>
public string RoleType
{
get { return this._roleType; }
set { this._roleType = value; }
}
private VMImageInput _vMImageInput;
/// <summary>
/// Optional. When a VM Image is used to create a new PersistantVMRole,
/// the DiskConfigurations in the VM Image are used to create new
/// Disks for the new VM. This parameter can be used to resize the
/// newly created Disks to a larger size than the underlying
/// DiskConfigurations in the VM Image.This property is only returned
/// with a version header of 2014-10-01 or newer.
/// </summary>
public VMImageInput VMImageInput
{
get { return this._vMImageInput; }
set { this._vMImageInput = value; }
}
private string _vMImageName;
/// <summary>
/// Optional. Optional. The name of the VMImage from which this Role is
/// to be created. If the OSDisk in the VMImage was Specialized, then
/// no WindowsProvisioningConfigurationSet or
/// LinuxProvisioningConfigurationSet should be provided. No
/// OSVirtualHardDisk or DataVirtualHardDisk should be specified when
/// using this argument.
/// </summary>
public string VMImageName
{
get { return this._vMImageName; }
set { this._vMImageName = value; }
}
/// <summary>
/// Initializes a new instance of the Role class.
/// </summary>
public Role()
{
this.ConfigurationSets = new LazyList<ConfigurationSet>();
this.DataVirtualHardDisks = new LazyList<DataVirtualHardDisk>();
this.ResourceExtensionReferences = new LazyList<ResourceExtensionReference>();
}
}
}
| |
// 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.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Editor.CSharp.TextStructureNavigation;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.TextStructureNavigation
{
public class TextStructureNavigatorTests
{
[WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)]
public async Task Empty()
{
await AssertExtentAsync(
string.Empty,
pos: 0,
isSignificant: false,
start: 0, length: 0);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)]
public async Task Whitespace()
{
await AssertExtentAsync(
" ",
pos: 0,
isSignificant: false,
start: 0, length: 3);
await AssertExtentAsync(
" ",
pos: 1,
isSignificant: false,
start: 0, length: 3);
await AssertExtentAsync(
" ",
pos: 3,
isSignificant: false,
start: 0, length: 3);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)]
public async Task EndOfFile()
{
await AssertExtentAsync(
"using System;",
pos: 13,
isSignificant: true,
start: 12, length: 1);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)]
public async Task NewLine()
{
await AssertExtentAsync(
"class Class1 {\r\n\r\n}",
pos: 14,
isSignificant: false,
start: 14, length: 2);
await AssertExtentAsync(
"class Class1 {\r\n\r\n}",
pos: 15,
isSignificant: false,
start: 14, length: 2);
await AssertExtentAsync(
"class Class1 {\r\n\r\n}",
pos: 16,
isSignificant: false,
start: 16, length: 2);
await AssertExtentAsync(
"class Class1 {\r\n\r\n}",
pos: 17,
isSignificant: false,
start: 16, length: 2);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)]
public async Task SingleLineComment()
{
await AssertExtentAsync(
"// Comment ",
pos: 0,
isSignificant: true,
start: 0, length: 12);
// It is important that this returns just the comment banner. Returning the whole comment
// means Ctrl+Right before the slash will cause it to jump across the entire comment
await AssertExtentAsync(
"// Comment ",
pos: 1,
isSignificant: true,
start: 0, length: 2);
await AssertExtentAsync(
"// Comment ",
pos: 5,
isSignificant: true,
start: 3, length: 7);
await AssertExtentAsync(
"// () test",
pos: 4,
isSignificant: true,
start: 3, length: 2);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)]
public async Task MultiLineComment()
{
await AssertExtentAsync(
"/* Comment */",
pos: 0,
isSignificant: true,
start: 0, length: 13);
// It is important that this returns just the comment banner. Returning the whole comment
// means Ctrl+Right before the slash will cause it to jump across the entire comment
await AssertExtentAsync(
"/* Comment */",
pos: 1,
isSignificant: true,
start: 0, length: 2);
await AssertExtentAsync(
"/* Comment */",
pos: 5,
isSignificant: true,
start: 3, length: 7);
await AssertExtentAsync(
"/* () test */",
pos: 4,
isSignificant: true,
start: 3, length: 2);
await AssertExtentAsync(
"/* () test */",
pos: 11,
isSignificant: true,
start: 11, length: 2);
// It is important that this returns just the comment banner. Returning the whole comment
// means Ctrl+Left after the slash will cause it to jump across the entire comment
await AssertExtentAsync(
"/* () test */",
pos: 12,
isSignificant: true,
start: 11, length: 2);
await AssertExtentAsync(
"/* () test */",
pos: 13,
isSignificant: true,
start: 11, length: 2);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)]
public async Task Keyword()
{
for (int i = 7; i <= 7 + 4; i++)
{
await AssertExtentAsync(
"public class Class1",
pos: i,
isSignificant: true,
start: 7, length: 5);
}
}
[WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)]
public async Task Identifier()
{
for (int i = 13; i <= 13 + 8; i++)
{
await AssertExtentAsync(
"public class SomeClass : IDisposable",
pos: i,
isSignificant: true,
start: 13, length: 9);
}
}
[WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)]
public async Task EscapedIdentifier()
{
for (int i = 12; i <= 12 + 9; i++)
{
await AssertExtentAsync(
"public enum @interface : int",
pos: i,
isSignificant: true,
start: 12, length: 10);
}
}
[WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)]
public async Task Number()
{
for (int i = 37; i <= 37 + 10; i++)
{
await AssertExtentAsync(
"class Test { private double num = -1.234678e10; }",
pos: i,
isSignificant: true,
start: 37, length: 11);
}
}
[WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)]
public async Task String()
{
const string TestString = "class Test { private string s1 = \" () test \"; }";
int startOfString = TestString.IndexOf('"');
int lengthOfStringIncludingQuotes = TestString.LastIndexOf('"') - startOfString + 1;
await AssertExtentAsync(
TestString,
pos: startOfString,
isSignificant: true,
start: startOfString, length: 1);
// Selects whitespace
await AssertExtentAsync(
TestString,
pos: startOfString + 1,
isSignificant: false,
start: startOfString + 1, length: 1);
await AssertExtentAsync(
TestString,
pos: startOfString + 2,
isSignificant: true,
start: startOfString + 2, length: 2);
await AssertExtentAsync(
TestString,
pos: TestString.IndexOf(" \"", StringComparison.Ordinal),
isSignificant: false,
start: TestString.IndexOf(" \"", StringComparison.Ordinal), length: 2);
await AssertExtentAsync(
TestString,
pos: TestString.LastIndexOf('"'),
isSignificant: true,
start: startOfString + lengthOfStringIncludingQuotes - 1, length: 1);
await AssertExtentAsync(
TestString,
pos: TestString.LastIndexOf('"') + 1,
isSignificant: true,
start: TestString.LastIndexOf('"') + 1, length: 1);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)]
public async Task InterpolatedString1()
{
const string TestString = "class Test { string x = \"hello\"; string s = $\" { x } hello\"; }";
int startOfFirstString = TestString.IndexOf('"');
int endOfFirstString = TestString.IndexOf('"', startOfFirstString + 1);
int startOfString = TestString.IndexOf("$\"", endOfFirstString + 1, StringComparison.Ordinal);
int lengthOfStringIncludingQuotes = TestString.LastIndexOf('"') - startOfString + 1;
// Selects interpolated string start token
await AssertExtentAsync(
TestString,
pos: startOfString,
isSignificant: true,
start: startOfString, length: 2);
// Selects whitespace
await AssertExtentAsync(
TestString,
pos: startOfString + 2,
isSignificant: false,
start: startOfString + 2, length: 1);
// Selects the opening curly brace
await AssertExtentAsync(
TestString,
pos: startOfString + 3,
isSignificant: true,
start: startOfString + 3, length: 1);
// Selects whitespace
await AssertExtentAsync(
TestString,
pos: startOfString + 4,
isSignificant: false,
start: startOfString + 4, length: 1);
// Selects identifier
await AssertExtentAsync(
TestString,
pos: startOfString + 5,
isSignificant: true,
start: startOfString + 5, length: 1);
// Selects whitespace
await AssertExtentAsync(
TestString,
pos: startOfString + 6,
isSignificant: false,
start: startOfString + 6, length: 1);
// Selects the closing curly brace
await AssertExtentAsync(
TestString,
pos: startOfString + 7,
isSignificant: true,
start: startOfString + 7, length: 1);
// Selects whitespace
await AssertExtentAsync(
TestString,
pos: startOfString + 8,
isSignificant: false,
start: startOfString + 8, length: 1);
// Selects hello
await AssertExtentAsync(
TestString,
pos: startOfString + 9,
isSignificant: true,
start: startOfString + 9, length: 5);
// Selects closing quote
await AssertExtentAsync(
TestString,
pos: startOfString + 14,
isSignificant: true,
start: startOfString + 14, length: 1);
}
private static async Task AssertExtentAsync(string code, int pos, bool isSignificant, int start, int length)
{
await AssertExtentAsync(code, pos, isSignificant, start, length, null);
await AssertExtentAsync(code, pos, isSignificant, start, length, Options.Script);
}
private static async Task AssertExtentAsync(string code, int pos, bool isSignificant, int start, int length, CSharpParseOptions options)
{
using (var workspace = await CSharpWorkspaceFactory.CreateWorkspaceFromFileAsync(code, options))
{
var buffer = workspace.Documents.First().GetTextBuffer();
var provider = new TextStructureNavigatorProvider(
workspace.GetService<ITextStructureNavigatorSelectorService>(),
workspace.GetService<IContentTypeRegistryService>(),
workspace.GetService<IWaitIndicator>());
var navigator = provider.CreateTextStructureNavigator(buffer);
var extent = navigator.GetExtentOfWord(new SnapshotPoint(buffer.CurrentSnapshot, pos));
Assert.Equal(isSignificant, extent.IsSignificant);
var expectedSpan = new SnapshotSpan(buffer.CurrentSnapshot, start, length);
Assert.Equal(expectedSpan, extent.Span);
}
}
private static async Task TestNavigatorAsync(
string code,
Func<ITextStructureNavigator, SnapshotSpan, SnapshotSpan> func,
int startPosition,
int startLength,
int endPosition,
int endLength)
{
await TestNavigatorAsync(code, func, startPosition, startLength, endPosition, endLength, null);
await TestNavigatorAsync(code, func, startPosition, startLength, endPosition, endLength, Options.Script);
}
private static async Task TestNavigatorAsync(
string code,
Func<ITextStructureNavigator, SnapshotSpan, SnapshotSpan> func,
int startPosition,
int startLength,
int endPosition,
int endLength,
CSharpParseOptions options)
{
using (var workspace = await CSharpWorkspaceFactory.CreateWorkspaceFromFileAsync(code, options))
{
var buffer = workspace.Documents.First().GetTextBuffer();
var provider = new TextStructureNavigatorProvider(
workspace.GetService<ITextStructureNavigatorSelectorService>(),
workspace.GetService<IContentTypeRegistryService>(),
workspace.GetService<IWaitIndicator>());
var navigator = provider.CreateTextStructureNavigator(buffer);
var actualSpan = func(navigator, new SnapshotSpan(buffer.CurrentSnapshot, startPosition, startLength));
var expectedSpan = new SnapshotSpan(buffer.CurrentSnapshot, endPosition, endLength);
Assert.Equal(expectedSpan, actualSpan.Span);
}
}
[WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)]
public async Task GetSpanOfEnclosingTest()
{
// First operation returns span of 'Class1'
await TestNavigatorAsync("class Class1 { }", (n, s) => n.GetSpanOfEnclosing(s), 10, 0, 6, 6);
// Second operation returns span of 'class Class1 { }'
await TestNavigatorAsync("class Class1 { }", (n, s) => n.GetSpanOfEnclosing(s), 6, 6, 0, 16);
// Last operation does nothing
await TestNavigatorAsync("class Class1 { }", (n, s) => n.GetSpanOfEnclosing(s), 0, 16, 0, 16);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)]
public async Task GetSpanOfFirstChildTest()
{
// Go from 'class Class1 { }' to 'class'
await TestNavigatorAsync("class Class1 { }", (n, s) => n.GetSpanOfFirstChild(s), 0, 16, 0, 5);
// Next operation should do nothing as we're at the bottom
await TestNavigatorAsync("class Class1 { }", (n, s) => n.GetSpanOfFirstChild(s), 0, 5, 0, 5);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)]
public async Task GetSpanOfNextSiblingTest()
{
// Go from 'class' to 'Class1'
await TestNavigatorAsync("class Class1 { }", (n, s) => n.GetSpanOfNextSibling(s), 0, 5, 6, 6);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)]
public async Task GetSpanOfPreviousSiblingTest()
{
// Go from '{' to 'Class1'
await TestNavigatorAsync("class Class1 { }", (n, s) => n.GetSpanOfPreviousSibling(s), 13, 1, 6, 6);
}
}
}
| |
using System;
using System.Data;
using Csla;
using Csla.Data;
using SelfLoad.DataAccess;
using SelfLoad.DataAccess.ERCLevel;
namespace SelfLoad.Business.ERCLevel
{
/// <summary>
/// D06_Country (editable child object).<br/>
/// This is a generated base class of <see cref="D06_Country"/> business object.
/// </summary>
/// <remarks>
/// This class contains one child collection:<br/>
/// - <see cref="D07_RegionObjects"/> of type <see cref="D07_RegionColl"/> (1:M relation to <see cref="D08_Region"/>)<br/>
/// This class is an item of <see cref="D05_CountryColl"/> collection.
/// </remarks>
[Serializable]
public partial class D06_Country : BusinessBase<D06_Country>
{
#region Static Fields
private static int _lastID;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Country_ID"/> property.
/// </summary>
public static readonly PropertyInfo<int> Country_IDProperty = RegisterProperty<int>(p => p.Country_ID, "Countries ID");
/// <summary>
/// Gets the Countries ID.
/// </summary>
/// <value>The Countries ID.</value>
public int Country_ID
{
get { return GetProperty(Country_IDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="Country_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Country_NameProperty = RegisterProperty<string>(p => p.Country_Name, "Countries Name");
/// <summary>
/// Gets or sets the Countries Name.
/// </summary>
/// <value>The Countries Name.</value>
public string Country_Name
{
get { return GetProperty(Country_NameProperty); }
set { SetProperty(Country_NameProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="D07_Country_SingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<D07_Country_Child> D07_Country_SingleObjectProperty = RegisterProperty<D07_Country_Child>(p => p.D07_Country_SingleObject, "D07 Country Single Object", RelationshipTypes.Child);
/// <summary>
/// Gets the D07 Country Single Object ("self load" child property).
/// </summary>
/// <value>The D07 Country Single Object.</value>
public D07_Country_Child D07_Country_SingleObject
{
get { return GetProperty(D07_Country_SingleObjectProperty); }
private set { LoadProperty(D07_Country_SingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="D07_Country_ASingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<D07_Country_ReChild> D07_Country_ASingleObjectProperty = RegisterProperty<D07_Country_ReChild>(p => p.D07_Country_ASingleObject, "D07 Country ASingle Object", RelationshipTypes.Child);
/// <summary>
/// Gets the D07 Country ASingle Object ("self load" child property).
/// </summary>
/// <value>The D07 Country ASingle Object.</value>
public D07_Country_ReChild D07_Country_ASingleObject
{
get { return GetProperty(D07_Country_ASingleObjectProperty); }
private set { LoadProperty(D07_Country_ASingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="D07_RegionObjects"/> property.
/// </summary>
public static readonly PropertyInfo<D07_RegionColl> D07_RegionObjectsProperty = RegisterProperty<D07_RegionColl>(p => p.D07_RegionObjects, "D07 Region Objects", RelationshipTypes.Child);
/// <summary>
/// Gets the D07 Region Objects ("self load" child property).
/// </summary>
/// <value>The D07 Region Objects.</value>
public D07_RegionColl D07_RegionObjects
{
get { return GetProperty(D07_RegionObjectsProperty); }
private set { LoadProperty(D07_RegionObjectsProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="D06_Country"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="D06_Country"/> object.</returns>
internal static D06_Country NewD06_Country()
{
return DataPortal.CreateChild<D06_Country>();
}
/// <summary>
/// Factory method. Loads a <see cref="D06_Country"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="D06_Country"/> object.</returns>
internal static D06_Country GetD06_Country(SafeDataReader dr)
{
D06_Country obj = new D06_Country();
// 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="D06_Country"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public D06_Country()
{
// 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="D06_Country"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
LoadProperty(Country_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID));
LoadProperty(D07_Country_SingleObjectProperty, DataPortal.CreateChild<D07_Country_Child>());
LoadProperty(D07_Country_ASingleObjectProperty, DataPortal.CreateChild<D07_Country_ReChild>());
LoadProperty(D07_RegionObjectsProperty, DataPortal.CreateChild<D07_RegionColl>());
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="D06_Country"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Country_IDProperty, dr.GetInt32("Country_ID"));
LoadProperty(Country_NameProperty, dr.GetString("Country_Name"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Loads child objects.
/// </summary>
internal void FetchChildren()
{
LoadProperty(D07_Country_SingleObjectProperty, D07_Country_Child.GetD07_Country_Child(Country_ID));
LoadProperty(D07_Country_ASingleObjectProperty, D07_Country_ReChild.GetD07_Country_ReChild(Country_ID));
LoadProperty(D07_RegionObjectsProperty, D07_RegionColl.GetD07_RegionColl(Country_ID));
}
/// <summary>
/// Inserts a new <see cref="D06_Country"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(D04_SubContinent parent)
{
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var args = new DataPortalHookArgs();
OnInsertPre(args);
var dal = dalManager.GetProvider<ID06_CountryDal>();
using (BypassPropertyChecks)
{
int country_ID = -1;
dal.Insert(
parent.SubContinent_ID,
out country_ID,
Country_Name
);
LoadProperty(Country_IDProperty, country_ID);
}
OnInsertPost(args);
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="D06_Country"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update()
{
if (!IsDirty)
return;
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var args = new DataPortalHookArgs();
OnUpdatePre(args);
var dal = dalManager.GetProvider<ID06_CountryDal>();
using (BypassPropertyChecks)
{
dal.Update(
Country_ID,
Country_Name
);
}
OnUpdatePost(args);
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Self deletes the <see cref="D06_Country"/> object from database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf()
{
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var args = new DataPortalHookArgs();
// flushes all pending data operations
FieldManager.UpdateChildren(this);
OnDeletePre(args);
var dal = dalManager.GetProvider<ID06_CountryDal>();
using (BypassPropertyChecks)
{
dal.Delete(ReadProperty(Country_IDProperty));
}
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
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using GTANetworkAPI;
public struct RespawnablePickup
{
public int Hash;
public int Amount;
public int PickupTime;
public int RespawnTime;
public Vector3 Position;
}
public class Deathmatch : Script
{
public static List<Vector3> Spawns = new List<Vector3>
{
new Vector3(1482.36, 3587.45, 35.39),
new Vector3(1613.67, 3560.03, 35.42),
new Vector3(1533.44, 3581.24, 38.73),
new Vector3(1576.09, 3607.35, 38.73),
new Vector3(1596.88, 3590.43, 42.12)
};
public static List<WeaponHash> Weapons = new List<WeaponHash> { WeaponHash.MicroSMG, WeaponHash.PumpShotgun, WeaponHash.CarbineRifle };
public static Dictionary<Client, int> Killstreaks = new Dictionary<Client, int>();
public static Random Rand = new Random();
public static int KillTarget;
public Deathmatch()
{
NAPI.Server.SetAutoSpawnOnConnect(false);
NAPI.Server.SetAutoRespawnAfterDeath(false);
}
[ServerEvent(Event.MapChange)]
public void OnMapChange(string mapName, XmlGroup map)
{
Console.WriteLine("OnMapChange");
Spawns.Clear();
Weapons.Clear();
Killstreaks.Clear();
var spawnpoints = map.getElementsByType("spawnpoint");
foreach (var point in spawnpoints)
{
Spawns.Add(new Vector3(point.getElementData<float>("posX"), point.getElementData<float>("posY"), point.getElementData<float>("posZ")));
}
var availableGuns = map.getElementsByType("weapon");
foreach (var point in availableGuns)
{
Weapons.Add(NAPI.Util.WeaponNameToModel(point.getElementData<string>("model")));
}
NAPI.World.ResetIplList();
var neededInteriors = map.getElementsByType("ipl");
foreach (var point in neededInteriors)
{
NAPI.World.RequestIpl(point.getElementData<string>("name"));
}
foreach (var player in NAPI.Pools.GetAllPlayers())
{
var pBlip = NAPI.Exported.playerblips.getPlayerBlip(player);
NAPI.Blip.SetBlipSprite(pBlip, 1);
NAPI.Blip.SetBlipColor(pBlip, 0);
Spawn(player);
}
}
[ServerEvent(Event.ResourceStart)]
public void OnResourceStart()
{
foreach (var player in NAPI.Pools.GetAllPlayers())
{
Spawn(player);
NAPI.Data.SetEntityData(player.Handle, "dm_score", 0);
NAPI.Data.SetEntityData(player.Handle, "dm_deaths", 0);
NAPI.Data.SetEntityData(player.Handle, "dm_kills", 0);
NAPI.Data.SetEntityData(player.Handle, "dm_kdr", 0);
}
KillTarget = NAPI.Resource.GetSetting<int>(this, "victory_kills");
}
[ServerEvent(Event.ResourceStop)]
public void OnResourceStop()
{
foreach (var player in NAPI.Pools.GetAllPlayers())
{
var pBlip = NAPI.Exported.playerblips.getPlayerBlip(player);
NAPI.Blip.SetBlipSprite(pBlip, 1);
NAPI.Blip.SetBlipColor(pBlip, 0);
NAPI.Data.ResetEntityData(player.Handle, "dm_score");
NAPI.Data.ResetEntityData(player.Handle, "dm_deaths");
NAPI.Data.ResetEntityData(player.Handle, "dm_kills");
NAPI.Data.ResetEntityData(player.Handle, "dm_kdr");
}
}
[ServerEvent(Event.PlayerConnected)]
public void OnPlayerConnected(Client player)
{
NAPI.Data.SetEntityData(player.Handle, "dm_score", 0);
NAPI.Data.SetEntityData(player.Handle, "dm_deaths", 0);
NAPI.Data.SetEntityData(player.Handle, "dm_kills", 0);
NAPI.Data.SetEntityData(player.Handle, "dm_kdr", 0);
Spawn(player);
}
public void Spawn(Client player)
{
var randSpawn = Spawns[Rand.Next(Spawns.Count)];
NAPI.Player.SpawnPlayer(player, randSpawn);
NAPI.Player.RemoveAllPlayerWeapons(player);
Weapons.ForEach(gun => NAPI.Player.GivePlayerWeapon(player, gun, 500));
NAPI.Player.SetPlayerHealth(player, 100);
}
[ServerEvent(Event.PlayerDeath)]
public void OnPlayerDeath(Client player, NetHandle entitykiller, uint weapon)
{
Client killer = null;
if (!entitykiller.IsNull)
{
foreach (var ply in NAPI.Pools.GetAllPlayers())
{
if (ply.Handle != entitykiller) continue;
killer = ply;
break;
}
}
NAPI.Data.SetEntityData(player.Handle, "dm_score", NAPI.Data.GetEntitySharedData(player.Handle, "dm_score") - 1);
NAPI.Data.SetEntityData(player.Handle, "dm_deaths", NAPI.Data.GetEntitySharedData(player.Handle, "dm_deaths") + 1);
NAPI.Data.SetEntityData(player.Handle, "dm_kdr", NAPI.Data.GetEntitySharedData(player.Handle, "dm_kills") / (float)NAPI.Data.GetEntitySharedData(player.Handle, "dm_deaths"));
if (killer != null)
{
NAPI.Data.SetEntityData(killer.Handle, "dm_kills", NAPI.Data.GetEntitySharedData(killer.Handle, "dm_kills") + 1);
NAPI.Data.SetEntityData(killer.Handle, "dm_score", NAPI.Data.GetEntitySharedData(killer.Handle, "dm_score") + 1);
if (NAPI.Data.GetEntitySharedData(killer.Handle, "dm_deaths") != 0)
{
NAPI.Data.SetEntityData(killer.Handle, "dm_kdr", NAPI.Data.GetEntitySharedData(killer.Handle, "dm_kills") / (float)NAPI.Data.GetEntitySharedData(killer.Handle, "dm_deaths"));
}
if (NAPI.Data.GetEntitySharedData(killer.Handle, "dm_kills") >= KillTarget)
{
NAPI.Chat.SendChatMessageToAll($"~b~~h~{killer.Name}~h~~w~ has won the round with ~h~{KillTarget}~h~ kills and {NAPI.Data.GetEntitySharedData(player.Handle, "dm_deaths")} deaths!");
//API.Exported.mapcycler.endRound();
}
if (Killstreaks.ContainsKey(killer))
{
Killstreaks[killer]++;
if (Killstreaks[killer] >= 3)
{
var kBlip = NAPI.Exported.playerblips.getPlayerBlip(killer);
NAPI.Blip.SetBlipSprite(kBlip, 303);
NAPI.Blip.SetBlipColor(kBlip, 1);
NAPI.Chat.SendChatMessageToAll($"~b~{killer.Name}~w~ is on a killstreak! ~r~{Killstreaks[killer]}~w~ kills and counting!");
switch (Killstreaks[killer])
{
case 4:
NAPI.Player.SetPlayerHealth(killer, Math.Min(100, NAPI.Player.GetPlayerHealth(killer) + 25));
NAPI.Chat.SendChatMessageToPlayer(killer, "~g~Health bonus!");
break;
case 6:
NAPI.Player.SetPlayerHealth(killer, Math.Min(100, NAPI.Player.GetPlayerHealth(killer) + 50));
NAPI.Chat.SendChatMessageToPlayer(killer, "~g~Health bonus!");
break;
case 8:
NAPI.Player.SetPlayerHealth(killer, Math.Min(100, NAPI.Player.GetPlayerHealth(killer) + 75));
NAPI.Player.SetPlayerArmor(killer, Math.Min(100, NAPI.Player.GetPlayerArmor(killer) + 25));
NAPI.Chat.SendChatMessageToPlayer(killer, "~g~Health and armor bonus!");
break;
case 12:
NAPI.Player.SetPlayerHealth(killer, Math.Min(100, NAPI.Player.GetPlayerHealth(killer) + 75));
NAPI.Player.SetPlayerArmor(killer, Math.Min(100, NAPI.Player.GetPlayerArmor(killer) + 50));
NAPI.Chat.SendChatMessageToPlayer(killer, "~g~Health and armor bonus!");
break;
default:
if (Killstreaks[killer] >= 16 && Killstreaks[killer] % 4 == 0)
{
NAPI.Player.SetPlayerHealth(killer, Math.Min(100, NAPI.Player.GetPlayerHealth(killer) + 75));
NAPI.Player.SetPlayerArmor(killer, Math.Min(100, NAPI.Player.GetPlayerArmor(killer) + 75));
NAPI.Chat.SendChatMessageToPlayer(killer, "~g~Health and armor bonus!");
}
break;
}
}
}
else
{
Killstreaks.Add(killer, 1);
}
}
var pBlip = NAPI.Exported.playerblips.getPlayerBlip(player);
if (Killstreaks.ContainsKey(player))
{
if (Killstreaks[player] >= 3 && killer != null)
{
NAPI.Chat.SendChatMessageToAll($"~b~{killer.Name}~w~ ruined ~r~{player.Name}~w~'s killstreak!");
NAPI.Blip.SetBlipColor(pBlip, 0);
NAPI.Blip.SetBlipSprite(pBlip, 1);
}
Killstreaks[player] = 0;
}
else
{
Killstreaks.Add(player, 0);
}
NAPI.Blip.SetBlipSprite(pBlip, 274);
Spawn(player);
}
}
| |
//
// 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.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Hyak.Common.Internals;
using Microsoft.Azure;
using Microsoft.Azure.Management.Compute;
using Microsoft.Azure.Management.Compute.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Compute
{
/// <summary>
/// Operations for managing the availability sets in compute management.
/// </summary>
internal partial class AvailabilitySetOperations : IServiceOperations<ComputeManagementClient>, IAvailabilitySetOperations
{
/// <summary>
/// Initializes a new instance of the AvailabilitySetOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal AvailabilitySetOperations(ComputeManagementClient client)
{
this._client = client;
}
private ComputeManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Compute.ComputeManagementClient.
/// </summary>
public ComputeManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// The operation to create or update the availability set.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Create Availability Set
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Create Availability Set operation response.
/// </returns>
public async Task<AvailabilitySetCreateOrUpdateResponse> CreateOrUpdateAsync(string resourceGroupName, AvailabilitySet parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Location == null)
{
throw new ArgumentNullException("parameters.Location");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Compute";
url = url + "/availabilitySets/";
if (parameters.Name != null)
{
url = url + Uri.EscapeDataString(parameters.Name);
}
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-06-15");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject availabilitySetJsonValue = new JObject();
requestDoc = availabilitySetJsonValue;
JObject propertiesValue = new JObject();
availabilitySetJsonValue["properties"] = propertiesValue;
if (parameters.PlatformUpdateDomainCount != null)
{
propertiesValue["platformUpdateDomainCount"] = parameters.PlatformUpdateDomainCount.Value;
}
if (parameters.PlatformFaultDomainCount != null)
{
propertiesValue["platformFaultDomainCount"] = parameters.PlatformFaultDomainCount.Value;
}
if (parameters.VirtualMachinesReferences != null)
{
if (parameters.VirtualMachinesReferences is ILazyCollection == false || ((ILazyCollection)parameters.VirtualMachinesReferences).IsInitialized)
{
JArray virtualMachinesArray = new JArray();
foreach (VirtualMachineReference virtualMachinesItem in parameters.VirtualMachinesReferences)
{
JObject virtualMachineReferenceValue = new JObject();
virtualMachinesArray.Add(virtualMachineReferenceValue);
if (virtualMachinesItem.ReferenceUri != null)
{
virtualMachineReferenceValue["id"] = virtualMachinesItem.ReferenceUri;
}
}
propertiesValue["virtualMachines"] = virtualMachinesArray;
}
}
if (parameters.Statuses != null)
{
if (parameters.Statuses is ILazyCollection == false || ((ILazyCollection)parameters.Statuses).IsInitialized)
{
JArray statusesArray = new JArray();
foreach (InstanceViewStatus statusesItem in parameters.Statuses)
{
JObject instanceViewStatusValue = new JObject();
statusesArray.Add(instanceViewStatusValue);
if (statusesItem.Code != null)
{
instanceViewStatusValue["code"] = statusesItem.Code;
}
if (statusesItem.Level != null)
{
instanceViewStatusValue["level"] = statusesItem.Level;
}
if (statusesItem.DisplayStatus != null)
{
instanceViewStatusValue["displayStatus"] = statusesItem.DisplayStatus;
}
if (statusesItem.Message != null)
{
instanceViewStatusValue["message"] = statusesItem.Message;
}
if (statusesItem.Time != null)
{
instanceViewStatusValue["time"] = statusesItem.Time.Value;
}
}
propertiesValue["statuses"] = statusesArray;
}
}
if (parameters.Id != null)
{
availabilitySetJsonValue["id"] = parameters.Id;
}
if (parameters.Name != null)
{
availabilitySetJsonValue["name"] = parameters.Name;
}
if (parameters.Type != null)
{
availabilitySetJsonValue["type"] = parameters.Type;
}
availabilitySetJsonValue["location"] = parameters.Location;
if (parameters.Tags != null)
{
JObject tagsDictionary = new JObject();
foreach (KeyValuePair<string, string> pair in parameters.Tags)
{
string tagsKey = pair.Key;
string tagsValue = pair.Value;
tagsDictionary[tagsKey] = tagsValue;
}
availabilitySetJsonValue["tags"] = tagsDictionary;
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AvailabilitySetCreateOrUpdateResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new AvailabilitySetCreateOrUpdateResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
AvailabilitySet availabilitySetInstance = new AvailabilitySet();
result.AvailabilitySet = availabilitySetInstance;
JToken propertiesValue2 = responseDoc["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
JToken platformUpdateDomainCountValue = propertiesValue2["platformUpdateDomainCount"];
if (platformUpdateDomainCountValue != null && platformUpdateDomainCountValue.Type != JTokenType.Null)
{
int platformUpdateDomainCountInstance = ((int)platformUpdateDomainCountValue);
availabilitySetInstance.PlatformUpdateDomainCount = platformUpdateDomainCountInstance;
}
JToken platformFaultDomainCountValue = propertiesValue2["platformFaultDomainCount"];
if (platformFaultDomainCountValue != null && platformFaultDomainCountValue.Type != JTokenType.Null)
{
int platformFaultDomainCountInstance = ((int)platformFaultDomainCountValue);
availabilitySetInstance.PlatformFaultDomainCount = platformFaultDomainCountInstance;
}
JToken virtualMachinesArray2 = propertiesValue2["virtualMachines"];
if (virtualMachinesArray2 != null && virtualMachinesArray2.Type != JTokenType.Null)
{
foreach (JToken virtualMachinesValue in ((JArray)virtualMachinesArray2))
{
VirtualMachineReference virtualMachineReferenceInstance = new VirtualMachineReference();
availabilitySetInstance.VirtualMachinesReferences.Add(virtualMachineReferenceInstance);
JToken idValue = virtualMachinesValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
virtualMachineReferenceInstance.ReferenceUri = idInstance;
}
}
}
JToken statusesArray2 = propertiesValue2["statuses"];
if (statusesArray2 != null && statusesArray2.Type != JTokenType.Null)
{
foreach (JToken statusesValue in ((JArray)statusesArray2))
{
InstanceViewStatus instanceViewStatusInstance = new InstanceViewStatus();
availabilitySetInstance.Statuses.Add(instanceViewStatusInstance);
JToken codeValue = statusesValue["code"];
if (codeValue != null && codeValue.Type != JTokenType.Null)
{
string codeInstance = ((string)codeValue);
instanceViewStatusInstance.Code = codeInstance;
}
JToken levelValue = statusesValue["level"];
if (levelValue != null && levelValue.Type != JTokenType.Null)
{
string levelInstance = ((string)levelValue);
instanceViewStatusInstance.Level = levelInstance;
}
JToken displayStatusValue = statusesValue["displayStatus"];
if (displayStatusValue != null && displayStatusValue.Type != JTokenType.Null)
{
string displayStatusInstance = ((string)displayStatusValue);
instanceViewStatusInstance.DisplayStatus = displayStatusInstance;
}
JToken messageValue = statusesValue["message"];
if (messageValue != null && messageValue.Type != JTokenType.Null)
{
string messageInstance = ((string)messageValue);
instanceViewStatusInstance.Message = messageInstance;
}
JToken timeValue = statusesValue["time"];
if (timeValue != null && timeValue.Type != JTokenType.Null)
{
DateTimeOffset timeInstance = ((DateTimeOffset)timeValue);
instanceViewStatusInstance.Time = timeInstance;
}
}
}
}
JToken idValue2 = responseDoc["id"];
if (idValue2 != null && idValue2.Type != JTokenType.Null)
{
string idInstance2 = ((string)idValue2);
availabilitySetInstance.Id = idInstance2;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
availabilitySetInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
availabilitySetInstance.Type = typeInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
availabilitySetInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey2 = ((string)property.Name);
string tagsValue2 = ((string)property.Value);
availabilitySetInstance.Tags.Add(tagsKey2, tagsValue2);
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The operation to delete the availability set.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='availabilitySetName'>
/// Required. The name of the availability set.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string availabilitySetName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (availabilitySetName == null)
{
throw new ArgumentNullException("availabilitySetName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("availabilitySetName", availabilitySetName);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Compute";
url = url + "/availabilitySets/";
url = url + Uri.EscapeDataString(availabilitySetName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-06-15");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The operation to get the availability set.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='availabilitySetName'>
/// Required. The name of the availability set.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// GET Availability Set operation response.
/// </returns>
public async Task<AvailabilitySetGetResponse> GetAsync(string resourceGroupName, string availabilitySetName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (availabilitySetName == null)
{
throw new ArgumentNullException("availabilitySetName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("availabilitySetName", availabilitySetName);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Compute";
url = url + "/availabilitySets/";
url = url + Uri.EscapeDataString(availabilitySetName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-06-15");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AvailabilitySetGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new AvailabilitySetGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
AvailabilitySet availabilitySetInstance = new AvailabilitySet();
result.AvailabilitySet = availabilitySetInstance;
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
JToken platformUpdateDomainCountValue = propertiesValue["platformUpdateDomainCount"];
if (platformUpdateDomainCountValue != null && platformUpdateDomainCountValue.Type != JTokenType.Null)
{
int platformUpdateDomainCountInstance = ((int)platformUpdateDomainCountValue);
availabilitySetInstance.PlatformUpdateDomainCount = platformUpdateDomainCountInstance;
}
JToken platformFaultDomainCountValue = propertiesValue["platformFaultDomainCount"];
if (platformFaultDomainCountValue != null && platformFaultDomainCountValue.Type != JTokenType.Null)
{
int platformFaultDomainCountInstance = ((int)platformFaultDomainCountValue);
availabilitySetInstance.PlatformFaultDomainCount = platformFaultDomainCountInstance;
}
JToken virtualMachinesArray = propertiesValue["virtualMachines"];
if (virtualMachinesArray != null && virtualMachinesArray.Type != JTokenType.Null)
{
foreach (JToken virtualMachinesValue in ((JArray)virtualMachinesArray))
{
VirtualMachineReference virtualMachineReferenceInstance = new VirtualMachineReference();
availabilitySetInstance.VirtualMachinesReferences.Add(virtualMachineReferenceInstance);
JToken idValue = virtualMachinesValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
virtualMachineReferenceInstance.ReferenceUri = idInstance;
}
}
}
JToken statusesArray = propertiesValue["statuses"];
if (statusesArray != null && statusesArray.Type != JTokenType.Null)
{
foreach (JToken statusesValue in ((JArray)statusesArray))
{
InstanceViewStatus instanceViewStatusInstance = new InstanceViewStatus();
availabilitySetInstance.Statuses.Add(instanceViewStatusInstance);
JToken codeValue = statusesValue["code"];
if (codeValue != null && codeValue.Type != JTokenType.Null)
{
string codeInstance = ((string)codeValue);
instanceViewStatusInstance.Code = codeInstance;
}
JToken levelValue = statusesValue["level"];
if (levelValue != null && levelValue.Type != JTokenType.Null)
{
string levelInstance = ((string)levelValue);
instanceViewStatusInstance.Level = levelInstance;
}
JToken displayStatusValue = statusesValue["displayStatus"];
if (displayStatusValue != null && displayStatusValue.Type != JTokenType.Null)
{
string displayStatusInstance = ((string)displayStatusValue);
instanceViewStatusInstance.DisplayStatus = displayStatusInstance;
}
JToken messageValue = statusesValue["message"];
if (messageValue != null && messageValue.Type != JTokenType.Null)
{
string messageInstance = ((string)messageValue);
instanceViewStatusInstance.Message = messageInstance;
}
JToken timeValue = statusesValue["time"];
if (timeValue != null && timeValue.Type != JTokenType.Null)
{
DateTimeOffset timeInstance = ((DateTimeOffset)timeValue);
instanceViewStatusInstance.Time = timeInstance;
}
}
}
}
JToken idValue2 = responseDoc["id"];
if (idValue2 != null && idValue2.Type != JTokenType.Null)
{
string idInstance2 = ((string)idValue2);
availabilitySetInstance.Id = idInstance2;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
availabilitySetInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
availabilitySetInstance.Type = typeInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
availabilitySetInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
availabilitySetInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The operation to list the availability sets.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The List Availability Set operation response.
/// </returns>
public async Task<AvailabilitySetListResponse> ListAsync(string resourceGroupName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Compute";
url = url + "/availabilitySets";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-06-15");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AvailabilitySetListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new AvailabilitySetListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
AvailabilitySet availabilitySetJsonInstance = new AvailabilitySet();
result.AvailabilitySets.Add(availabilitySetJsonInstance);
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
JToken platformUpdateDomainCountValue = propertiesValue["platformUpdateDomainCount"];
if (platformUpdateDomainCountValue != null && platformUpdateDomainCountValue.Type != JTokenType.Null)
{
int platformUpdateDomainCountInstance = ((int)platformUpdateDomainCountValue);
availabilitySetJsonInstance.PlatformUpdateDomainCount = platformUpdateDomainCountInstance;
}
JToken platformFaultDomainCountValue = propertiesValue["platformFaultDomainCount"];
if (platformFaultDomainCountValue != null && platformFaultDomainCountValue.Type != JTokenType.Null)
{
int platformFaultDomainCountInstance = ((int)platformFaultDomainCountValue);
availabilitySetJsonInstance.PlatformFaultDomainCount = platformFaultDomainCountInstance;
}
JToken virtualMachinesArray = propertiesValue["virtualMachines"];
if (virtualMachinesArray != null && virtualMachinesArray.Type != JTokenType.Null)
{
foreach (JToken virtualMachinesValue in ((JArray)virtualMachinesArray))
{
VirtualMachineReference virtualMachineReferenceInstance = new VirtualMachineReference();
availabilitySetJsonInstance.VirtualMachinesReferences.Add(virtualMachineReferenceInstance);
JToken idValue = virtualMachinesValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
virtualMachineReferenceInstance.ReferenceUri = idInstance;
}
}
}
JToken statusesArray = propertiesValue["statuses"];
if (statusesArray != null && statusesArray.Type != JTokenType.Null)
{
foreach (JToken statusesValue in ((JArray)statusesArray))
{
InstanceViewStatus instanceViewStatusInstance = new InstanceViewStatus();
availabilitySetJsonInstance.Statuses.Add(instanceViewStatusInstance);
JToken codeValue = statusesValue["code"];
if (codeValue != null && codeValue.Type != JTokenType.Null)
{
string codeInstance = ((string)codeValue);
instanceViewStatusInstance.Code = codeInstance;
}
JToken levelValue = statusesValue["level"];
if (levelValue != null && levelValue.Type != JTokenType.Null)
{
string levelInstance = ((string)levelValue);
instanceViewStatusInstance.Level = levelInstance;
}
JToken displayStatusValue = statusesValue["displayStatus"];
if (displayStatusValue != null && displayStatusValue.Type != JTokenType.Null)
{
string displayStatusInstance = ((string)displayStatusValue);
instanceViewStatusInstance.DisplayStatus = displayStatusInstance;
}
JToken messageValue = statusesValue["message"];
if (messageValue != null && messageValue.Type != JTokenType.Null)
{
string messageInstance = ((string)messageValue);
instanceViewStatusInstance.Message = messageInstance;
}
JToken timeValue = statusesValue["time"];
if (timeValue != null && timeValue.Type != JTokenType.Null)
{
DateTimeOffset timeInstance = ((DateTimeOffset)timeValue);
instanceViewStatusInstance.Time = timeInstance;
}
}
}
}
JToken idValue2 = valueValue["id"];
if (idValue2 != null && idValue2.Type != JTokenType.Null)
{
string idInstance2 = ((string)idValue2);
availabilitySetJsonInstance.Id = idInstance2;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
availabilitySetJsonInstance.Name = nameInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
availabilitySetJsonInstance.Type = typeInstance;
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
availabilitySetJsonInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
availabilitySetJsonInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Lists virtual-machine-sizes available to be used for an
/// availability set.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='availabilitySetName'>
/// Required. The name of the availability set.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The List Virtual Machine operation response.
/// </returns>
public async Task<VirtualMachineSizeListResponse> ListAvailableSizesAsync(string resourceGroupName, string availabilitySetName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (availabilitySetName == null)
{
throw new ArgumentNullException("availabilitySetName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("availabilitySetName", availabilitySetName);
TracingAdapter.Enter(invocationId, this, "ListAvailableSizesAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Compute";
url = url + "/availabilitySets/";
url = url + Uri.EscapeDataString(availabilitySetName);
url = url + "/vmSizes";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-06-15");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
VirtualMachineSizeListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new VirtualMachineSizeListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
VirtualMachineSize virtualMachineSizeInstance = new VirtualMachineSize();
result.VirtualMachineSizes.Add(virtualMachineSizeInstance);
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
virtualMachineSizeInstance.Name = nameInstance;
}
JToken numberOfCoresValue = valueValue["numberOfCores"];
if (numberOfCoresValue != null && numberOfCoresValue.Type != JTokenType.Null)
{
int numberOfCoresInstance = ((int)numberOfCoresValue);
virtualMachineSizeInstance.NumberOfCores = numberOfCoresInstance;
}
JToken osDiskSizeInMBValue = valueValue["osDiskSizeInMB"];
if (osDiskSizeInMBValue != null && osDiskSizeInMBValue.Type != JTokenType.Null)
{
int osDiskSizeInMBInstance = ((int)osDiskSizeInMBValue);
virtualMachineSizeInstance.OSDiskSizeInMB = osDiskSizeInMBInstance;
}
JToken resourceDiskSizeInMBValue = valueValue["resourceDiskSizeInMB"];
if (resourceDiskSizeInMBValue != null && resourceDiskSizeInMBValue.Type != JTokenType.Null)
{
int resourceDiskSizeInMBInstance = ((int)resourceDiskSizeInMBValue);
virtualMachineSizeInstance.ResourceDiskSizeInMB = resourceDiskSizeInMBInstance;
}
JToken memoryInMBValue = valueValue["memoryInMB"];
if (memoryInMBValue != null && memoryInMBValue.Type != JTokenType.Null)
{
int memoryInMBInstance = ((int)memoryInMBValue);
virtualMachineSizeInstance.MemoryInMB = memoryInMBInstance;
}
JToken maxDataDiskCountValue = valueValue["maxDataDiskCount"];
if (maxDataDiskCountValue != null && maxDataDiskCountValue.Type != JTokenType.Null)
{
int maxDataDiskCountInstance = ((int)maxDataDiskCountValue);
virtualMachineSizeInstance.MaxDataDiskCount = maxDataDiskCountInstance;
}
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using CpsDbHelper.Extensions;
using CpsDbHelper.Utils;
namespace CpsDbHelper
{
public class DataReaderHelper : DbHelper<DataReaderHelper>
{
private const string DefaultKey = "__default";
private readonly IDictionary<string, object> _results = new Dictionary<string, object>();
private readonly IDictionary<string, Func<IDataReader, DataReaderHelper, object>> _processDelegates = new Dictionary<string, Func<IDataReader, DataReaderHelper, object>>();
private readonly IDictionary<string, Action<IDataReader>> _preActions = new Dictionary<string, Action<IDataReader>>();
public DataReaderHelper(string text, string connectionString, IAdoNetProviderFactory provider)
: base(text, connectionString, provider)
{
}
public DataReaderHelper(string text, IDbConnection connection, IDbTransaction transaction, IAdoNetProviderFactory provider)
: base(text, connection, transaction, provider)
{
}
protected override void BeginExecute(IDbCommand cmd)
{
using (var reader = cmd.ExecuteReader())
{
ProcessReader(reader);
}
}
protected override async Task BeginExecuteAsync(IDbCommand cmd)
{
var command = cmd as DbCommand;
if (command != null)
{
using (var reader = await command.ExecuteReaderAsync())
{
ProcessReader(reader);
}
}
else
{
throw new NotSupportedException("The async operation is not supported by this data provider");
}
}
/// <summary>
/// Define an action that executes right after the sqlCommand.execute() and before looping through the DataReader
/// </summary>
/// <param name="action">the action to apply to the DataReader</param>
/// <param name="resultKey">The result set key which matches the define/map result method. the action will be applied before the key specified result set</param>
/// <returns></returns>
public virtual DataReaderHelper PreProcessResult(Action<IDataReader> action, string resultKey = DefaultKey)
{
_preActions.Add(resultKey, action);
return this;
}
/// <summary>
/// Define a result, use the reader to process result and return it to helper, later use the result key to get the result
/// </summary>
/// <param name="fun">the function that applied to the DataReader to process the result. the return value is the final result</param>
/// <param name="resultKey">the identifier to find the reuslt later</param>
/// <returns></returns>
public DataReaderHelper DefineResult(Func<IDataReader, DataReaderHelper, object> fun, string resultKey = DefaultKey)
{
_processDelegates.Add(resultKey, fun);
return this;
}
/// <summary>
/// Define a result, use the reader to process result and return it to helper, later use the result key to get the result
/// </summary>
/// <param name="fun">the function that applied to the DataReader to process the result. the return value is the final result</param>
/// <param name="resultKey">the identifier to find the reuslt later</param>
/// <returns></returns>
public DataReaderHelper DefineResult(Func<IDataReader, object> fun, string resultKey = DefaultKey)
{
_processDelegates.Add(resultKey, (reader, helper) => fun(reader));
return this;
}
/// <summary>
/// Define a result, use the reader to process result and return it to helper, later use the result key to get the result
/// </summary>
/// <param name="fun">the function that applied to the DataReader to process the result. the return value is the item of a list, the final result is the list of the item</param>
/// <param name="resultKey">the identifier to find the reuslt later</param>
/// <returns></returns>
public DataReaderHelper DefineListResult<T>(Func<IDataReader, DataReaderHelper, T> fun, string resultKey = DefaultKey)
{
_processDelegates.Add(resultKey, (reader, helper) => ProcessListResult(reader, fun));
return this;
}
/// <summary>
/// Define a result, use the reader to process result and return it to helper, later use the result key to get the result
/// </summary>
/// <param name="fun">the function that applied to the DataReader to process the result. the return value is the item of a list, the final result is the list of the item</param>
/// <param name="resultKey">the identifier to find the reuslt later</param>
/// <returns></returns>
public DataReaderHelper DefineListResult<T>(Func<IDataReader, T> fun, string resultKey = DefaultKey)
{
_processDelegates.Add(resultKey, (reader, helper) => ProcessListResult(reader, (rea, hel) => fun(rea)));
return this;
}
/// <summary>
/// Start mapping TValue with the result set, the row will be aligned with TValue in later operations
/// </summary>
/// <typeparam name="TValue">The type of the result which will be produced after proceesing this set of reader result</typeparam>
/// <param name="resultKey">the identifier to find the reuslt with helper.GetResult()</param>
/// <returns></returns>
public DataReaderMapper<TValue> BeginMapResult<TValue>(string resultKey = DefaultKey)
{
return new DataReaderMapper<TValue>(this, resultKey);
}
/// <summary>
/// Auto map property names with column names to TValue from the result set
/// </summary>
/// <typeparam name="TValue">The type of the result which will be produced after proceesing this set of reader result</typeparam>
/// <param name="resultKey">the identifier to find the reuslt with helper.GetResult()</param>
/// <returns></returns>
public DataReaderHelper AutoMapResult<TValue>(string resultKey = DefaultKey)
{
return new DataReaderMapper<TValue>(this, resultKey).AutoMap().FinishMap();
}
/// <summary>
/// Use this method to map the only one column from the reuslt set to a simple type
/// </summary>
/// <typeparam name="TValue">a C# simple type which the column's value will be converted to</typeparam>
/// <param name="columnName">the column name of the reuslt set</param>
/// <param name="resultKey">the identifier to find the reuslt with helper.GetResult()</param>
/// <returns></returns>
public DataReaderHelper DefineBasicTypeListResult<TValue>(string columnName, string resultKey = DefaultKey)
{
_processDelegates.Add(resultKey, (reader, helper) =>
{
var ordinal = reader.GetOrdinal(columnName);
var ret = new List<TValue>();
while (reader.Read())
{
ret.Add(reader.Get<TValue>(ordinal));
}
return ret;
});
return this;
}
/// <summary>
/// Get the result after Execute() is called.
/// previous DefineResult will return the return value of the function passed in
/// DefineListResult<TValue>/MapResult<TValue>/AutoMapResult<TValue> will need to use IList<TValue> to retrieve the result
/// </summary>
/// <typeparam name="T">the type of the result to cast to</typeparam>
/// <param name="key">The key used to define result</param>
/// <returns></returns>
public DataReaderHelper GetResult<T>(out T result, string key = DefaultKey)
{
result = (T)_results[key];
return this;
}
/// <summary>
/// Get the result after Execute() is called.
/// previous DefineResult will return the return value of the function passed in
/// DefineListResult<TValue>/MapResult<TValue>/AutoMapResult<TValue> will need to use IList<TValue> to retrieve the result
/// </summary>
/// <typeparam name="T">the type of the result to cast to</typeparam>
/// <param name="key">The key used to define result</param>
/// <returns></returns>
public T GetResult<T>(string key = DefaultKey)
{
return (T)_results[key];
}
/// <summary>
/// Get the result after Execute() is called.
/// returns List<T> previous defined by DefineListResult<T>/MapResult<T>/AutoMapResult<T>
/// </summary>
/// <typeparam name="T">the type of the result to cast to</typeparam>
/// <param name="key">The key used to define result</param>
/// <returns></returns>
public DataReaderHelper GetResultCollection<T>(out IList<T> result, string key = DefaultKey)
{
result = (IList<T>)_results[key];
return this;
}
/// <summary>
/// Get the result after Execute() is called.
/// </summary>
/// <typeparam name="T">the type of the result to cast to</typeparam>
/// <param name="key">The key used to define result</param>
/// <returns>List<T> previous defined by DefineListResult<T>/MapResult<T>/AutoMapResult<T></returns>
public IList<T> GetResultCollection<T>(string key = DefaultKey)
{
return (IList<T>)_results[key];
}
private object ProcessListResult<T>(IDataReader reader, Func<IDataReader, DataReaderHelper, T> fun)
{
var ret = new List<T>();
while (reader.Read())
{
ret.Add(fun(reader, this));
}
return ret;
}
private void ProcessReader(IDataReader reader)
{
var first = true;
foreach (var del in _processDelegates)
{
if (!first)
{
if (!reader.NextResult())
{
return;
}
}
if (_preActions.ContainsKey(del.Key))
{
_preActions[del.Key](reader);
}
var res = del.Value(reader, this);
_results.Add(del.Key, res);
first = false;
}
}
}
public static partial class FactoryExtensions
{
public static DataReaderHelper BeginReader(this DbHelperFactory factory, string text)
{
if (factory.CheckExistingConnection())
{
return new DataReaderHelper(text, factory.DbConnection, factory.DbTransaction, factory.Provider);
}
return new DataReaderHelper(text, factory.ConnectionString, factory.Provider);
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King; 2014 Extesla, 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.
#endregion
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.Reflection;
using OpenGamingLibrary.Collections;
using OpenGamingLibrary.Json.Utilities;
using System.Collections;
#if NET20
using OpenGamingLibrary.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace OpenGamingLibrary.Json.Serialization
{
/// <summary>
/// Contract details for a <see cref="Type"/> used by the <see cref="JsonSerializer"/>.
/// </summary>
public class JsonArrayContract : JsonContainerContract
{
/// <summary>
/// Gets the <see cref="Type"/> of the collection items.
/// </summary>
/// <value>The <see cref="Type"/> of the collection items.</value>
public Type CollectionItemType { get; private set; }
/// <summary>
/// Gets a value indicating whether the collection type is a multidimensional array.
/// </summary>
/// <value><c>true</c> if the collection type is a multidimensional array; otherwise, <c>false</c>.</value>
public bool IsMultidimensionalArray { get; private set; }
private readonly Type _genericCollectionDefinitionType;
private Type _genericWrapperType;
private ObjectConstructor<object> _genericWrapperCreator;
private Func<object> _genericTemporaryCollectionCreator;
internal bool IsArray { get; private set; }
internal bool ShouldCreateWrapper { get; private set; }
internal bool CanDeserialize { get; private set; }
private readonly ConstructorInfo _parametrizedConstructor;
private ObjectConstructor<object> _parametrizedCreator;
internal ObjectConstructor<object> ParametrizedCreator
{
get
{
if (_parametrizedCreator == null)
_parametrizedCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParametrizedConstructor(_parametrizedConstructor);
return _parametrizedCreator;
}
}
internal bool HasParametrizedCreator
{
get { return _parametrizedCreator != null || _parametrizedConstructor != null; }
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonArrayContract"/> class.
/// </summary>
/// <param name="underlyingType">The underlying type for the contract.</param>
public JsonArrayContract(Type underlyingType)
: base(underlyingType)
{
ContractType = JsonContractType.Array;
IsArray = CreatedType.IsArray;
bool canDeserialize;
Type tempCollectionType;
if (IsArray)
{
CollectionItemType = ReflectionUtils.GetCollectionItemType(UnderlyingType);
IsReadOnlyOrFixedSize = true;
_genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType);
canDeserialize = true;
IsMultidimensionalArray = (IsArray && UnderlyingType.GetArrayRank() > 1);
}
else if (typeof(IList).IsAssignableFrom(underlyingType))
{
if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(ICollection<>), out _genericCollectionDefinitionType))
CollectionItemType = _genericCollectionDefinitionType.GetGenericArguments()[0];
else
CollectionItemType = ReflectionUtils.GetCollectionItemType(underlyingType);
if (underlyingType == typeof(IList))
CreatedType = typeof(List<object>);
if (CollectionItemType != null)
_parametrizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType);
IsReadOnlyOrFixedSize = ReflectionUtils.InheritsGenericDefinition(underlyingType, typeof(ReadOnlyCollection<>));
canDeserialize = true;
}
else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(ICollection<>), out _genericCollectionDefinitionType))
{
CollectionItemType = _genericCollectionDefinitionType.GetGenericArguments()[0];
if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(ICollection<>))
|| ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IList<>)))
CreatedType = typeof(List<>).MakeGenericType(CollectionItemType);
#if !(NET20 || NET35 || PORTABLE40)
if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(ISet<>)))
CreatedType = typeof(HashSet<>).MakeGenericType(CollectionItemType);
#endif
_parametrizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType);
canDeserialize = true;
ShouldCreateWrapper = true;
}
else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IEnumerable<>), out tempCollectionType))
{
CollectionItemType = tempCollectionType.GetGenericArguments()[0];
if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IEnumerable<>)))
CreatedType = typeof(List<>).MakeGenericType(CollectionItemType);
_parametrizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType);
if (underlyingType.IsGenericType() && underlyingType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
{
_genericCollectionDefinitionType = tempCollectionType;
IsReadOnlyOrFixedSize = false;
ShouldCreateWrapper = false;
canDeserialize = true;
}
else
{
_genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType);
IsReadOnlyOrFixedSize = true;
ShouldCreateWrapper = true;
canDeserialize = HasParametrizedCreator;
}
}
else
{
// types that implement IEnumerable and nothing else
canDeserialize = false;
ShouldCreateWrapper = true;
}
CanDeserialize = canDeserialize;
#if (NET20 || NET35)
if (CollectionItemType != null && ReflectionUtils.IsNullableType(CollectionItemType))
{
// bug in .NET 2.0 & 3.5 that List<Nullable<T>> throws an error when adding null via IList.Add(object)
// wrapper will handle calling Add(T) instead
if (ReflectionUtils.InheritsGenericDefinition(CreatedType, typeof(List<>), out tempCollectionType)
|| (IsArray && !IsMultidimensionalArray))
{
ShouldCreateWrapper = true;
}
}
#endif
}
internal IWrappedCollection CreateWrapper(object list)
{
if (_genericWrapperCreator == null)
{
_genericWrapperType = typeof(CollectionWrapper<>).MakeGenericType(CollectionItemType);
Type constructorArgument;
if (ReflectionUtils.InheritsGenericDefinition(_genericCollectionDefinitionType, typeof(List<>))
|| _genericCollectionDefinitionType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
constructorArgument = typeof(ICollection<>).MakeGenericType(CollectionItemType);
else
constructorArgument = _genericCollectionDefinitionType;
ConstructorInfo genericWrapperConstructor = _genericWrapperType.GetConstructor(new[] { constructorArgument });
_genericWrapperCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParametrizedConstructor(genericWrapperConstructor);
}
return (IWrappedCollection)_genericWrapperCreator(list);
}
internal IList CreateTemporaryCollection()
{
if (_genericTemporaryCollectionCreator == null)
{
// multidimensional array will also have array instances in it
Type collectionItemType = (IsMultidimensionalArray) ? typeof(object) : CollectionItemType;
Type temporaryListType = typeof(List<>).MakeGenericType(collectionItemType);
_genericTemporaryCollectionCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateDefaultConstructor<object>(temporaryListType);
}
return (IList)_genericTemporaryCollectionCreator();
}
}
}
| |
#region License
/* **********************************************************************************
* Copyright (c) Roman Ivantsov
* This source code is subject to terms and conditions of the MIT License
* for Irony. A copy of the license can be found in the License.txt file
* at the root of this distribution.
* By using this source code in any fashion, you are agreeing to be bound by the terms of the
* MIT License.
* You must not remove this notice from this software.
* **********************************************************************************/
#endregion
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Globalization;
namespace Irony.Parsing {
[Flags]
public enum ParseOptions {
Reserved = 0x01,
AnalyzeCode = 0x10, //run code analysis; effective only in Module mode
}
public enum ParseMode {
File, //default, continuous input file
VsLineScan, // line-by-line scanning in VS integration for syntax highlighting
CommandLine, //line-by-line from console
}
public enum ParserStatus {
Init, //initial state
Parsing,
Previewing, //previewing tokens
Recovering, //recovering from error
Accepted,
AcceptedPartial,
Error,
}
// The purpose of this class is to provide a container for information shared
// between parser, scanner and token filters.
public partial class ParsingContext {
public readonly Parser Parser;
public readonly LanguageData Language;
//Parser settings
public ParseOptions Options;
public bool TracingEnabled;
public ParseMode Mode = ParseMode.File;
public int MaxErrors = 20; //maximum error count to report
public CultureInfo Culture; //defaults to Grammar.DefaultCulture, might be changed by app code
#region properties and fields
//Parser fields
public ParseTree CurrentParseTree { get; internal set; }
public readonly TokenStack OpenBraces = new TokenStack();
public ParserTrace ParserTrace = new ParserTrace();
internal readonly ParserStack ParserStack = new ParserStack();
public ParserState CurrentParserState { get; internal set; }
public ParseTreeNode CurrentParserInput { get; internal set; }
public Token CurrentToken; //The token just scanned by Scanner
public TokenList CurrentCommentTokens = new TokenList(); //accumulated comment tokens
public Token PreviousToken;
public SourceLocation PreviousLineStart; //Location of last line start
//list for terminals - for current parser state and current input char
public TerminalList CurrentTerminals = new TerminalList();
public ISourceStream Source;
//Internal fields
internal TokenFilterList TokenFilters = new TokenFilterList();
internal TokenStack BufferedTokens = new TokenStack();
internal IEnumerator<Token> FilteredTokens; //stream of tokens after filter
internal TokenStack PreviewTokens = new TokenStack();
internal ParsingEventArgs SharedParsingEventArgs;
internal ValidateTokenEventArgs SharedValidateTokenEventArgs;
public VsScannerStateMap VsLineScanState; //State variable used in line scanning mode for VS integration
public ParserStatus Status {get; internal set;}
public bool HasErrors; //error flag, once set remains set
//values dictionary to use by custom language implementations to save some temporary values during parsing
public readonly Dictionary<string, object> Values = new Dictionary<string, object>();
public int TabWidth = 8;
#endregion
#region constructors
public ParsingContext(Parser parser) {
this.Parser = parser;
Language = Parser.Language;
Culture = Language.Grammar.DefaultCulture;
//This might be a problem for multi-threading - if we have several contexts on parallel threads with different culture.
//Resources.Culture is static property (this is not Irony's fault, this is auto-generated file).
Resources.Culture = Culture;
SharedParsingEventArgs = new ParsingEventArgs(this);
SharedValidateTokenEventArgs = new ValidateTokenEventArgs(this);
}
#endregion
#region Events: TokenCreated
public event EventHandler<ParsingEventArgs> TokenCreated;
internal void OnTokenCreated() {
if (TokenCreated != null)
TokenCreated(this, SharedParsingEventArgs);
}
#endregion
#region Error handling and tracing
public Token CreateErrorToken(string message, params object[] args) {
if (args != null && args.Length > 0)
message = string.Format(message, args);
return Source.CreateToken(Language.Grammar.SyntaxError, message);
}
public void AddParserError(string message, params object[] args) {
var location = CurrentParserInput == null? Source.Location : CurrentParserInput.Span.Location;
HasErrors = true;
AddParserMessage(ErrorLevel.Error, location, message, args);
}
public void AddParserMessage(ErrorLevel level, SourceLocation location, string message, params object[] args) {
if (CurrentParseTree == null) return;
if (CurrentParseTree.ParserMessages.Count >= MaxErrors) return;
if (args != null && args.Length > 0)
message = string.Format(message, args);
CurrentParseTree.ParserMessages.Add(new LogMessage(level, location, message, CurrentParserState));
if (TracingEnabled)
AddTrace(true, message);
}
public void AddTrace(string message, params object[] args) {
AddTrace(false, message, args);
}
public void AddTrace(bool asError, string message, params object[] args) {
if (!TracingEnabled)
return;
if (args != null && args.Length > 0)
message = string.Format(message, args);
ParserTrace.Add(new ParserTraceEntry(CurrentParserState, ParserStack.Top, CurrentParserInput, message, asError));
}
#region comments
// Computes set of expected terms in a parser state. While there may be extended list of symbols expected at some point,
// we want to reorganize and reduce it. For example, if the current state expects all arithmetic operators as an input,
// it would be better to not list all operators (+, -, *, /, etc) but simply put "operator" covering them all.
// To achieve this grammar writer can group operators (or any other terminals) into named groups using Grammar's methods
// AddTermReportGroup, AddNoReportGroup etc. Then instead of reporting each operator separately, Irony would include
// a single "group name" to represent them all.
// The "expected report set" is not computed during parser construction (it would take considerable time),
// but does it on demand during parsing, when error is detected and the expected set is actually needed for error message.
// Multi-threading concerns. When used in multi-threaded environment (web server), the LanguageData would be shared in
// application-wide cache to avoid rebuilding the parser data on every request. The LanguageData is immutable, except
// this one case - the expected sets are constructed late by CoreParser on the when-needed basis.
// We don't do any locking here, just compute the set and on return from this function the state field is assigned.
// We assume that this field assignment is an atomic, concurrency-safe operation. The worst thing that might happen
// is "double-effort" when two threads start computing the same set around the same time, and the last one to finish would
// leave its result in the state field.
#endregion
internal static StringSet ComputeGroupedExpectedSetForState(Grammar grammar, ParserState state) {
var terms = new TerminalSet();
terms.UnionWith(state.ExpectedTerminals);
var result = new StringSet();
//Eliminate no-report terminals
foreach (var group in grammar.TermReportGroups)
if (group.GroupType == TermReportGroupType.DoNotReport)
terms.ExceptWith(group.Terminals);
//Add normal and operator groups
foreach (var group in grammar.TermReportGroups)
if ((group.GroupType == TermReportGroupType.Normal || group.GroupType == TermReportGroupType.Operator) &&
terms.Overlaps(group.Terminals)) {
result.Add(group.Alias);
terms.ExceptWith(group.Terminals);
}
//Add remaining terminals "as is"
foreach (var terminal in terms)
result.Add(terminal.ErrorAlias);
return result;
}
#endregion
internal void Reset() {
CurrentParserState = Parser.InitialState;
CurrentParserInput = null;
CurrentCommentTokens = new TokenList();
ParserStack.Clear();
HasErrors = false;
ParserStack.Push(new ParseTreeNode(CurrentParserState));
CurrentParseTree = null;
OpenBraces.Clear();
ParserTrace.Clear();
CurrentTerminals.Clear();
CurrentToken = null;
PreviousToken = null;
PreviousLineStart = new SourceLocation(0, -1, 0);
BufferedTokens.Clear();
PreviewTokens.Clear();
Values.Clear();
foreach (var filter in TokenFilters)
filter.Reset();
}
public void SetSourceLocation(SourceLocation location) {
foreach (var filter in TokenFilters)
filter.OnSetSourceLocation(location);
Source.Location = location;
}
public SourceSpan ComputeStackRangeSpan(int nodeCount) {
if (nodeCount == 0)
return new SourceSpan(CurrentParserInput.Span.Location, 0);
var first = ParserStack[ParserStack.Count - nodeCount];
var last = ParserStack.Top;
return new SourceSpan(first.Span.Location, last.Span.EndPosition - first.Span.Location.Position);
}
#region Expected term set computations
public StringSet GetExpectedTermSet() {
if (CurrentParserState == null)
return new StringSet();
//See note about multi-threading issues in ComputeReportedExpectedSet comments.
if (CurrentParserState.ReportedExpectedSet == null)
CurrentParserState.ReportedExpectedSet = Construction.ParserDataBuilder.ComputeGroupedExpectedSetForState(Language.Grammar, CurrentParserState);
//Filter out closing braces which are not expected based on previous input.
// While the closing parenthesis ")" might be expected term in a state in general,
// if there was no opening parenthesis in preceding input then we would not
// expect a closing one.
var expectedSet = FilterBracesInExpectedSet(CurrentParserState.ReportedExpectedSet);
return expectedSet;
}
private StringSet FilterBracesInExpectedSet(StringSet stateExpectedSet) {
var result = new StringSet();
result.UnionWith(stateExpectedSet);
//Find what brace we expect
var nextClosingBrace = string.Empty;
if (OpenBraces.Count > 0) {
var lastOpenBraceTerm = OpenBraces.Peek().KeyTerm;
var nextClosingBraceTerm = lastOpenBraceTerm.IsPairFor as KeyTerm;
if (nextClosingBraceTerm != null)
nextClosingBrace = nextClosingBraceTerm.Text;
}
//Now check all closing braces in result set, and leave only nextClosingBrace
foreach (var term in Language.Grammar.KeyTerms.Values) {
if (term.Flags.IsSet(TermFlags.IsCloseBrace)) {
var brace = term.Text;
if (result.Contains(brace) && brace != nextClosingBrace)
result.Remove(brace);
}
}//foreach term
return result;
}
#endregion
}//class
// A struct used for packing/unpacking ScannerState int value; used for VS integration.
// When Terminal produces incomplete token, it sets
// this state to non-zero value; this value identifies this terminal as the one who will continue scanning when
// it resumes, and the terminal's internal state when there may be several types of multi-line tokens for one terminal.
// For ex., there maybe several types of string literal like in Python.
[StructLayout(LayoutKind.Explicit)]
public struct VsScannerStateMap {
[FieldOffset(0)]
public int Value;
[FieldOffset(0)]
public byte TerminalIndex; //1-based index of active multiline term in MultilineTerminals
[FieldOffset(1)]
public byte TokenSubType; //terminal subtype (used in StringLiteral to identify string kind)
[FieldOffset(2)]
public short TerminalFlags; //Terminal flags
}//struct
}
| |
// Copyright (c) 2015 hugula
// direct https://github.com/tenvick/hugula
//
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.IO;
using System.Text.RegularExpressions;
using System;
using System.Text;
using SLua;
using Lua = SLua.LuaSvr;
[CustomLuaClass]
public class PLua : MonoBehaviour
{
public static string enterLua = "main";
public LuaFunction onDestroyFn;
public static bool isDebug = true;
public Lua lua;
public LNet net;
public LNet ChatNet;
public static Dictionary<string, TextAsset> luacache;
#region priveta
private string luaMain = "";
private const string initLua = @"require(""core.unity3d"")";
private LuaFunction _updateFn;
#endregion
#region mono
public LuaFunction updateFn
{
get { return _updateFn; }
set
{
_updateFn = value;
}
}
void Awake()
{
DontDestroyOnLoad(this.gameObject);
luacache = new Dictionary<string, TextAsset>();
lua = new Lua();
_instance = this;
LoadScript();
}
void Start()
{
net = LNet.instance;
ChatNet = LNet.ChatInstance;
lua.init(null, () =>
{ LoadBundle(true); });
}
void Update()
{
if (net != null) net.Update();
if (ChatNet != null) ChatNet.Update();
if (_updateFn != null) _updateFn.call();
}
void OnApplicationPause(bool pauseStatus)
{
if (net != null) net.OnApplicationPause(pauseStatus);
}
void OnDestroy()
{
if (onDestroyFn != null) onDestroyFn.call();
updateFn = null;
if (lua != null) lua.luaState.Close();
lua = null;
_instance = null;
if(net!=null)net.Dispose();
net = null;
if(ChatNet!=null)ChatNet.Dispose();
ChatNet = null;
luacache.Clear();
}
#endregion
private void SetLuaPath()
{
this.luaMain = "return require(\"" + enterLua + "\") \n";
Debug.Log(luaMain);
}
private void LoadScript()
{
SetLuaPath();
RegisterFunc();
}
/// <summary>
/// lua bundle
/// </summary>
/// <returns></returns>
private IEnumerator loadLuaBundle(bool domain,LuaFunction onLoadedFn)
{
string keyName = "";
string luaP = CUtils.GetAssetFullPath("font.u3d");
WWW luaLoader = new WWW(luaP);
yield return luaLoader;
if (luaLoader.error == null)
{
byte[] byts=CryptographHelper.Decrypt(luaLoader.bytes,DESHelper.instance.Key,DESHelper.instance.IV);
AssetBundle item = AssetBundle.CreateFromMemoryImmediate(byts);
TextAsset[] all = item.LoadAllAssets<TextAsset>();
foreach (var ass in all)
{
keyName = ass.name;
luacache[keyName] = ass;
}
item.Unload(false);
luaLoader.Dispose();
}
DoUnity3dLua();
if (domain)
DoMain();
if (onLoadedFn != null) onLoadedFn.call();
}
#region public
public void DoUnity3dLua()
{
lua.luaState.doString(initLua);//
}
/// <summary>
/// lua begin
/// </summary>
public void DoMain()
{
lua.luaState.doString(this.luaMain);
}
/// <summary>
/// load assetbundle
/// </summary>
public void LoadBundle(bool domain)
{
#if UNITY_EDITOR
if(!isDebug)
{
StopCoroutine(loadLuaBundle(domain, null));
StartCoroutine(loadLuaBundle(domain, null));
}else
{
DoUnity3dLua();
if (domain)
DoMain();
}
#else
StopCoroutine(loadLuaBundle(domain, null));
StartCoroutine(loadLuaBundle(domain, null));
#endif
}
/// <summary>
/// load assetbundle
/// </summary>
public void LoadBundle(LuaFunction onLoadedFn)
{
StopCoroutine(loadLuaBundle(false, onLoadedFn));
StartCoroutine(loadLuaBundle(false, onLoadedFn));
}
#endregion
#region toolMethod
public void RegisterFunc()
{
LuaState.loaderDelegate=Loader;
}
/// <summary>
/// loader
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static byte[] Loader(string name)
{
byte[] str = null;
#if UNITY_EDITOR
if (isDebug)
{
name = name.Replace('.','/');
string path = Application.dataPath + "/Lua/" + name+".lua";
try
{
str = File.ReadAllBytes(path);
}
catch
{
}
}
else
{
name = name.Replace('.','_').Replace('/','_');
if (luacache.ContainsKey(name))
{
TextAsset file = luacache[name];
str = file.bytes;
}
}
#else
name = name.Replace('.','_').Replace('/','_');
if(luacache.ContainsKey(name))
{
TextAsset file = luacache[name];
str = file.bytes;
}
#endif
return str;
}
public static void Delay(LuaFunction luafun, float time, object args = null)
{
_instance.StartCoroutine(DelayDo(luafun, args, time));
}
public static void StopDelay(string methodName = "DelayDo")
{
_instance.StopCoroutine(methodName);
}
private static IEnumerator DelayDo(LuaFunction luafun, object arg, float time)
{
yield return new WaitForSeconds(time);
luafun.call(arg);
}
#endregion
#region static
private static PLua _instance;
public static PLua instance
{
get
{
return _instance;
}
}
#endregion
}
| |
using UnityEngine;
using System.Collections;
using UnityEditor;
using System.Reflection;
using System.Linq;
using System;
using System.Text.RegularExpressions;
namespace StrayTech
{
/// <summary>
/// Any extension methods used by editor classes can be created here.
/// </summary>
public static class EditorExtensions
{
#region const members
public const float LINE_HEIGHT = 16f;
public const float SPACING = 3f;
public const float SPACED_LINE = LINE_HEIGHT + SPACING;
#endregion const members
#region static members
/// <summary>
/// A Blank GUIContent.
/// </summary>
public static GUIContent Blank = new GUIContent();
#endregion static members
#region methods
/// <summary>
/// "Extracts" a single line from the given source Rect, and returns the sub-Rect.
/// </summary>
/// <param name="canvas">The source area to extract space from. Space will be pulled from the top of the Rect.</param>
/// <returns>A single-line high Rect, positioned at the top of the Canvas.</returns>
public static Rect ExtractSpace(ref Rect canvas)
{
return EditorExtensions.ExtractSpace(ref canvas, EditorGUIUtility.singleLineHeight);
}
/// <summary>
/// "Extracts" a Rect of the given height from the given source Rect, and returns the sub-Rect.
/// </summary>
/// <param name="canvas">The source area to extract space from. Space will be pulled from the top of the Rect.</param>
/// <param name="height">The amount of space to extract from the Canvas.</param>
/// <returns>A rect with height "height", positioned at the top of the Canvas.</returns>
public static Rect ExtractSpace(ref Rect canvas, float height)
{
// if height is taller than the canvas, just extract the rest of the canvas.
float amountToExtract = canvas.height >= height ? height : canvas.height;
// create the extracted area
Rect output = new Rect(canvas);
output.height = amountToExtract;
// shove the canvas's top down
canvas.yMin += amountToExtract;
return output;
}
public static Rect ExtractSpaceHorizontal(ref Rect canvas, float width, bool rightToLeft = true)
{
float amountToExtract = canvas.width >= width ? width : canvas.width;
Rect output = new Rect(canvas);
output.width = amountToExtract;
if (rightToLeft == true)
{
canvas.xMin += amountToExtract;
}
else
{
canvas.xMax -= amountToExtract;
output.x = canvas.xMax;
}
return output;
}
public static Rect PadRectangle(this Rect source, float padding)
{
return PadRectangle(source, padding, padding, padding, padding);
}
public static Rect PadRectangle(this Rect source, float top, float left, float bottom, float right)
{
Rect output = new Rect(source);
output.yMin += top;
output.xMin += left;
output.yMax -= bottom;
output.xMax -= right;
return output;
}
public static void DrawFrame(Rect canvas, float padding, Color border, Color inner)
{
EditorGUI.DrawRect(canvas, border);
EditorGUI.DrawRect(EditorExtensions.PadRectangle(canvas, padding), inner);
}
public static string ValueAsString(this SerializedProperty property)
{
switch (property.propertyType)
{
case SerializedPropertyType.AnimationCurve:
return property.animationCurveValue.ToString();
case SerializedPropertyType.ArraySize:
return property.ToString();
case SerializedPropertyType.Boolean:
return property.boolValue.ToString();
case SerializedPropertyType.Bounds:
return property.boundsValue.ToString();
case SerializedPropertyType.Character:
return property.stringValue.ToString();
case SerializedPropertyType.Color:
return property.colorValue.ToString();
case SerializedPropertyType.Enum:
return property.enumNames[property.enumValueIndex];
case SerializedPropertyType.Float:
return property.ToString();
case SerializedPropertyType.Generic:
return property.ToString();
case SerializedPropertyType.Gradient:
return property.ToString();
case SerializedPropertyType.Integer:
return property.intValue.ToString();
case SerializedPropertyType.LayerMask:
return property.ToString();
case SerializedPropertyType.ObjectReference:
return property.objectReferenceValue != null ? property.objectReferenceValue.name : "null";
case SerializedPropertyType.Quaternion:
return property.quaternionValue.ToString();
case SerializedPropertyType.Rect:
return property.rectValue.ToString();
case SerializedPropertyType.String:
return property.stringValue;
case SerializedPropertyType.Vector2:
return property.vector2Value.ToString();
case SerializedPropertyType.Vector3:
return property.vector3Value.ToString();
default:
break;
}
return string.Empty;
}
/// <summary>
/// Find serialized property by name. Throws an exception if the property couldn't be found.
/// </summary>
/// <param name="source">This SerializedObject.</param>
/// <param name="propertyPath">The name of the field/property to find.</param>
/// <returns>The SerializedProperty with the given name.</returns>
public static SerializedProperty FindPropertyExplosive(this SerializedObject source, string propertyPath)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
if (string.IsNullOrEmpty(propertyPath))
{
throw new ArgumentException("propertyName");
}
var output = source.FindProperty(propertyPath);
if (output == null)
{
throw new MissingFieldException(string.Format("No such field '{0}' in '{1}'!", propertyPath, source.targetObject.name));
}
return output;
}
/// <summary>
/// Find serialized property by name. Throws an exception if the property couldn't be found.
/// </summary>
/// <param name="source">This SerializedProperty.</param>
/// <param name="relativePropertyPath">The name of the field/property to find.</param>
/// <returns>The SerializedProperty with the given name.</returns>
public static SerializedProperty FindPropertyRelativeExplosive(this SerializedProperty source, string relativePropertyPath)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
if (string.IsNullOrEmpty(relativePropertyPath))
{
throw new ArgumentException("propertyName");
}
var output = source.FindPropertyRelative(relativePropertyPath);
if (output == null)
{
throw new MissingFieldException(string.Format("No such field '{0}' in '{1}'!", relativePropertyPath, source.name));
}
return output;
}
/// <summary>
/// Niceifys the inspector name of a given property
/// by stripping any leading underscores and capitalizing the first letter
/// of the property.
/// </summary>
/// <returns></returns>
public static string NiceifyPropertyName(this string myString)
{
//Don't bother with 2 character names, they probably aren't savable anyway.
if (myString.Length <= 2)
return myString;
string toReturn = myString;
try
{
//Remove the leading _ if it exists.
if (toReturn.StartsWith("_"))
{
toReturn = toReturn.Remove(0, 1);
}
//Replace the first character with the uppercase version of that character.
var firstCharacter = toReturn[0];
toReturn = toReturn.Remove(0, 1);
toReturn = toReturn.Insert(0, char.ToUpper(firstCharacter).ToString());
//Add a space before each capital letter.
toReturn = Regex.Replace(toReturn, "([a-z])([A-Z])", "$1 $2");
}
catch (System.Exception)
{
//Catch any possible exceptions with our string operations and reset our result if anything goes wrong.
toReturn = myString;
}
return toReturn;
}
/// <summary>
/// Render a property on a new line.
/// </summary>
public static Rect RenderSingleLineProperty(Rect currentPosition, SerializedProperty property, string overrideName = "")
{
if (property == null)
return currentPosition;
//Update position for new line.
currentPosition = MoveToNewLine(currentPosition);
string nameString = property.name;
if (string.IsNullOrEmpty(overrideName) == false)
{
nameString = overrideName;
}
//Render the property. .
EditorGUI.PropertyField(currentPosition, property, new GUIContent(ObjectNames.NicifyVariableName(nameString)));
return currentPosition;
}
public static void RenderBackgroundRect(Rect position, float propertyHeight, string title)
{
if (Event.current.type == EventType.Repaint)
{
//Make the rect take up the entire property.
Rect newPosition = new Rect(position.xMin, position.yMin, position.width, Mathf.Max(0, propertyHeight));
GUI.skin.box.normal.textColor = GUI.skin.label.normal.textColor;
GUI.skin.box.fontStyle = FontStyle.BoldAndItalic;
if (string.IsNullOrEmpty(title) == false)
{
GUI.skin.box.Draw(newPosition, new GUIContent(ObjectNames.NicifyVariableName(title)), 0);
}
else
{
GUI.skin.box.Draw(newPosition, GUIContent.none, 0);
}
}
}
/// <summary>
/// Move the position to a new line.
/// </summary>
public static Rect MoveToNewLine(Rect position)
{
return new Rect(position.xMin, position.yMin + (LINE_HEIGHT + SPACING), position.width - SPACING, LINE_HEIGHT);
}
/// <summary>
/// Calculate the total height of a property based on the number of single line elements.
/// </summary>
public static float CalculatePropertyHeight(float numberOfSingleLineElements)
{
if (numberOfSingleLineElements <= 0)
return LINE_HEIGHT;
return (LINE_HEIGHT * numberOfSingleLineElements) + ((numberOfSingleLineElements + 1) * SPACING);
}
/// <summary>
/// Remove all interfaces of the provided type from the provided GameObject.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="gameObject"></param>
public static void RemoveInterfaces<T>(GameObject gameObject)
where T : class
{
//Bail if provided null argument.
if (gameObject == null)
return;
//Bail if provided incorrect type.
if (typeof(T).IsInterface == false)
return;
//Get all attached interfaces of the provided type.
var foundInterfaces = gameObject.GetInterfaces<T>();
for (int i = foundInterfaces.Length - 1; i >= 0; i--)
{
//We can cast the interface to a component because we know that only
//interfaces which are also monobehaviors will be found by GetInterfaces.
var component = foundInterfaces[i] as Component;
//Call DestroyImmediate because we are in editor mode.
UnityEngine.Object.DestroyImmediate(component);
}
}
/// <summary>
/// Remove all MonoBehaviors of the provided type from the provided GameObject.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="gameObject"></param>
public static void RemoveBehaviors<T>(GameObject gameObject)
where T : MonoBehaviour
{
//Bail if provided null argument.
if (gameObject == null)
return;
//Get all attached interfaces of the provided type.
var foundComponents = gameObject.GetComponents<T>();
for (int i = foundComponents.Length - 1; i >= 0; i--)
{
//Call DestroyImmediate because we are in editor mode.
UnityEngine.Object.DestroyImmediate(foundComponents[i]);
}
}
/// <summary>
/// Helper method which attempts to
/// 1. Load the provided asset in the resources folder.
/// 2. Get a MonoBehaviour Component of type T from the loaded asset
/// </summary>
/// <returns></returns>
public static T GetComponentFromLoadedResource<T>(string resourcePath)
where T : Component
{
if (string.IsNullOrEmpty(resourcePath))
return null;
//Try to load and instantiate the resource specified at the asset path.
var loadedResource = GameObject.Instantiate(Resources.Load<GameObject>(resourcePath)) as GameObject;
if (loadedResource == null)
{
Debug.LogError("Could not load resource at asset path: " + resourcePath);
//Be safe and destroy immediate.. the Instantiate ~*could*~ have created something (if the
//asset it loaded was not a GameObject the "as" check would have made loadedResource null, however something
//definitely was loaded). So just call this, passing in null wont explode so it can't hurt.
GameObject.DestroyImmediate(loadedResource);
return null;
}
//Attempt to get the desired component.
var foundComponent = loadedResource.GetComponent<T>();
if (foundComponent == null)
{
//bail if spawned prefab didn't have the requested component.
Debug.LogError(string.Format("Could not get a {0} component from asset loaded from path {1}. Destroying!", typeof(T).Name, resourcePath));
GameObject.DestroyImmediate(loadedResource);
return null;
}
return foundComponent;
}
public static T LoadScriptableObject<T>(string resourcePath)
where T : ScriptableObject
{
if (string.IsNullOrEmpty(resourcePath))
return null;
//Try to load the resource specified at the asset path.
var loadedResource = Resources.Load(resourcePath) as T;
if (loadedResource == null)
{
Debug.LogError("Could not load resource at asset path: " + resourcePath);
GameObject.DestroyImmediate(loadedResource);
return null;
}
return loadedResource;
}
/// <summary>
/// Show the user the new object they created using our menu.
/// </summary>
/// <param name="toFocus"></param>
public static void FocusOnGameObject(GameObject toFocus)
{
if (toFocus == null)
return;
//Make the new object the active selection and move the camera to focus on it.
Selection.activeGameObject = toFocus;
if (SceneView.lastActiveSceneView != null)
{
SceneView.lastActiveSceneView.FrameSelected();
}
EditorGUIUtility.PingObject(toFocus);
}
/// <summary>
/// Returns the number of children of the provided parent, whose name matches
/// the provided string.
/// </summary>
public static int GetChildCountOfNamesContain(GameObject parent, string searchString)
{
if (parent == null || string.IsNullOrEmpty(searchString))
return 0;
int foundChildrenCount = 0;
foreach (Transform child in parent.transform)
{
if (child.name.Contains(searchString))
{
foundChildrenCount++;
}
}
return foundChildrenCount;
}
#endregion methods
}
}
| |
using UnityEngine;
using UnityEngine.Experimental.Rendering.HDPipeline;
using UnityEngine.Experimental.Rendering;
using System.Text;
using static UnityEngine.Experimental.Rendering.HDPipeline.RenderPipelineSettings;
using UnityEditor.Rendering;
namespace UnityEditor.Experimental.Rendering.HDPipeline
{
using CED = CoreEditorDrawer<SerializedHDRenderPipelineAsset>;
static partial class HDRenderPipelineUI
{
enum Expandable
{
CameraFrameSettings = 1 << 0,
BakedOrCustomProbeFrameSettings = 1 << 1,
RealtimeProbeFrameSettings = 1 << 2,
General = 1 << 3,
Rendering = 1 << 4,
Lighting = 1 << 5,
Material = 1 << 6,
LightLoop = 1 << 7,
Cookie = 1 << 8,
Reflection = 1 << 9,
Sky = 1 << 10,
Shadow = 1 << 11,
Decal = 1 << 12,
PostProcess = 1 << 13,
DynamicResolution = 1 << 14,
LowResTransparency = 1 << 15
}
readonly static ExpandedState<Expandable, HDRenderPipelineAsset> k_ExpandedState = new ExpandedState<Expandable, HDRenderPipelineAsset>(Expandable.CameraFrameSettings | Expandable.General, "HDRP");
enum ShadowResolutionValue
{
ShadowResolution128 = 128,
ShadowResolution256 = 256,
ShadowResolution512 = 512,
ShadowResolution1024 = 1024,
ShadowResolution2048 = 2048,
ShadowResolution4096 = 4096,
ShadowResolution8192 = 8192,
ShadowResolution16384 = 16384
}
internal enum SelectedFrameSettings
{
Camera,
BakedOrCustomReflection,
RealtimeReflection
}
internal static DiffusionProfileSettingsListUI diffusionProfileUI = new DiffusionProfileSettingsListUI();
internal static SelectedFrameSettings selectedFrameSettings;
static HDRenderPipelineUI()
{
Inspector = CED.Group(
CED.Group(SupportedSettingsInfoSection),
FrameSettingsSection,
CED.FoldoutGroup(k_GeneralSectionTitle, Expandable.General, k_ExpandedState, Drawer_SectionGeneral),
CED.FoldoutGroup(k_RenderingSectionTitle, Expandable.Rendering, k_ExpandedState,
CED.Group(GroupOption.Indent, Drawer_SectionRenderingUnsorted),
CED.FoldoutGroup(k_DecalsSubTitle, Expandable.Decal, k_ExpandedState, FoldoutOption.Indent | FoldoutOption.SubFoldout, Drawer_SectionDecalSettings),
CED.FoldoutGroup(k_DynamicResolutionSubTitle, Expandable.DynamicResolution, k_ExpandedState, FoldoutOption.Indent | FoldoutOption.SubFoldout | FoldoutOption.NoSpaceAtEnd, Drawer_SectionDynamicResolutionSettings),
CED.FoldoutGroup(k_LowResTransparencySubTitle, Expandable.LowResTransparency, k_ExpandedState, FoldoutOption.Indent | FoldoutOption.SubFoldout | FoldoutOption.NoSpaceAtEnd, Drawer_SectionLowResTransparentSettings)
),
CED.FoldoutGroup(k_LightingSectionTitle, Expandable.Lighting, k_ExpandedState,
CED.Group(GroupOption.Indent, Drawer_SectionLightingUnsorted),
CED.FoldoutGroup(k_CookiesSubTitle, Expandable.Cookie, k_ExpandedState, FoldoutOption.Indent | FoldoutOption.SubFoldout, Drawer_SectionCookies),
CED.FoldoutGroup(k_ReflectionsSubTitle, Expandable.Reflection, k_ExpandedState, FoldoutOption.Indent | FoldoutOption.SubFoldout, Drawer_SectionReflection),
CED.FoldoutGroup(k_SkySubTitle, Expandable.Sky, k_ExpandedState, FoldoutOption.Indent | FoldoutOption.SubFoldout, Drawer_SectionSky),
CED.FoldoutGroup(k_ShadowSubTitle, Expandable.Shadow, k_ExpandedState, FoldoutOption.Indent | FoldoutOption.SubFoldout, Drawer_SectionShadows),
CED.FoldoutGroup(k_LightLoopSubTitle, Expandable.LightLoop, k_ExpandedState, FoldoutOption.Indent | FoldoutOption.SubFoldout | FoldoutOption.NoSpaceAtEnd, Drawer_SectionLightLoop)
),
CED.FoldoutGroup(k_MaterialSectionTitle, Expandable.Material, k_ExpandedState, Drawer_SectionMaterialUnsorted),
CED.FoldoutGroup(k_PostProcessSectionTitle, Expandable.PostProcess, k_ExpandedState, Drawer_SectionPostProcessSettings)
);
// fix init of selection along what is serialized
if (k_ExpandedState[Expandable.BakedOrCustomProbeFrameSettings])
selectedFrameSettings = SelectedFrameSettings.BakedOrCustomReflection;
else if (k_ExpandedState[Expandable.RealtimeProbeFrameSettings])
selectedFrameSettings = SelectedFrameSettings.RealtimeReflection;
else //default value: camera
selectedFrameSettings = SelectedFrameSettings.Camera;
}
public static readonly CED.IDrawer Inspector;
static readonly CED.IDrawer FrameSettingsSection = CED.Group(
CED.Group(
(serialized, owner) => EditorGUILayout.BeginVertical("box"),
Drawer_TitleDefaultFrameSettings
),
CED.Conditional(
(serialized, owner) => k_ExpandedState[Expandable.CameraFrameSettings],
CED.Select(
(serialized, owner) => serialized.defaultFrameSettings,
FrameSettingsUI.InspectorInnerbox(withOverride: false)
)
),
CED.Conditional(
(serialized, owner) => k_ExpandedState[Expandable.BakedOrCustomProbeFrameSettings],
CED.Select(
(serialized, owner) => serialized.defaultBakedOrCustomReflectionFrameSettings,
FrameSettingsUI.InspectorInnerbox(withOverride: false)
)
),
CED.Conditional(
(serialized, owner) => k_ExpandedState[Expandable.RealtimeProbeFrameSettings],
CED.Select(
(serialized, owner) => serialized.defaultRealtimeReflectionFrameSettings,
FrameSettingsUI.InspectorInnerbox(withOverride: false)
)
),
CED.Group((serialized, owner) => EditorGUILayout.EndVertical())
);
static public void ApplyChangedDisplayedFrameSettings(SerializedHDRenderPipelineAsset serialized, Editor owner)
{
k_ExpandedState.SetExpandedAreas(Expandable.CameraFrameSettings | Expandable.BakedOrCustomProbeFrameSettings | Expandable.RealtimeProbeFrameSettings, false);
switch (selectedFrameSettings)
{
case SelectedFrameSettings.Camera:
k_ExpandedState.SetExpandedAreas(Expandable.CameraFrameSettings, true);
break;
case SelectedFrameSettings.BakedOrCustomReflection:
k_ExpandedState.SetExpandedAreas(Expandable.BakedOrCustomProbeFrameSettings, true);
break;
case SelectedFrameSettings.RealtimeReflection:
k_ExpandedState.SetExpandedAreas(Expandable.RealtimeProbeFrameSettings, true);
break;
}
}
static void Drawer_TitleDefaultFrameSettings(SerializedHDRenderPipelineAsset serialized, Editor owner)
{
GUILayout.BeginHorizontal();
EditorGUILayout.LabelField(k_DefaultFrameSettingsContent, EditorStyles.boldLabel);
EditorGUI.BeginChangeCheck();
selectedFrameSettings = (SelectedFrameSettings)EditorGUILayout.EnumPopup(selectedFrameSettings);
if (EditorGUI.EndChangeCheck())
ApplyChangedDisplayedFrameSettings(serialized, owner);
GUILayout.EndHorizontal();
}
static void Drawer_SectionGeneral(SerializedHDRenderPipelineAsset serialized, Editor owner)
{
EditorGUILayout.PropertyField(serialized.renderPipelineResources, k_RenderPipelineResourcesContent);
// Not serialized as editor only datas... Retrieve them in data
EditorGUI.showMixedValue = serialized.editorResourceHasMultipleDifferentValues;
EditorGUI.BeginChangeCheck();
var editorResources = EditorGUILayout.ObjectField(k_RenderPipelineEditorResourcesContent, serialized.firstEditorResources, typeof(HDRenderPipelineEditorResources), allowSceneObjects: false) as HDRenderPipelineEditorResources;
if (EditorGUI.EndChangeCheck())
serialized.SetEditorResource(editorResources);
EditorGUI.showMixedValue = false;
EditorGUILayout.PropertyField(serialized.enableSRPBatcher, k_SRPBatcher);
EditorGUILayout.PropertyField(serialized.shaderVariantLogLevel, k_ShaderVariantLogLevel);
}
static void Drawer_SectionCookies(SerializedHDRenderPipelineAsset serialized, Editor owner)
{
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.lightLoopSettings.cookieSize, k_CoockieSizeContent);
EditorGUI.BeginChangeCheck();
EditorGUILayout.DelayedIntField(serialized.renderPipelineSettings.lightLoopSettings.cookieTexArraySize, k_CookieTextureArraySizeContent);
if (EditorGUI.EndChangeCheck())
serialized.renderPipelineSettings.lightLoopSettings.cookieTexArraySize.intValue = Mathf.Clamp(serialized.renderPipelineSettings.lightLoopSettings.cookieTexArraySize.intValue, 1, TextureCache.k_MaxSupported);
if (serialized.renderPipelineSettings.lightLoopSettings.cookieTexArraySize.hasMultipleDifferentValues)
EditorGUILayout.HelpBox(k_MultipleDifferenteValueMessage, MessageType.Info);
else
{
long currentCache = TextureCache2D.GetApproxCacheSizeInByte(serialized.renderPipelineSettings.lightLoopSettings.cookieTexArraySize.intValue, serialized.renderPipelineSettings.lightLoopSettings.cookieSize.intValue, 1);
if (currentCache > LightLoop.k_MaxCacheSize)
{
int reserved = TextureCache2D.GetMaxCacheSizeForWeightInByte(LightLoop.k_MaxCacheSize, serialized.renderPipelineSettings.lightLoopSettings.cookieSize.intValue, 1);
string message = string.Format(k_CacheErrorFormat, HDEditorUtils.HumanizeWeight(currentCache), reserved);
EditorGUILayout.HelpBox(message, MessageType.Error);
}
else
{
string message = string.Format(k_CacheInfoFormat, HDEditorUtils.HumanizeWeight(currentCache));
EditorGUILayout.HelpBox(message, MessageType.Info);
}
}
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.lightLoopSettings.pointCookieSize, k_PointCoockieSizeContent);
EditorGUI.BeginChangeCheck();
EditorGUILayout.DelayedIntField(serialized.renderPipelineSettings.lightLoopSettings.cubeCookieTexArraySize, k_PointCookieTextureArraySizeContent);
if (EditorGUI.EndChangeCheck())
serialized.renderPipelineSettings.lightLoopSettings.cubeCookieTexArraySize.intValue = Mathf.Clamp(serialized.renderPipelineSettings.lightLoopSettings.cubeCookieTexArraySize.intValue, 1, TextureCache.k_MaxSupported);
if (serialized.renderPipelineSettings.lightLoopSettings.cubeCookieTexArraySize.hasMultipleDifferentValues)
EditorGUILayout.HelpBox(k_MultipleDifferenteValueMessage, MessageType.Info);
else
{
long currentCache = TextureCacheCubemap.GetApproxCacheSizeInByte(serialized.renderPipelineSettings.lightLoopSettings.cubeCookieTexArraySize.intValue, serialized.renderPipelineSettings.lightLoopSettings.pointCookieSize.intValue, 1);
if (currentCache > LightLoop.k_MaxCacheSize)
{
int reserved = TextureCacheCubemap.GetMaxCacheSizeForWeightInByte(LightLoop.k_MaxCacheSize, serialized.renderPipelineSettings.lightLoopSettings.pointCookieSize.intValue, 1);
string message = string.Format(k_CacheErrorFormat, HDEditorUtils.HumanizeWeight(currentCache), reserved);
EditorGUILayout.HelpBox(message, MessageType.Error);
}
else
{
string message = string.Format(k_CacheInfoFormat, HDEditorUtils.HumanizeWeight(currentCache));
EditorGUILayout.HelpBox(message, MessageType.Info);
}
}
}
static void Drawer_SectionReflection(SerializedHDRenderPipelineAsset serialized, Editor owner)
{
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.supportSSR, k_SupportSSRContent);
EditorGUILayout.Space();
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.lightLoopSettings.reflectionCacheCompressed, k_CompressProbeCacheContent);
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.lightLoopSettings.reflectionCubemapSize, k_CubemapSizeContent);
EditorGUI.BeginChangeCheck();
EditorGUILayout.DelayedIntField(serialized.renderPipelineSettings.lightLoopSettings.reflectionProbeCacheSize, k_ProbeCacheSizeContent);
if (EditorGUI.EndChangeCheck())
serialized.renderPipelineSettings.lightLoopSettings.reflectionProbeCacheSize.intValue = Mathf.Clamp(serialized.renderPipelineSettings.lightLoopSettings.reflectionProbeCacheSize.intValue, 1, TextureCache.k_MaxSupported);
if (serialized.renderPipelineSettings.lightLoopSettings.reflectionProbeCacheSize.hasMultipleDifferentValues)
EditorGUILayout.HelpBox(k_MultipleDifferenteValueMessage, MessageType.Info);
else
{
long currentCache = ReflectionProbeCache.GetApproxCacheSizeInByte(serialized.renderPipelineSettings.lightLoopSettings.reflectionProbeCacheSize.intValue, serialized.renderPipelineSettings.lightLoopSettings.reflectionCubemapSize.intValue, serialized.renderPipelineSettings.lightLoopSettings.supportFabricConvolution.boolValue ? 2 : 1);
if (currentCache > LightLoop.k_MaxCacheSize)
{
int reserved = ReflectionProbeCache.GetMaxCacheSizeForWeightInByte(LightLoop.k_MaxCacheSize, serialized.renderPipelineSettings.lightLoopSettings.reflectionCubemapSize.intValue, serialized.renderPipelineSettings.lightLoopSettings.supportFabricConvolution.boolValue ? 2 : 1);
string message = string.Format(k_CacheErrorFormat, HDEditorUtils.HumanizeWeight(currentCache), reserved);
EditorGUILayout.HelpBox(message, MessageType.Error);
}
else
{
string message = string.Format(k_CacheInfoFormat, HDEditorUtils.HumanizeWeight(currentCache));
EditorGUILayout.HelpBox(message, MessageType.Info);
}
}
EditorGUILayout.Space();
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.lightLoopSettings.planarReflectionCacheCompressed, k_CompressPlanarProbeCacheContent);
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.lightLoopSettings.planarReflectionCubemapSize, k_PlanarTextureSizeContent);
EditorGUI.BeginChangeCheck();
EditorGUILayout.DelayedIntField(serialized.renderPipelineSettings.lightLoopSettings.planarReflectionProbeCacheSize, k_PlanarProbeCacheSizeContent);
if (EditorGUI.EndChangeCheck())
serialized.renderPipelineSettings.lightLoopSettings.planarReflectionProbeCacheSize.intValue = Mathf.Clamp(serialized.renderPipelineSettings.lightLoopSettings.planarReflectionProbeCacheSize.intValue, 1, TextureCache.k_MaxSupported);
if (serialized.renderPipelineSettings.lightLoopSettings.planarReflectionProbeCacheSize.hasMultipleDifferentValues)
EditorGUILayout.HelpBox(k_MultipleDifferenteValueMessage, MessageType.Info);
else
{
long currentCache = PlanarReflectionProbeCache.GetApproxCacheSizeInByte(serialized.renderPipelineSettings.lightLoopSettings.planarReflectionProbeCacheSize.intValue, serialized.renderPipelineSettings.lightLoopSettings.planarReflectionCubemapSize.intValue, 1);
if (currentCache > LightLoop.k_MaxCacheSize)
{
int reserved = PlanarReflectionProbeCache.GetMaxCacheSizeForWeightInByte(LightLoop.k_MaxCacheSize, serialized.renderPipelineSettings.lightLoopSettings.planarReflectionCubemapSize.intValue, 1);
string message = string.Format(k_CacheErrorFormat, HDEditorUtils.HumanizeWeight(currentCache), reserved);
EditorGUILayout.HelpBox(message, MessageType.Error);
}
else
{
string message = string.Format(k_CacheInfoFormat, HDEditorUtils.HumanizeWeight(currentCache));
EditorGUILayout.HelpBox(message, MessageType.Info);
}
}
EditorGUILayout.Space();
EditorGUI.BeginChangeCheck();
EditorGUILayout.DelayedIntField(serialized.renderPipelineSettings.lightLoopSettings.maxEnvLightsOnScreen, k_MaxEnvContent);
if (EditorGUI.EndChangeCheck())
serialized.renderPipelineSettings.lightLoopSettings.maxEnvLightsOnScreen.intValue = Mathf.Clamp(serialized.renderPipelineSettings.lightLoopSettings.maxEnvLightsOnScreen.intValue, 1, LightLoop.k_MaxEnvLightsOnScreen);
}
static void Drawer_SectionSky(SerializedHDRenderPipelineAsset serialized, Editor owner)
{
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.lightLoopSettings.skyReflectionSize, k_SkyReflectionSizeContent);
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.lightLoopSettings.skyLightingOverrideLayerMask, k_SkyLightingOverrideMaskContent);
if (!serialized.renderPipelineSettings.lightLoopSettings.skyLightingOverrideLayerMask.hasMultipleDifferentValues
&& serialized.renderPipelineSettings.lightLoopSettings.skyLightingOverrideLayerMask.intValue == -1)
{
EditorGUILayout.HelpBox(k_SkyLightingHelpBoxContent, MessageType.Warning);
}
}
static void Drawer_SectionShadows(SerializedHDRenderPipelineAsset serialized, Editor owner)
{
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.supportShadowMask, k_SupportShadowMaskContent);
EditorGUILayout.IntPopup(serialized.renderPipelineSettings.hdShadowInitParams.directionalShadowMapDepthBits, k_ShadowBitDepthNames, k_ShadowBitDepthValues, k_DirectionalShadowPrecisionContent);
EditorGUILayout.LabelField(k_ShadowPunctualLightAtlasSubTitle);
++EditorGUI.indentLevel;
CoreEditorUtils.DrawEnumPopup(serialized.renderPipelineSettings.hdShadowInitParams.serializedPunctualAtlasInit.shadowMapResolution, typeof(ShadowResolutionValue), k_ResolutionContent);
EditorGUILayout.IntPopup(serialized.renderPipelineSettings.hdShadowInitParams.serializedPunctualAtlasInit.shadowMapDepthBits, k_ShadowBitDepthNames, k_ShadowBitDepthValues, k_DirectionalShadowPrecisionContent);
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.hdShadowInitParams.serializedPunctualAtlasInit.useDynamicViewportRescale, k_DynamicRescaleContent);
--EditorGUI.indentLevel;
EditorGUILayout.LabelField(k_ShadowAreaLightAtlasSubTitle);
++EditorGUI.indentLevel;
CoreEditorUtils.DrawEnumPopup(serialized.renderPipelineSettings.hdShadowInitParams.serializedAreaAtlasInit.shadowMapResolution, typeof(ShadowResolutionValue), k_ResolutionContent);
EditorGUILayout.IntPopup(serialized.renderPipelineSettings.hdShadowInitParams.serializedAreaAtlasInit.shadowMapDepthBits, k_ShadowBitDepthNames, k_ShadowBitDepthValues, k_PrecisionContent);
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.hdShadowInitParams.serializedAreaAtlasInit.useDynamicViewportRescale, k_DynamicRescaleContent);
--EditorGUI.indentLevel;
EditorGUILayout.DelayedIntField(serialized.renderPipelineSettings.hdShadowInitParams.maxShadowRequests, k_MaxRequestContent);
if (!serialized.renderPipelineSettings.supportedLitShaderMode.hasMultipleDifferentValues)
{
bool isDeferredOnly = serialized.renderPipelineSettings.supportedLitShaderMode.intValue == (int)RenderPipelineSettings.SupportedLitShaderMode.DeferredOnly;
// Deferred Only mode does not allow to change filtering quality, but rather it is hardcoded.
if (isDeferredOnly)
serialized.renderPipelineSettings.hdShadowInitParams.shadowQuality.intValue = (int)HDShadowQuality.Low;
using (new EditorGUI.DisabledScope(isDeferredOnly))
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.hdShadowInitParams.shadowQuality, k_FilteringQuality);
}
else
{
using (new EditorGUI.DisabledGroupScope(true))
EditorGUILayout.LabelField(k_MultipleDifferenteValueMessage);
}
}
static void Drawer_SectionDecalSettings(SerializedHDRenderPipelineAsset serialized, Editor owner)
{
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.supportDecals, k_SupportDecalContent);
++EditorGUI.indentLevel;
using (new EditorGUI.DisabledScope(!serialized.renderPipelineSettings.supportDecals.boolValue))
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.decalSettings.drawDistance, k_DrawDistanceContent);
if (EditorGUI.EndChangeCheck())
serialized.renderPipelineSettings.decalSettings.drawDistance.intValue = Mathf.Max(serialized.renderPipelineSettings.decalSettings.drawDistance.intValue, 0);
EditorGUI.BeginChangeCheck();
EditorGUILayout.DelayedIntField(serialized.renderPipelineSettings.decalSettings.atlasWidth, k_AtlasWidthContent);
if (EditorGUI.EndChangeCheck())
serialized.renderPipelineSettings.decalSettings.atlasWidth.intValue = Mathf.Max(serialized.renderPipelineSettings.decalSettings.atlasWidth.intValue, 0);
EditorGUI.BeginChangeCheck();
EditorGUILayout.DelayedIntField(serialized.renderPipelineSettings.decalSettings.atlasHeight, k_AtlasHeightContent);
if (EditorGUI.EndChangeCheck())
serialized.renderPipelineSettings.decalSettings.atlasHeight.intValue = Mathf.Max(serialized.renderPipelineSettings.decalSettings.atlasHeight.intValue, 0);
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.decalSettings.perChannelMask, k_MetalAndAOContent);
EditorGUI.BeginChangeCheck();
EditorGUILayout.DelayedIntField(serialized.renderPipelineSettings.lightLoopSettings.maxDecalsOnScreen, k_MaxDecalContent);
if (EditorGUI.EndChangeCheck())
serialized.renderPipelineSettings.lightLoopSettings.maxDecalsOnScreen.intValue = Mathf.Clamp(serialized.renderPipelineSettings.lightLoopSettings.maxDecalsOnScreen.intValue, 1, LightLoop.k_MaxDecalsOnScreen);
}
--EditorGUI.indentLevel;
}
static void Drawer_SectionLightLoop(SerializedHDRenderPipelineAsset serialized, Editor o)
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.DelayedIntField(serialized.renderPipelineSettings.lightLoopSettings.maxDirectionalLightsOnScreen, k_MaxDirectionalContent);
if (EditorGUI.EndChangeCheck())
serialized.renderPipelineSettings.lightLoopSettings.maxDirectionalLightsOnScreen.intValue = Mathf.Clamp(serialized.renderPipelineSettings.lightLoopSettings.maxDirectionalLightsOnScreen.intValue, 1, LightLoop.k_MaxDirectionalLightsOnScreen);
EditorGUI.BeginChangeCheck();
EditorGUILayout.DelayedIntField(serialized.renderPipelineSettings.lightLoopSettings.maxPunctualLightsOnScreen, k_MaxPonctualContent);
if (EditorGUI.EndChangeCheck())
serialized.renderPipelineSettings.lightLoopSettings.maxPunctualLightsOnScreen.intValue = Mathf.Clamp(serialized.renderPipelineSettings.lightLoopSettings.maxPunctualLightsOnScreen.intValue, 1, LightLoop.k_MaxPunctualLightsOnScreen);
EditorGUI.BeginChangeCheck();
EditorGUILayout.DelayedIntField(serialized.renderPipelineSettings.lightLoopSettings.maxAreaLightsOnScreen, k_MaxAreaContent);
if (EditorGUI.EndChangeCheck())
serialized.renderPipelineSettings.lightLoopSettings.maxAreaLightsOnScreen.intValue = Mathf.Clamp(serialized.renderPipelineSettings.lightLoopSettings.maxAreaLightsOnScreen.intValue, 1, LightLoop.k_MaxAreaLightsOnScreen);
}
static void Drawer_SectionDynamicResolutionSettings(SerializedHDRenderPipelineAsset serialized, Editor owner)
{
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.dynamicResolutionSettings.enabled, k_Enabled);
++EditorGUI.indentLevel;
using (new EditorGUI.DisabledScope(!serialized.renderPipelineSettings.dynamicResolutionSettings.enabled.boolValue))
{
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.dynamicResolutionSettings.dynamicResType, k_DynResType);
if (serialized.renderPipelineSettings.dynamicResolutionSettings.dynamicResType.hasMultipleDifferentValues)
{
using (new EditorGUI.DisabledGroupScope(true))
EditorGUILayout.LabelField(k_MultipleDifferenteValueMessage);
}
else
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.dynamicResolutionSettings.softwareUpsamplingFilter, k_UpsampleFilter);
if (!serialized.renderPipelineSettings.dynamicResolutionSettings.forcePercentage.hasMultipleDifferentValues
&& !serialized.renderPipelineSettings.dynamicResolutionSettings.forcePercentage.boolValue)
{
float minPercentage = serialized.renderPipelineSettings.dynamicResolutionSettings.minPercentage.floatValue;
float maxPercentage = serialized.renderPipelineSettings.dynamicResolutionSettings.maxPercentage.floatValue;
EditorGUI.showMixedValue = serialized.renderPipelineSettings.dynamicResolutionSettings.minPercentage.hasMultipleDifferentValues;
EditorGUI.BeginChangeCheck();
minPercentage = EditorGUILayout.DelayedFloatField(k_MinPercentage, minPercentage);
if (EditorGUI.EndChangeCheck())
serialized.renderPipelineSettings.dynamicResolutionSettings.minPercentage.floatValue = Mathf.Clamp(minPercentage, 0.0f, maxPercentage);
EditorGUI.showMixedValue = serialized.renderPipelineSettings.dynamicResolutionSettings.maxPercentage.hasMultipleDifferentValues;
EditorGUI.BeginChangeCheck();
maxPercentage = EditorGUILayout.DelayedFloatField(k_MinPercentage, maxPercentage);
if (EditorGUI.EndChangeCheck())
serialized.renderPipelineSettings.dynamicResolutionSettings.maxPercentage.floatValue = Mathf.Clamp(maxPercentage, 0.0f, 100.0f);
EditorGUI.showMixedValue = false;
}
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.dynamicResolutionSettings.forcePercentage, k_ForceScreenPercentage);
if (!serialized.renderPipelineSettings.dynamicResolutionSettings.forcePercentage.hasMultipleDifferentValues
&& serialized.renderPipelineSettings.dynamicResolutionSettings.forcePercentage.boolValue)
{
EditorGUI.showMixedValue = serialized.renderPipelineSettings.dynamicResolutionSettings.forcedPercentage.hasMultipleDifferentValues;
float forcePercentage = serialized.renderPipelineSettings.dynamicResolutionSettings.forcedPercentage.floatValue;
EditorGUI.BeginChangeCheck();
forcePercentage = EditorGUILayout.DelayedFloatField(k_ForcedScreenPercentage, forcePercentage);
if (EditorGUI.EndChangeCheck())
serialized.renderPipelineSettings.dynamicResolutionSettings.forcedPercentage.floatValue = Mathf.Clamp(forcePercentage, 0.0f, 100.0f);
EditorGUI.showMixedValue = false;
}
if (serialized.renderPipelineSettings.dynamicResolutionSettings.forcePercentage.hasMultipleDifferentValues)
{
using (new EditorGUI.DisabledGroupScope(true))
EditorGUILayout.LabelField(k_MultipleDifferenteValueMessage);
}
}
--EditorGUI.indentLevel;
}
static void Drawer_SectionLowResTransparentSettings(SerializedHDRenderPipelineAsset serialized, Editor owner)
{
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.lowresTransparentSettings.enabled, k_LowResTransparentEnabled);
/* For the time being we don't enable the option control and default to nearest depth. This might change in a close future.
++EditorGUI.indentLevel;
using (new EditorGUI.DisabledScope(!serialized.renderPipelineSettings.lowresTransparentSettings.enabled.boolValue))
{
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.lowresTransparentSettings.checkerboardDepthBuffer, k_CheckerboardDepthBuffer);
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.lowresTransparentSettings.upsampleType, k_UpsampleFilter);
}
--EditorGUI.indentLevel;
*/
}
static void Drawer_SectionPostProcessSettings(SerializedHDRenderPipelineAsset serialized, Editor owner)
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.DelayedIntField(serialized.renderPipelineSettings.postProcessSettings.lutSize, k_LutSize);
if (EditorGUI.EndChangeCheck())
serialized.renderPipelineSettings.postProcessSettings.lutSize.intValue = Mathf.Clamp(serialized.renderPipelineSettings.postProcessSettings.lutSize.intValue, GlobalPostProcessSettings.k_MinLutSize, GlobalPostProcessSettings.k_MaxLutSize);
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.postProcessSettings.lutFormat, k_LutFormat);
}
static void Drawer_SectionRenderingUnsorted(SerializedHDRenderPipelineAsset serialized, Editor owner)
{
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.colorBufferFormat, k_ColorBufferFormatContent);
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.supportedLitShaderMode, k_SupportLitShaderModeContent);
// MSAA is an option that is only available in full forward but Camera can be set in Full Forward only. Thus MSAA have no dependency currently
//Note: do not use SerializedProperty.enumValueIndex here as this enum not start at 0 as it is used as flags.
bool msaaAllowed = true;
for (int index = 0; index < serialized.serializedObject.targetObjects.Length && msaaAllowed; ++index)
{
var litShaderMode = (serialized.serializedObject.targetObjects[index] as HDRenderPipelineAsset).currentPlatformRenderPipelineSettings.supportedLitShaderMode;
msaaAllowed &= litShaderMode == SupportedLitShaderMode.ForwardOnly || litShaderMode == SupportedLitShaderMode.Both;
}
using (new EditorGUI.DisabledScope(!msaaAllowed))
{
++EditorGUI.indentLevel;
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.MSAASampleCount, k_MSAASampleCountContent);
--EditorGUI.indentLevel;
}
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.supportMotionVectors, k_SupportMotionVectorContent);
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.supportRuntimeDebugDisplay, k_SupportRuntimeDebugDisplayContent);
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.supportDitheringCrossFade, k_SupportDitheringCrossFadeContent);
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.supportTransparentBackface, k_SupportTransparentBackface);
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.supportTransparentDepthPrepass, k_SupportTransparentDepthPrepass);
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.supportTransparentDepthPostpass, k_SupportTransparentDepthPostpass);
// Only display the support ray tracing feature if the platform supports it
#if REALTIME_RAYTRACING_SUPPORT
if(UnityEngine.SystemInfo.supportsRayTracing)
{
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.supportRayTracing, k_SupportRaytracing);
}
else
#endif
{
serialized.renderPipelineSettings.supportRayTracing.boolValue = false;
}
EditorGUILayout.Space(); //to separate with following sub sections
}
static void Drawer_SectionLightingUnsorted(SerializedHDRenderPipelineAsset serialized, Editor owner)
{
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.supportSSAO, k_SupportSSAOContent);
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.supportVolumetrics, k_SupportVolumetricContent);
using (new EditorGUI.DisabledScope(serialized.renderPipelineSettings.supportVolumetrics.hasMultipleDifferentValues
|| !serialized.renderPipelineSettings.supportVolumetrics.boolValue))
{
++EditorGUI.indentLevel;
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.increaseResolutionOfVolumetrics, k_VolumetricResolutionContent);
--EditorGUI.indentLevel;
}
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.supportLightLayers, k_SupportLightLayerContent);
EditorGUILayout.Space(); //to separate with following sub sections
}
static void Drawer_SectionMaterialUnsorted(SerializedHDRenderPipelineAsset serialized, Editor owner)
{
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.supportDistortion, k_SupportDistortion);
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.supportSubsurfaceScattering, k_SupportedSSSContent);
using (new EditorGUI.DisabledScope(serialized.renderPipelineSettings.supportSubsurfaceScattering.hasMultipleDifferentValues
|| !serialized.renderPipelineSettings.supportSubsurfaceScattering.boolValue))
{
++EditorGUI.indentLevel;
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.increaseSssSampleCount, k_SSSSampleCountContent);
--EditorGUI.indentLevel;
}
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.lightLoopSettings.supportFabricConvolution, k_SupportFabricBSDFConvolutionContent);
diffusionProfileUI.drawElement = DrawDiffusionProfileElement;
diffusionProfileUI.OnGUI(serialized.diffusionProfileSettingsList);
}
static void DrawDiffusionProfileElement(SerializedProperty element, Rect rect, int index)
{
EditorGUI.ObjectField(rect, element, EditorGUIUtility.TrTextContent("Profile " + index));
}
const string supportedFormaterMultipleValue = "\u2022 {0} --Multiple different values--";
const string supportedFormater = "\u2022 {0} ({1})";
const string supportedLitShaderModeFormater = "\u2022 {0}: {1} ({2})";
static void AppendSupport(StringBuilder builder, SerializedProperty property, GUIContent content)
{
if (property.hasMultipleDifferentValues)
builder.AppendLine().AppendFormat(supportedFormaterMultipleValue, content.text);
else if (property.boolValue)
builder.AppendLine().AppendFormat(supportedFormater, content.text, k_SupportDrawbacks[content]);
}
static void SupportedSettingsInfoSection(SerializedHDRenderPipelineAsset serialized, Editor owner)
{
StringBuilder builder = new StringBuilder("Features supported by this asset:").AppendLine();
SupportedLitShaderMode supportedLitShaderMode = serialized.renderPipelineSettings.supportedLitShaderMode.GetEnumValue<SupportedLitShaderMode>();
if (serialized.renderPipelineSettings.supportedLitShaderMode.hasMultipleDifferentValues)
builder.AppendFormat(supportedFormaterMultipleValue, k_SupportLitShaderModeContent.text);
else
builder.AppendFormat(supportedLitShaderModeFormater, k_SupportLitShaderModeContent.text, supportedLitShaderMode, k_SupportLitShaderModeDrawbacks[supportedLitShaderMode]);
if (serialized.renderPipelineSettings.supportShadowMask.hasMultipleDifferentValues || serialized.renderPipelineSettings.supportedLitShaderMode.hasMultipleDifferentValues)
builder.AppendLine().AppendFormat(supportedFormaterMultipleValue, k_SupportShadowMaskContent.text);
else if (serialized.renderPipelineSettings.supportShadowMask.boolValue)
builder.AppendLine().AppendFormat(supportedFormater, k_SupportShadowMaskContent.text, k_SupportShadowMaskDrawbacks[supportedLitShaderMode]);
AppendSupport(builder, serialized.renderPipelineSettings.supportSSR, k_SupportSSRContent);
AppendSupport(builder, serialized.renderPipelineSettings.supportSSAO, k_SupportSSAOContent);
AppendSupport(builder, serialized.renderPipelineSettings.supportSubsurfaceScattering, k_SupportedSSSContent);
AppendSupport(builder, serialized.renderPipelineSettings.supportVolumetrics, k_SupportVolumetricContent);
if (serialized.renderPipelineSettings.supportLightLayers.hasMultipleDifferentValues)
builder.AppendLine().AppendFormat(supportedFormaterMultipleValue, k_SupportLightLayerContent.text);
else if (serialized.renderPipelineSettings.supportLightLayers.boolValue)
builder.AppendLine().AppendFormat(supportedFormater, k_SupportLightLayerContent.text, k_SupportLightLayerDrawbacks[supportedLitShaderMode]);
if (serialized.renderPipelineSettings.MSAASampleCount.hasMultipleDifferentValues)
builder.AppendLine().AppendFormat(supportedFormaterMultipleValue, k_MSAASampleCountContent.text);
else if (serialized.renderPipelineSettings.supportMSAA)
{
// NO MSAA in deferred
if (serialized.renderPipelineSettings.supportedLitShaderMode.intValue != (int)RenderPipelineSettings.SupportedLitShaderMode.DeferredOnly)
builder.AppendLine().AppendFormat(supportedFormater, "Multisample Anti-aliasing", k_SupportDrawbacks[k_MSAASampleCountContent]);
}
if (serialized.renderPipelineSettings.supportDecals.hasMultipleDifferentValues)
builder.AppendLine().AppendFormat(supportedFormaterMultipleValue, k_DecalsSubTitle.text);
else if (serialized.renderPipelineSettings.supportDecals.boolValue)
builder.AppendLine().AppendFormat(supportedFormater, k_DecalsSubTitle.text, k_SupportDrawbacks[k_SupportDecalContent]);
if (serialized.renderPipelineSettings.decalSettings.perChannelMask.hasMultipleDifferentValues)
builder.AppendLine().AppendFormat(supportedFormaterMultipleValue, k_DecalsMetalAndAOSubTitle.text);
else if (serialized.renderPipelineSettings.supportDecals.boolValue && serialized.renderPipelineSettings.decalSettings.perChannelMask.boolValue)
builder.AppendLine().AppendFormat(supportedFormater, k_DecalsMetalAndAOSubTitle.text, k_SupportDrawbacks[k_MetalAndAOContent]);
AppendSupport(builder, serialized.renderPipelineSettings.supportMotionVectors, k_SupportMotionVectorContent);
AppendSupport(builder, serialized.renderPipelineSettings.supportRuntimeDebugDisplay, k_SupportRuntimeDebugDisplayContent);
AppendSupport(builder, serialized.renderPipelineSettings.supportDitheringCrossFade, k_SupportDitheringCrossFadeContent);
AppendSupport(builder, serialized.renderPipelineSettings.supportDistortion, k_SupportDistortion);
AppendSupport(builder, serialized.renderPipelineSettings.supportTransparentBackface, k_SupportTransparentBackface);
AppendSupport(builder, serialized.renderPipelineSettings.supportTransparentDepthPrepass, k_SupportTransparentDepthPrepass);
AppendSupport(builder, serialized.renderPipelineSettings.supportTransparentDepthPostpass, k_SupportTransparentDepthPostpass);
#if REALTIME_RAYTRACING_SUPPORT
AppendSupport(builder, serialized.renderPipelineSettings.supportRayTracing, k_SupportRaytracing);
#endif
EditorGUILayout.HelpBox(builder.ToString(), MessageType.Info, wide: true);
}
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using FluentAssertions;
using Microsoft.DotNet.PlatformAbstractions;
using Microsoft.DotNet.Tools.Test.Utilities;
using Microsoft.DotNet.CommandFactory;
using Xunit;
using Microsoft.DotNet.Cli.Utils;
namespace Microsoft.DotNet.Tests
{
public class GivenAnAppBaseCommandResolver
{
[Fact]
public void It_returns_null_when_CommandName_is_null()
{
var appBaseCommandResolver = SetupPlatformAppBaseCommandResolver(forceGeneric: true);
var commandResolverArguments = new CommandResolverArguments()
{
CommandName = null,
CommandArguments = null
};
var result = appBaseCommandResolver.Resolve(commandResolverArguments);
result.Should().BeNull();
}
[Fact]
public void It_returns_null_when_CommandName_does_not_exist_applocal()
{
var appBaseCommandResolver = SetupPlatformAppBaseCommandResolver(forceGeneric: true);
var commandResolverArguments = new CommandResolverArguments()
{
CommandName = "nonexistent-command",
CommandArguments = null
};
var result = appBaseCommandResolver.Resolve(commandResolverArguments);
result.Should().BeNull();
}
[Fact]
public void It_returns_a_CommandSpec_with_CommandName_as_FileName_when_CommandName_exists_applocal()
{
var environment = CommandResolverTestUtils.SetupEnvironmentProviderWhichFindsExtensions(".exe");
var appBaseCommandResolver = SetupPlatformAppBaseCommandResolver(environment, forceGeneric: true);
CommandResolverTestUtils.CreateNonRunnableTestCommand(AppContext.BaseDirectory, "appbasetestcommand1", ".exe");
var commandResolverArguments = new CommandResolverArguments()
{
CommandName = "appbasetestcommand1",
CommandArguments = null
};
var result = appBaseCommandResolver.Resolve(commandResolverArguments);
result.Should().NotBeNull();
var commandFile = Path.GetFileNameWithoutExtension(result.Path);
commandFile.Should().Be("appbasetestcommand1");
}
[Fact]
public void It_returns_null_when_CommandName_exists_applocal_in_a_subdirectory()
{
var environment = CommandResolverTestUtils.SetupEnvironmentProviderWhichFindsExtensions(".exe");
var appBaseCommandResolver = SetupPlatformAppBaseCommandResolver(environment, forceGeneric: true);
var testDir = Path.Combine(AppContext.BaseDirectory, "appbasetestsubdir");
CommandResolverTestUtils.CreateNonRunnableTestCommand(testDir, "appbasetestsubdircommand", ".exe");
var commandResolverArguments = new CommandResolverArguments()
{
CommandName = "appbasetestsubdircommand",
CommandArguments = null
};
var result = appBaseCommandResolver.Resolve(commandResolverArguments);
result.Should().BeNull();
}
[Fact]
public void It_escapes_CommandArguments_when_returning_a_CommandSpec()
{
var environment = CommandResolverTestUtils.SetupEnvironmentProviderWhichFindsExtensions(".exe");
var appBaseCommandResolver = SetupPlatformAppBaseCommandResolver(environment, forceGeneric: true);
CommandResolverTestUtils.CreateNonRunnableTestCommand(AppContext.BaseDirectory, "appbasetestcommand1", ".exe");
var commandResolverArguments = new CommandResolverArguments()
{
CommandName = "appbasetestcommand1",
CommandArguments = new[] { "arg with space" }
};
var result = appBaseCommandResolver.Resolve(commandResolverArguments);
result.Should().NotBeNull();
result.Args.Should().Be("\"arg with space\"");
}
[Fact]
public void It_returns_a_CommandSpec_with_Args_as_stringEmpty_when_returning_a_CommandSpec_and_CommandArguments_are_null()
{
var environment = CommandResolverTestUtils.SetupEnvironmentProviderWhichFindsExtensions(".exe");
var appBaseCommandResolver = SetupPlatformAppBaseCommandResolver(environment, forceGeneric: true);
CommandResolverTestUtils.CreateNonRunnableTestCommand(AppContext.BaseDirectory, "appbasetestcommand1", ".exe");
var commandResolverArguments = new CommandResolverArguments()
{
CommandName = "appbasetestcommand1",
CommandArguments = null
};
var result = appBaseCommandResolver.Resolve(commandResolverArguments);
result.Should().NotBeNull();
result.Args.Should().Be(string.Empty);
}
[Fact]
public void It_prefers_EXE_over_CMD_when_two_command_candidates_exist_and_using_WindowsExePreferredCommandSpecFactory()
{
var environment = CommandResolverTestUtils.SetupEnvironmentProviderWhichFindsExtensions(".exe");
var platformCommandSpecFactory = new WindowsExePreferredCommandSpecFactory();
var appBaseCommandResolver = new AppBaseCommandResolver(environment, platformCommandSpecFactory);
CommandResolverTestUtils.CreateNonRunnableTestCommand(AppContext.BaseDirectory, "appbasetestcommand1", ".exe");
CommandResolverTestUtils.CreateNonRunnableTestCommand(AppContext.BaseDirectory, "appbasetestcommand1", ".cmd");
var commandResolverArguments = new CommandResolverArguments()
{
CommandName = "appbasetestcommand1",
CommandArguments = null
};
var result = appBaseCommandResolver.Resolve(commandResolverArguments);
result.Should().NotBeNull();
var commandFile = Path.GetFileName(result.Path);
commandFile.Should().Be("appbasetestcommand1.exe");
}
[Fact]
public void It_wraps_command_with_CMD_EXE_when_command_has_CMD_Extension_and_using_WindowsExePreferredCommandSpecFactory()
{
var environment = new EnvironmentProvider(new[] { ".cmd" });
var platformCommandSpecFactory = new WindowsExePreferredCommandSpecFactory();
var pathCommandResolver = new PathCommandResolver(environment, platformCommandSpecFactory);
var testCommandPath =
CommandResolverTestUtils.CreateNonRunnableTestCommand(AppContext.BaseDirectory, "someWrapCommand", ".cmd");
var commandResolverArguments = new CommandResolverArguments()
{
CommandName = "someWrapCommand",
CommandArguments = null
};
var result = pathCommandResolver.Resolve(commandResolverArguments);
result.Should().NotBeNull();
var commandFile = Path.GetFileName(result.Path);
commandFile.Should().Be("cmd.exe");
result.Args.Should().Contain(testCommandPath);
}
private AppBaseCommandResolver SetupPlatformAppBaseCommandResolver(
IEnvironmentProvider environment = null,
bool forceGeneric = false)
{
environment = environment ?? new EnvironmentProvider();
IPlatformCommandSpecFactory platformCommandSpecFactory = new GenericPlatformCommandSpecFactory();
if (RuntimeEnvironment.OperatingSystemPlatform == Platform.Windows
&& !forceGeneric)
{
platformCommandSpecFactory = new WindowsExePreferredCommandSpecFactory();
}
var appBaseCommandResolver = new AppBaseCommandResolver(environment, platformCommandSpecFactory);
return appBaseCommandResolver;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics.Log;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Versions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics.EngineV1
{
internal partial class DiagnosticIncrementalAnalyzer : BaseDiagnosticIncrementalAnalyzer
{
private readonly int _correlationId;
private readonly MemberRangeMap _memberRangeMap;
private readonly AnalyzerExecutor _executor;
private readonly StateManager _stateManager;
private readonly SimpleTaskQueue _eventQueue;
public DiagnosticIncrementalAnalyzer(
DiagnosticAnalyzerService owner,
int correlationId,
Workspace workspace,
HostAnalyzerManager analyzerManager,
AbstractHostDiagnosticUpdateSource hostDiagnosticUpdateSource)
: base(owner, workspace, analyzerManager, hostDiagnosticUpdateSource)
{
_correlationId = correlationId;
_memberRangeMap = new MemberRangeMap();
_executor = new AnalyzerExecutor(this);
_eventQueue = new SimpleTaskQueue(TaskScheduler.Default);
_stateManager = new StateManager(analyzerManager);
_stateManager.ProjectAnalyzerReferenceChanged += OnProjectAnalyzerReferenceChanged;
}
private void OnProjectAnalyzerReferenceChanged(object sender, ProjectAnalyzerReferenceChangedEventArgs e)
{
if (e.Removed.Length == 0)
{
// nothing to refresh
return;
}
// guarantee order of the events.
var asyncToken = Owner.Listener.BeginAsyncOperation(nameof(OnProjectAnalyzerReferenceChanged));
_eventQueue.ScheduleTask(() => ClearProjectStatesAsync(e.Project, e.Removed, CancellationToken.None), CancellationToken.None).CompletesAsyncOperation(asyncToken);
}
public override Task DocumentOpenAsync(Document document, CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Diagnostics_DocumentOpen, GetOpenLogMessage, document, cancellationToken))
{
return ClearOnlyDocumentStates(document, raiseEvent: true, cancellationToken: cancellationToken);
}
}
public override Task DocumentCloseAsync(Document document, CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Diagnostics_DocumentClose, GetResetLogMessage, document, cancellationToken))
{
// we don't need the info for closed file
_memberRangeMap.Remove(document.Id);
return ClearOnlyDocumentStates(document, raiseEvent: true, cancellationToken: cancellationToken);
}
}
public override Task DocumentResetAsync(Document document, CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Diagnostics_DocumentReset, GetResetLogMessage, document, cancellationToken))
{
// unlike document open or close where we don't know whether this document will be re-analyzed again due to
// engine's option such as "Close File Diagnostics", this one will be called when we want to re-analyze the document
// for whatever reason. so we let events to be raised when actual analysis happens but clear the cache so that
// we don't return existing data without re-analysis.
return ClearOnlyDocumentStates(document, raiseEvent: false, cancellationToken: cancellationToken);
}
}
private Task ClearOnlyDocumentStates(Document document, bool raiseEvent, CancellationToken cancellationToken)
{
// we remove whatever information we used to have on document open/close and re-calculate diagnostics
// we had to do this since some diagnostic analyzer changes its behavior based on whether the document is opened or not.
// so we can't use cached information.
ClearDocumentStates(document, _stateManager.GetStateSets(document.Project), raiseEvent, includeProjectState: false, cancellationToken: cancellationToken);
return SpecializedTasks.EmptyTask;
}
private bool CheckOption(Workspace workspace, string language, bool documentOpened)
{
var optionService = workspace.Services.GetService<IOptionService>();
if (optionService == null || optionService.GetOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic, language))
{
return true;
}
if (documentOpened)
{
return true;
}
return false;
}
internal IEnumerable<DiagnosticAnalyzer> GetAnalyzers(Project project)
{
return _stateManager.GetAnalyzers(project);
}
public override async Task AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken)
{
await AnalyzeSyntaxAsync(document, diagnosticIds: null, skipClosedFileChecks: false, cancellationToken: cancellationToken).ConfigureAwait(false);
}
private async Task AnalyzeSyntaxAsync(Document document, ImmutableHashSet<string> diagnosticIds, bool skipClosedFileChecks, CancellationToken cancellationToken)
{
try
{
if (!skipClosedFileChecks && !CheckOption(document.Project.Solution.Workspace, document.Project.Language, document.IsOpen()))
{
return;
}
var textVersion = await document.GetTextVersionAsync(cancellationToken).ConfigureAwait(false);
var dataVersion = await document.GetSyntaxVersionAsync(cancellationToken).ConfigureAwait(false);
var versions = new VersionArgument(textVersion, dataVersion);
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var fullSpan = root == null ? null : (TextSpan?)root.FullSpan;
var userDiagnosticDriver = new DiagnosticAnalyzerDriver(document, fullSpan, root, this, cancellationToken);
var openedDocument = document.IsOpen();
foreach (var stateSet in _stateManager.GetOrUpdateStateSets(document.Project))
{
if (SkipRunningAnalyzer(document.Project.CompilationOptions, userDiagnosticDriver, openedDocument, skipClosedFileChecks, stateSet))
{
await ClearExistingDiagnostics(document, stateSet, StateType.Syntax, cancellationToken).ConfigureAwait(false);
continue;
}
if (ShouldRunAnalyzerForStateType(stateSet.Analyzer, StateType.Syntax, diagnosticIds))
{
var data = await _executor.GetSyntaxAnalysisDataAsync(userDiagnosticDriver, stateSet, versions).ConfigureAwait(false);
if (data.FromCache)
{
RaiseDiagnosticsUpdated(StateType.Syntax, document.Id, stateSet, new SolutionArgument(document), data.Items);
continue;
}
var state = stateSet.GetState(StateType.Syntax);
await state.PersistAsync(document, data.ToPersistData(), cancellationToken).ConfigureAwait(false);
RaiseDocumentDiagnosticsUpdatedIfNeeded(StateType.Syntax, document, stateSet, data.OldItems, data.Items);
}
}
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
public override async Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, CancellationToken cancellationToken)
{
await AnalyzeDocumentAsync(document, bodyOpt, diagnosticIds: null, skipClosedFileChecks: false, cancellationToken: cancellationToken).ConfigureAwait(false);
}
private async Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, ImmutableHashSet<string> diagnosticIds, bool skipClosedFileChecks, CancellationToken cancellationToken)
{
try
{
if (!skipClosedFileChecks && !CheckOption(document.Project.Solution.Workspace, document.Project.Language, document.IsOpen()))
{
return;
}
var textVersion = await document.GetTextVersionAsync(cancellationToken).ConfigureAwait(false);
var projectVersion = await document.Project.GetDependentVersionAsync(cancellationToken).ConfigureAwait(false);
var dataVersion = await document.Project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false);
var versions = new VersionArgument(textVersion, dataVersion, projectVersion);
if (bodyOpt == null)
{
await AnalyzeDocumentAsync(document, versions, diagnosticIds, skipClosedFileChecks, cancellationToken).ConfigureAwait(false);
}
else
{
// only open file can go this route
await AnalyzeBodyDocumentAsync(document, bodyOpt, versions, cancellationToken).ConfigureAwait(false);
}
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private async Task AnalyzeBodyDocumentAsync(Document document, SyntaxNode member, VersionArgument versions, CancellationToken cancellationToken)
{
try
{
// syntax facts service must exist, otherwise, this method won't have called.
var syntaxFacts = document.Project.LanguageServices.GetService<ISyntaxFactsService>();
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var memberId = syntaxFacts.GetMethodLevelMemberId(root, member);
var spanBasedDriver = new DiagnosticAnalyzerDriver(document, member.FullSpan, root, this, cancellationToken);
var documentBasedDriver = new DiagnosticAnalyzerDriver(document, root.FullSpan, root, this, cancellationToken);
foreach (var stateSet in _stateManager.GetOrUpdateStateSets(document.Project))
{
if (Owner.IsAnalyzerSuppressed(stateSet.Analyzer, document.Project))
{
await ClearExistingDiagnostics(document, stateSet, StateType.Document, cancellationToken).ConfigureAwait(false);
continue;
}
if (ShouldRunAnalyzerForStateType(stateSet.Analyzer, StateType.Document))
{
var supportsSemanticInSpan = stateSet.Analyzer.SupportsSpanBasedSemanticDiagnosticAnalysis();
var userDiagnosticDriver = supportsSemanticInSpan ? spanBasedDriver : documentBasedDriver;
var ranges = _memberRangeMap.GetSavedMemberRange(stateSet.Analyzer, document);
var data = await _executor.GetDocumentBodyAnalysisDataAsync(
stateSet, versions, userDiagnosticDriver, root, member, memberId, supportsSemanticInSpan, ranges).ConfigureAwait(false);
_memberRangeMap.UpdateMemberRange(stateSet.Analyzer, document, versions.TextVersion, memberId, member.FullSpan, ranges);
var state = stateSet.GetState(StateType.Document);
await state.PersistAsync(document, data.ToPersistData(), cancellationToken).ConfigureAwait(false);
if (data.FromCache)
{
RaiseDiagnosticsUpdated(StateType.Document, document.Id, stateSet, new SolutionArgument(document), data.Items);
continue;
}
RaiseDocumentDiagnosticsUpdatedIfNeeded(StateType.Document, document, stateSet, data.OldItems, data.Items);
}
}
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private async Task AnalyzeDocumentAsync(Document document, VersionArgument versions, ImmutableHashSet<string> diagnosticIds, bool skipClosedFileChecks, CancellationToken cancellationToken)
{
try
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var fullSpan = root == null ? null : (TextSpan?)root.FullSpan;
var userDiagnosticDriver = new DiagnosticAnalyzerDriver(document, fullSpan, root, this, cancellationToken);
bool openedDocument = document.IsOpen();
foreach (var stateSet in _stateManager.GetOrUpdateStateSets(document.Project))
{
if (SkipRunningAnalyzer(document.Project.CompilationOptions, userDiagnosticDriver, openedDocument, skipClosedFileChecks, stateSet))
{
await ClearExistingDiagnostics(document, stateSet, StateType.Document, cancellationToken).ConfigureAwait(false);
continue;
}
if (ShouldRunAnalyzerForStateType(stateSet.Analyzer, StateType.Document, diagnosticIds))
{
var data = await _executor.GetDocumentAnalysisDataAsync(userDiagnosticDriver, stateSet, versions).ConfigureAwait(false);
if (data.FromCache)
{
RaiseDiagnosticsUpdated(StateType.Document, document.Id, stateSet, new SolutionArgument(document), data.Items);
continue;
}
if (openedDocument)
{
_memberRangeMap.Touch(stateSet.Analyzer, document, versions.TextVersion);
}
var state = stateSet.GetState(StateType.Document);
await state.PersistAsync(document, data.ToPersistData(), cancellationToken).ConfigureAwait(false);
RaiseDocumentDiagnosticsUpdatedIfNeeded(StateType.Document, document, stateSet, data.OldItems, data.Items);
}
}
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
public override async Task AnalyzeProjectAsync(Project project, bool semanticsChanged, CancellationToken cancellationToken)
{
await AnalyzeProjectAsync(project, cancellationToken).ConfigureAwait(false);
}
private async Task AnalyzeProjectAsync(Project project, CancellationToken cancellationToken)
{
try
{
// Compilation actions can report diagnostics on open files, so "documentOpened = true"
if (!CheckOption(project.Solution.Workspace, project.Language, documentOpened: true))
{
return;
}
var projectTextVersion = await project.GetLatestDocumentVersionAsync(cancellationToken).ConfigureAwait(false);
var semanticVersion = await project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false);
var projectVersion = await project.GetDependentVersionAsync(cancellationToken).ConfigureAwait(false);
var analyzerDriver = new DiagnosticAnalyzerDriver(project, this, cancellationToken);
var versions = new VersionArgument(projectTextVersion, semanticVersion, projectVersion);
foreach (var stateSet in _stateManager.GetOrUpdateStateSets(project))
{
// Compilation actions can report diagnostics on open files, so we skipClosedFileChecks.
if (SkipRunningAnalyzer(project.CompilationOptions, analyzerDriver, openedDocument: true, skipClosedFileChecks: true, stateSet: stateSet))
{
await ClearExistingDiagnostics(project, stateSet, cancellationToken).ConfigureAwait(false);
continue;
}
if (ShouldRunAnalyzerForStateType(stateSet.Analyzer, StateType.Project, diagnosticIds: null))
{
var data = await _executor.GetProjectAnalysisDataAsync(analyzerDriver, stateSet, versions).ConfigureAwait(false);
if (data.FromCache)
{
RaiseProjectDiagnosticsUpdated(project, stateSet, data.Items);
continue;
}
var state = stateSet.GetState(StateType.Project);
await PersistProjectData(project, state, data).ConfigureAwait(false);
RaiseProjectDiagnosticsUpdatedIfNeeded(project, stateSet, data.OldItems, data.Items);
}
}
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private bool SkipRunningAnalyzer(
CompilationOptions compilationOptions,
DiagnosticAnalyzerDriver userDiagnosticDriver,
bool openedDocument,
bool skipClosedFileChecks,
StateSet stateSet)
{
if (Owner.IsAnalyzerSuppressed(stateSet.Analyzer, userDiagnosticDriver.Project))
{
return true;
}
if (skipClosedFileChecks)
{
return false;
}
if (ShouldRunAnalyzerForClosedFile(compilationOptions, openedDocument, stateSet.Analyzer))
{
return false;
}
return true;
}
private static async Task PersistProjectData(Project project, DiagnosticState state, AnalysisData data)
{
// TODO: Cancellation is not allowed here to prevent data inconsistency. But there is still a possibility of data inconsistency due to
// things like exception. For now, I am letting it go and let v2 engine take care of it properly. If v2 doesn't come online soon enough
// more refactoring is required on project state.
// clear all existing data
state.Remove(project.Id);
foreach (var document in project.Documents)
{
state.Remove(document.Id);
}
// quick bail out
if (data.Items.Length == 0)
{
return;
}
// save new data
var group = data.Items.GroupBy(d => d.DocumentId);
foreach (var kv in group)
{
if (kv.Key == null)
{
// save project scope diagnostics
await state.PersistAsync(project, new AnalysisData(data.TextVersion, data.DataVersion, kv.ToImmutableArrayOrEmpty()), CancellationToken.None).ConfigureAwait(false);
continue;
}
// save document scope diagnostics
var document = project.GetDocument(kv.Key);
if (document == null)
{
continue;
}
await state.PersistAsync(document, new AnalysisData(data.TextVersion, data.DataVersion, kv.ToImmutableArrayOrEmpty()), CancellationToken.None).ConfigureAwait(false);
}
}
public override void RemoveDocument(DocumentId documentId)
{
using (Logger.LogBlock(FunctionId.Diagnostics_RemoveDocument, GetRemoveLogMessage, documentId, CancellationToken.None))
{
_memberRangeMap.Remove(documentId);
foreach (var stateSet in _stateManager.GetStateSets(documentId.ProjectId))
{
stateSet.Remove(documentId);
var solutionArgs = new SolutionArgument(null, documentId.ProjectId, documentId);
for (var stateType = 0; stateType < s_stateTypeCount; stateType++)
{
RaiseDiagnosticsUpdated((StateType)stateType, documentId, stateSet, solutionArgs, ImmutableArray<DiagnosticData>.Empty);
}
}
}
}
public override void RemoveProject(ProjectId projectId)
{
using (Logger.LogBlock(FunctionId.Diagnostics_RemoveProject, GetRemoveLogMessage, projectId, CancellationToken.None))
{
foreach (var stateSet in _stateManager.GetStateSets(projectId))
{
stateSet.Remove(projectId);
var solutionArgs = new SolutionArgument(null, projectId, null);
RaiseDiagnosticsUpdated(StateType.Project, projectId, stateSet, solutionArgs, ImmutableArray<DiagnosticData>.Empty);
}
}
_stateManager.RemoveStateSet(projectId);
}
public override async Task<bool> TryAppendDiagnosticsForSpanAsync(Document document, TextSpan range, List<DiagnosticData> diagnostics, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default(CancellationToken))
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var getter = new LatestDiagnosticsForSpanGetter(this, document, root, range, blockForData: false, diagnostics: diagnostics, includeSuppressedDiagnostics: includeSuppressedDiagnostics, cancellationToken: cancellationToken);
return await getter.TryGetAsync().ConfigureAwait(false);
}
public override async Task<IEnumerable<DiagnosticData>> GetDiagnosticsForSpanAsync(Document document, TextSpan range, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default(CancellationToken))
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var getter = new LatestDiagnosticsForSpanGetter(this, document, root, range, blockForData: true, includeSuppressedDiagnostics: includeSuppressedDiagnostics, cancellationToken: cancellationToken);
var result = await getter.TryGetAsync().ConfigureAwait(false);
Contract.Requires(result);
return getter.Diagnostics;
}
private bool ShouldRunAnalyzerForClosedFile(CompilationOptions options, bool openedDocument, DiagnosticAnalyzer analyzer)
{
// we have opened document, doesn't matter
if (openedDocument || analyzer.IsCompilerAnalyzer())
{
return true;
}
// PERF: Don't query descriptors for compiler analyzer, always execute it.
if (analyzer.IsCompilerAnalyzer())
{
return true;
}
return Owner.GetDiagnosticDescriptors(analyzer).Any(d => GetEffectiveSeverity(d, options) != ReportDiagnostic.Hidden);
}
private static ReportDiagnostic GetEffectiveSeverity(DiagnosticDescriptor descriptor, CompilationOptions options)
{
return options == null
? MapSeverityToReport(descriptor.DefaultSeverity)
: descriptor.GetEffectiveSeverity(options);
}
private static ReportDiagnostic MapSeverityToReport(DiagnosticSeverity severity)
{
switch (severity)
{
case DiagnosticSeverity.Hidden:
return ReportDiagnostic.Hidden;
case DiagnosticSeverity.Info:
return ReportDiagnostic.Info;
case DiagnosticSeverity.Warning:
return ReportDiagnostic.Warn;
case DiagnosticSeverity.Error:
return ReportDiagnostic.Error;
default:
throw ExceptionUtilities.Unreachable;
}
}
private bool ShouldRunAnalyzerForStateType(DiagnosticAnalyzer analyzer, StateType stateTypeId, ImmutableHashSet<string> diagnosticIds)
{
return ShouldRunAnalyzerForStateType(analyzer, stateTypeId, diagnosticIds, Owner.GetDiagnosticDescriptors);
}
private static bool ShouldRunAnalyzerForStateType(DiagnosticAnalyzer analyzer, StateType stateTypeId,
ImmutableHashSet<string> diagnosticIds = null, Func<DiagnosticAnalyzer, ImmutableArray<DiagnosticDescriptor>> getDescriptors = null)
{
// PERF: Don't query descriptors for compiler analyzer, always execute it for all state types.
if (analyzer.IsCompilerAnalyzer())
{
return true;
}
if (diagnosticIds != null && getDescriptors(analyzer).All(d => !diagnosticIds.Contains(d.Id)))
{
return false;
}
switch (stateTypeId)
{
case StateType.Syntax:
return analyzer.SupportsSyntaxDiagnosticAnalysis();
case StateType.Document:
return analyzer.SupportsSemanticDiagnosticAnalysis();
case StateType.Project:
return analyzer.SupportsProjectDiagnosticAnalysis();
default:
throw ExceptionUtilities.Unreachable;
}
}
public override void LogAnalyzerCountSummary()
{
DiagnosticAnalyzerLogger.LogAnalyzerCrashCountSummary(_correlationId, DiagnosticLogAggregator);
DiagnosticAnalyzerLogger.LogAnalyzerTypeCountSummary(_correlationId, DiagnosticLogAggregator);
// reset the log aggregator
ResetDiagnosticLogAggregator();
}
private static bool CheckSyntaxVersions(Document document, AnalysisData existingData, VersionArgument versions)
{
if (existingData == null)
{
return false;
}
return document.CanReusePersistedTextVersion(versions.TextVersion, existingData.TextVersion) &&
document.CanReusePersistedSyntaxTreeVersion(versions.DataVersion, existingData.DataVersion);
}
private static bool CheckSemanticVersions(Document document, AnalysisData existingData, VersionArgument versions)
{
if (existingData == null)
{
return false;
}
return document.CanReusePersistedTextVersion(versions.TextVersion, existingData.TextVersion) &&
document.Project.CanReusePersistedDependentSemanticVersion(versions.ProjectVersion, versions.DataVersion, existingData.DataVersion);
}
private static bool CheckSemanticVersions(Project project, AnalysisData existingData, VersionArgument versions)
{
if (existingData == null)
{
return false;
}
return VersionStamp.CanReusePersistedVersion(versions.TextVersion, existingData.TextVersion) &&
project.CanReusePersistedDependentSemanticVersion(versions.ProjectVersion, versions.DataVersion, existingData.DataVersion);
}
private void RaiseDocumentDiagnosticsUpdatedIfNeeded(
StateType type, Document document, StateSet stateSet, ImmutableArray<DiagnosticData> existingItems, ImmutableArray<DiagnosticData> newItems)
{
var noItems = existingItems.Length == 0 && newItems.Length == 0;
if (noItems)
{
return;
}
RaiseDiagnosticsUpdated(type, document.Id, stateSet, new SolutionArgument(document), newItems);
}
private void RaiseProjectDiagnosticsUpdatedIfNeeded(
Project project, StateSet stateSet, ImmutableArray<DiagnosticData> existingItems, ImmutableArray<DiagnosticData> newItems)
{
var noItems = existingItems.Length == 0 && newItems.Length == 0;
if (noItems)
{
return;
}
RaiseProjectDiagnosticsRemovedIfNeeded(project, stateSet, existingItems, newItems);
RaiseProjectDiagnosticsUpdated(project, stateSet, newItems);
}
private void RaiseProjectDiagnosticsRemovedIfNeeded(
Project project, StateSet stateSet, ImmutableArray<DiagnosticData> existingItems, ImmutableArray<DiagnosticData> newItems)
{
if (existingItems.Length == 0)
{
return;
}
var removedItems = existingItems.GroupBy(d => d.DocumentId).Select(g => g.Key).Except(newItems.GroupBy(d => d.DocumentId).Select(g => g.Key));
foreach (var documentId in removedItems)
{
if (documentId == null)
{
RaiseDiagnosticsUpdated(StateType.Project, project.Id, stateSet, new SolutionArgument(project), ImmutableArray<DiagnosticData>.Empty);
continue;
}
var document = project.GetDocument(documentId);
var argument = documentId == null ? new SolutionArgument(null, documentId.ProjectId, documentId) : new SolutionArgument(document);
RaiseDiagnosticsUpdated(StateType.Project, documentId, stateSet, argument, ImmutableArray<DiagnosticData>.Empty);
}
}
private void RaiseProjectDiagnosticsUpdated(Project project, StateSet stateSet, ImmutableArray<DiagnosticData> diagnostics)
{
var group = diagnostics.GroupBy(d => d.DocumentId);
foreach (var kv in group)
{
if (kv.Key == null)
{
RaiseDiagnosticsUpdated(StateType.Project, project.Id, stateSet, new SolutionArgument(project), kv.ToImmutableArrayOrEmpty());
continue;
}
RaiseDiagnosticsUpdated(StateType.Project, kv.Key, stateSet, new SolutionArgument(project.GetDocument(kv.Key)), kv.ToImmutableArrayOrEmpty());
}
}
private static ImmutableArray<DiagnosticData> GetDiagnosticData(ILookup<DocumentId, DiagnosticData> lookup, DocumentId documentId)
{
return lookup.Contains(documentId) ? lookup[documentId].ToImmutableArrayOrEmpty() : ImmutableArray<DiagnosticData>.Empty;
}
private void RaiseDiagnosticsUpdated(
StateType type, object key, StateSet stateSet, SolutionArgument solution, ImmutableArray<DiagnosticData> diagnostics)
{
if (Owner == null)
{
return;
}
// get right arg id for the given analyzer
var id = stateSet.ErrorSourceName != null ?
new HostAnalyzerKey(stateSet.Analyzer, type, key, stateSet.ErrorSourceName) : (object)new ArgumentKey(stateSet.Analyzer, type, key);
Owner.RaiseDiagnosticsUpdated(this,
new DiagnosticsUpdatedArgs(id, Workspace, solution.Solution, solution.ProjectId, solution.DocumentId, diagnostics));
}
private ImmutableArray<DiagnosticData> UpdateDocumentDiagnostics(
AnalysisData existingData, ImmutableArray<TextSpan> range, ImmutableArray<DiagnosticData> memberDiagnostics,
SyntaxTree tree, SyntaxNode member, int memberId)
{
// get old span
var oldSpan = range[memberId];
// get old diagnostics
var diagnostics = existingData.Items;
// check quick exit cases
if (diagnostics.Length == 0 && memberDiagnostics.Length == 0)
{
return diagnostics;
}
// simple case
if (diagnostics.Length == 0 && memberDiagnostics.Length > 0)
{
return memberDiagnostics;
}
// regular case
var result = new List<DiagnosticData>();
// update member location
Contract.Requires(member.FullSpan.Start == oldSpan.Start);
var delta = member.FullSpan.End - oldSpan.End;
var replaced = false;
foreach (var diagnostic in diagnostics)
{
if (diagnostic.TextSpan.Start < oldSpan.Start)
{
result.Add(diagnostic);
continue;
}
if (!replaced)
{
result.AddRange(memberDiagnostics);
replaced = true;
}
if (oldSpan.End <= diagnostic.TextSpan.Start)
{
result.Add(UpdatePosition(diagnostic, tree, delta));
continue;
}
}
// if it haven't replaced, replace it now
if (!replaced)
{
result.AddRange(memberDiagnostics);
replaced = true;
}
return result.ToImmutableArray();
}
private DiagnosticData UpdatePosition(DiagnosticData diagnostic, SyntaxTree tree, int delta)
{
var start = Math.Min(Math.Max(diagnostic.TextSpan.Start + delta, 0), tree.Length);
var newSpan = new TextSpan(start, start >= tree.Length ? 0 : diagnostic.TextSpan.Length);
var mappedLineInfo = tree.GetMappedLineSpan(newSpan);
var originalLineInfo = tree.GetLineSpan(newSpan);
return new DiagnosticData(
diagnostic.Id,
diagnostic.Category,
diagnostic.Message,
diagnostic.ENUMessageForBingSearch,
diagnostic.Severity,
diagnostic.DefaultSeverity,
diagnostic.IsEnabledByDefault,
diagnostic.WarningLevel,
diagnostic.CustomTags,
diagnostic.Properties,
diagnostic.Workspace,
diagnostic.ProjectId,
new DiagnosticDataLocation(diagnostic.DocumentId, newSpan,
originalFilePath: originalLineInfo.Path,
originalStartLine: originalLineInfo.StartLinePosition.Line,
originalStartColumn: originalLineInfo.StartLinePosition.Character,
originalEndLine: originalLineInfo.EndLinePosition.Line,
originalEndColumn: originalLineInfo.EndLinePosition.Character,
mappedFilePath: mappedLineInfo.GetMappedFilePathIfExist(),
mappedStartLine: mappedLineInfo.StartLinePosition.Line,
mappedStartColumn: mappedLineInfo.StartLinePosition.Character,
mappedEndLine: mappedLineInfo.EndLinePosition.Line,
mappedEndColumn: mappedLineInfo.EndLinePosition.Character),
description: diagnostic.Description,
helpLink: diagnostic.HelpLink,
isSuppressed: diagnostic.IsSuppressed);
}
private static IEnumerable<DiagnosticData> GetDiagnosticData(Document document, SyntaxTree tree, TextSpan? span, IEnumerable<Diagnostic> diagnostics)
{
return diagnostics != null ? diagnostics.Where(dx => ShouldIncludeDiagnostic(dx, tree, span)).Select(d => DiagnosticData.Create(document, d)) : null;
}
private static bool ShouldIncludeDiagnostic(Diagnostic diagnostic, SyntaxTree tree, TextSpan? span)
{
if (diagnostic == null)
{
return false;
}
if (diagnostic.Location == null || diagnostic.Location == Location.None)
{
return false;
}
if (diagnostic.Location.SourceTree != tree)
{
return false;
}
if (span == null)
{
return true;
}
return span.Value.Contains(diagnostic.Location.SourceSpan);
}
private static IEnumerable<DiagnosticData> GetDiagnosticData(Project project, IEnumerable<Diagnostic> diagnostics)
{
if (diagnostics == null)
{
yield break;
}
foreach (var diagnostic in diagnostics)
{
if (diagnostic.Location == null || diagnostic.Location == Location.None)
{
yield return DiagnosticData.Create(project, diagnostic);
continue;
}
var document = project.GetDocument(diagnostic.Location.SourceTree);
if (document == null)
{
continue;
}
yield return DiagnosticData.Create(document, diagnostic);
}
}
private static async Task<IEnumerable<DiagnosticData>> GetSyntaxDiagnosticsAsync(DiagnosticAnalyzerDriver userDiagnosticDriver, DiagnosticAnalyzer analyzer)
{
using (Logger.LogBlock(FunctionId.Diagnostics_SyntaxDiagnostic, GetSyntaxLogMessage, userDiagnosticDriver.Document, userDiagnosticDriver.Span, analyzer, userDiagnosticDriver.CancellationToken))
{
try
{
Contract.ThrowIfNull(analyzer);
var tree = await userDiagnosticDriver.Document.GetSyntaxTreeAsync(userDiagnosticDriver.CancellationToken).ConfigureAwait(false);
var diagnostics = await userDiagnosticDriver.GetSyntaxDiagnosticsAsync(analyzer).ConfigureAwait(false);
return GetDiagnosticData(userDiagnosticDriver.Document, tree, userDiagnosticDriver.Span, diagnostics);
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
}
private static async Task<IEnumerable<DiagnosticData>> GetSemanticDiagnosticsAsync(DiagnosticAnalyzerDriver userDiagnosticDriver, DiagnosticAnalyzer analyzer)
{
using (Logger.LogBlock(FunctionId.Diagnostics_SemanticDiagnostic, GetSemanticLogMessage, userDiagnosticDriver.Document, userDiagnosticDriver.Span, analyzer, userDiagnosticDriver.CancellationToken))
{
try
{
Contract.ThrowIfNull(analyzer);
var tree = await userDiagnosticDriver.Document.GetSyntaxTreeAsync(userDiagnosticDriver.CancellationToken).ConfigureAwait(false);
var diagnostics = await userDiagnosticDriver.GetSemanticDiagnosticsAsync(analyzer).ConfigureAwait(false);
return GetDiagnosticData(userDiagnosticDriver.Document, tree, userDiagnosticDriver.Span, diagnostics);
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
}
private static async Task<IEnumerable<DiagnosticData>> GetProjectDiagnosticsAsync(DiagnosticAnalyzerDriver userDiagnosticDriver, DiagnosticAnalyzer analyzer)
{
using (Logger.LogBlock(FunctionId.Diagnostics_ProjectDiagnostic, GetProjectLogMessage, userDiagnosticDriver.Project, analyzer, userDiagnosticDriver.CancellationToken))
{
try
{
Contract.ThrowIfNull(analyzer);
var diagnostics = await userDiagnosticDriver.GetProjectDiagnosticsAsync(analyzer).ConfigureAwait(false);
return GetDiagnosticData(userDiagnosticDriver.Project, diagnostics);
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
}
private void ClearDocumentStates(
Document document, IEnumerable<StateSet> states,
bool raiseEvent, bool includeProjectState,
CancellationToken cancellationToken)
{
// Compiler + User diagnostics
foreach (var state in states)
{
for (var stateType = 0; stateType < s_stateTypeCount; stateType++)
{
if (!includeProjectState && stateType == (int)StateType.Project)
{
// don't re-set project state type
continue;
}
cancellationToken.ThrowIfCancellationRequested();
ClearDocumentState(document, state, (StateType)stateType, raiseEvent);
}
}
}
private void ClearDocumentState(Document document, StateSet stateSet, StateType type, bool raiseEvent)
{
var state = stateSet.GetState(type);
// remove saved info
state.Remove(document.Id);
if (raiseEvent)
{
// raise diagnostic updated event
var documentId = document.Id;
var solutionArgs = new SolutionArgument(document);
RaiseDiagnosticsUpdated(type, document.Id, stateSet, solutionArgs, ImmutableArray<DiagnosticData>.Empty);
}
}
private void ClearProjectStatesAsync(Project project, IEnumerable<StateSet> states, CancellationToken cancellationToken)
{
foreach (var document in project.Documents)
{
ClearDocumentStates(document, states, raiseEvent: true, includeProjectState: true, cancellationToken: cancellationToken);
}
foreach (var stateSet in states)
{
cancellationToken.ThrowIfCancellationRequested();
ClearProjectState(project, stateSet);
}
}
private void ClearProjectState(Project project, StateSet stateSet)
{
var state = stateSet.GetState(StateType.Project);
// remove saved cache
state.Remove(project.Id);
// raise diagnostic updated event
var solutionArgs = new SolutionArgument(project);
RaiseDiagnosticsUpdated(StateType.Project, project.Id, stateSet, solutionArgs, ImmutableArray<DiagnosticData>.Empty);
}
private async Task ClearExistingDiagnostics(Document document, StateSet stateSet, StateType type, CancellationToken cancellationToken)
{
var state = stateSet.GetState(type);
var existingData = await state.TryGetExistingDataAsync(document, cancellationToken).ConfigureAwait(false);
if (existingData?.Items.Length > 0)
{
ClearDocumentState(document, stateSet, type, raiseEvent: true);
}
}
private async Task ClearExistingDiagnostics(Project project, StateSet stateSet, CancellationToken cancellationToken)
{
var state = stateSet.GetState(StateType.Project);
var existingData = await state.TryGetExistingDataAsync(project, cancellationToken).ConfigureAwait(false);
if (existingData?.Items.Length > 0)
{
ClearProjectState(project, stateSet);
}
}
private static string GetSyntaxLogMessage(Document document, TextSpan? span, DiagnosticAnalyzer analyzer)
{
return string.Format("syntax: {0}, {1}, {2}", document.FilePath ?? document.Name, span.HasValue ? span.Value.ToString() : "Full", analyzer.ToString());
}
private static string GetSemanticLogMessage(Document document, TextSpan? span, DiagnosticAnalyzer analyzer)
{
return string.Format("semantic: {0}, {1}, {2}", document.FilePath ?? document.Name, span.HasValue ? span.Value.ToString() : "Full", analyzer.ToString());
}
private static string GetProjectLogMessage(Project project, DiagnosticAnalyzer analyzer)
{
return string.Format("project: {0}, {1}", project.FilePath ?? project.Name, analyzer.ToString());
}
private static string GetResetLogMessage(Document document)
{
return string.Format("document reset: {0}", document.FilePath ?? document.Name);
}
private static string GetOpenLogMessage(Document document)
{
return string.Format("document open: {0}", document.FilePath ?? document.Name);
}
private static string GetRemoveLogMessage(DocumentId id)
{
return string.Format("document remove: {0}", id.ToString());
}
private static string GetRemoveLogMessage(ProjectId id)
{
return string.Format("project remove: {0}", id.ToString());
}
public override Task NewSolutionSnapshotAsync(Solution newSolution, CancellationToken cancellationToken)
{
return SpecializedTasks.EmptyTask;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace KaoriStudio.Core.Configuration
{
public partial class ConfigurationDictionary
{
/// <summary>
/// Tries to retrieve a value given a key
/// </summary>
/// <param name="key">The key</param>
/// <param name="value">The value output</param>
/// <returns>Whether the key could be found</returns>
public bool TryGetValue(string key, out object value)
{
if (this.arrayData != null)
{
if (key == null)
{
value = this.arrayData[0];
return true;
}
else
{
value = default(object);
return false;
}
}
else if (this.mapData != null)
{
for (int i = 0; i < this.mapData.Count; i++)
{
var pair = this.mapData[i];
if (key == pair.Key)
{
value = pair.Value;
return true;
}
}
value = default(object);
return false;
}
else
{
value = default(object);
return false;
}
}
/// <summary>
/// Addresses values of this configuration map by key
/// </summary>
/// <param name="key">The key of the pair</param>
/// <returns>The value of the associated value</returns>
public object this[string key]
{
get
{
if (this.arrayData != null)
{
if (key == null)
return this.arrayData[0];
else
throw KNFException(key);
}
else if (this.mapData != null)
{
for (int i = 0; i < this.mapData.Count; i++)
{
var pair = this.mapData[i];
if (key == pair.Key)
return pair.Value;
}
throw KNFException(key);
}
else
throw KNFException(key);
}
set
{
if (key == null)
{
if (this.arrayData != null)
{
this.arrayData.Add(value);
}
else if (this.mapData != null)
{
this.mapData.Add(new KeyValuePair<string, object>(null, value));
}
else
{
this.arrayData = new List<object>();
this.arrayData.Add(value);
}
}
else
{
if (this.arrayData != null)
this.ConvertToMap();
if (this.mapData == null)
this.mapData = new List<KeyValuePair<string, object>>();
else
{
for (int i = 0; i < this.mapData.Count; i++)
{
var pair = this.mapData[i];
if (pair.Key == null)
continue;
else if (pair.Key == key)
{
this.mapData[i] = new KeyValuePair<string, object>(key, value);
this._version++;
return;
}
}
}
this.mapData.Add(new KeyValuePair<string, object>(key, value));
}
}
}
/// <summary>
/// Addresses pairs of this configuration map by index
/// </summary>
/// <param name="index">The index</param>
/// <returns>The pair at the index</returns>
public KeyValuePair<string, object> this[int index]
{
get
{
if (this.arrayData != null)
{
return new KeyValuePair<string, object>(null, this.arrayData[index]);
}
else if (this.mapData != null)
{
return this.mapData[index];
}
else
{
throw new IndexOutOfRangeException();
}
}
set
{
if (this.arrayData != null)
{
if (value.Key == null)
{
this.arrayData[index] = value.Value;
this._version++;
}
else
{
this.ConvertToMap();
this.mapData[index] = value;
}
}
else if (this.mapData != null)
{
this.mapData[index] = value;
this._version++;
}
else
throw new IndexOutOfRangeException();
}
}
/// <summary>
/// Gets an accessor for casting values
/// </summary>
/// <typeparam name="T">The type to cast</typeparam>
/// <returns>Accessor for casting values</returns>
public CastAccessor<T> Caster<T>()
{
return new CastAccessor<T>(this);
}
/// <summary>
/// Gets an accessor for converting values
/// </summary>
/// <typeparam name="T">The type to cast</typeparam>
/// <returns>Accessor for converting values</returns>
public ConvertAccessor<T> Converter<T>()
{
return new ConvertAccessor<T>(this);
}
/// <summary>
/// Gets an accessor for parsing values
/// </summary>
/// <typeparam name="T">The type to cast</typeparam>
/// <returns>Accessor for parsing values</returns>
public ParseAccessor<T> Parser<T>()
{
return new ParseAccessor<T>(this);
}
/// <summary>
/// Accessor for casting values
/// </summary>
/// <typeparam name="T">The type to cast</typeparam>
public struct CastAccessor<T>
{
private ConfigurationDictionary map;
/// <summary>
/// Creates a CastAccessor
/// </summary>
/// <param name="map">The map</param>
public CastAccessor(ConfigurationDictionary map)
{
this.map = map;
}
/// <summary>
/// Accessor for casted values
/// </summary>
/// <param name="key">The key</param>
/// <returns>The value</returns>
public T this[string key]
{
get
{
return map.ValueAs<T>(key);
}
set
{
map.SetValueAs(key, value);
}
}
/// <summary>
/// Accessor for casted values
/// </summary>
/// <param name="key">The key</param>
/// <param name="def">The default value</param>
/// <returns>The value</returns>
public T this[string key, T def]
{
get
{
return map.ValueAs<T>(key, def);
}
}
}
/// <summary>
/// Accessor for converting values
/// </summary>
/// <typeparam name="T">The type to convert</typeparam>
public struct ConvertAccessor<T>
{
private ConfigurationDictionary map;
/// <summary>
/// Creates a ConvertAccessor
/// </summary>
/// <param name="map">The map</param>
public ConvertAccessor(ConfigurationDictionary map)
{
this.map = map;
}
/// <summary>
/// Accessor for converted values
/// </summary>
/// <param name="key">The key</param>
/// <returns>The value</returns>
public T this[string key]
{
get
{
return map.ConvertValueAs<T>(key);
}
set
{
map.ConvertSetValueAs(key, value);
}
}
/// <summary>
/// Accessor for converted values
/// </summary>
/// <param name="key">The key</param>
/// <param name="def">The default value</param>
/// <returns>The value</returns>
public T this[string key, T def]
{
get
{
return map.ConvertValueAs<T>(key, def);
}
}
}
/// <summary>
/// Accessor for parsing values
/// </summary>
/// <typeparam name="T">The type to parse</typeparam>
public struct ParseAccessor<T>
{
private ConfigurationDictionary map;
/// <summary>
/// Creates a ParseAccessor
/// </summary>
/// <param name="map">The map</param>
public ParseAccessor(ConfigurationDictionary map)
{
this.map = map;
}
/// <summary>
/// Accessor for parsed values
/// </summary>
/// <param name="key">The key</param>
/// <returns>The value</returns>
public T this[string key]
{
get
{
return map.ParseValueAs<T>(key);
}
set
{
map.ConvertSetValueAs(key, value);
}
}
/// <summary>
/// Accessor for parsed values
/// </summary>
/// <param name="key">The key</param>
/// <param name="def">The default value</param>
/// <returns>The value</returns>
public T this[string key, T def]
{
get
{
return map.ParseValueAs<T>(key, def);
}
}
}
}
}
| |
using System;
namespace qf4net
{
/// <summary>
/// QEventManager.
/// </summary>
public abstract class QEventManagerBase : QEventManagerEventsBase, IQEventManager
{
public QEventManagerBase (IQTimer timer)
{
_Timer = timer;
_Timer.TimeOut += new QTimeoutHandler(_Timer_TimeOut);
}
#region Message Queue
object _QLock = new Object ();
System.Threading.AutoResetEvent _WaitHandle = new System.Threading.AutoResetEvent (false);
System.Collections.Stack _FrontStack = new System.Collections.Stack ();
System.Collections.Queue _BottomQueue = new System.Collections.Queue ();
public void Dispatch (IQHsm hsm, IQEvent ev)
{
AsyncDispatch (hsm, ev);
Poll ();
}
protected virtual void InternalDispatch (IQHsm hsm, IQEvent ev)
{
bool ok = hsm.DispatchWithExceptionTrap (ev, false);
if (ok)
{
ev.Commit ();
} else
{
ev.Abort ();
}
}
public void AsyncDispatch (IQHsm hsm, IQEvent ev)
{
HsmEventHolder holder = new HsmEventHolder (this, hsm, ev);
AsyncDispatch (holder);
}
public void AsyncDispatchFront (IQHsm hsm, IQEvent ev)
{
lock (_QLock)
{
#warning Using a stack will alway push the most recent event to the front - thus reversing instead of maintaining "insert" order
HsmEventHolder holder = new HsmEventHolder (this, hsm, ev);
_FrontStack.Push (holder);
}
_WaitHandle.Set ();
}
public void AsyncDispatch (IQSimpleCommand cmd)
{
lock (_QLock)
{
if (!(cmd is HsmEventHolder))
{
if (!(cmd is SimpleTransactionalCmd))
{
cmd = new SimpleTransactionalCmd (cmd);
}
}
_BottomQueue.Enqueue (cmd);
}
_WaitHandle.Set ();
}
public bool PollOne ()
{
front:
int count;
object queueEntry = null;
lock (_QLock)
{
count = _FrontStack.Count;
if (count > 0)
{
queueEntry = _FrontStack.Pop ();
} else
{
count = _BottomQueue.Count;
if (count > 0)
{
queueEntry = _BottomQueue.Dequeue ();
}
}
}
if (count > 0)
{
if (queueEntry == null)
{
Logger.Error ("---- QueueEntry is null! ----");
goto front;
}
IQSimpleCommand command = queueEntry as IQSimpleCommand;
if (command == null)
{
Logger.Error ("---- Command is null! ----");
goto front;
}
Execute (command);
return true;
}
return false;
}
internal void DispatchFromEventHolder (HsmEventHolder holder)
{
System.Diagnostics.Debug.Assert (holder != null);
try
{
System.Security.Principal.IPrincipal previousPrincipal = System.Threading.Thread.CurrentPrincipal;
System.Threading.Thread.CurrentPrincipal = holder.Principal;
DoPolledEvent (this, holder, PollContext.BeforeHandled);
InternalDispatch (holder.Hsm, holder.Event);
DoPolledEvent (this, holder, PollContext.AfterHandled);
System.Threading.Thread.CurrentPrincipal = previousPrincipal;
}
catch (Exception ex)
{
DoEventManagerDispatchException (this, ex, holder.Hsm, holder.Event);
}
}
protected void Execute (IQSimpleCommand cmd)
{
try
{
cmd.Execute ();
}
catch (Exception ex)
{
DoEventManagerDispatchCommandException (this, ex, cmd);
}
}
IQEventManagerRunner _Runner;
public IQEventManagerRunner Runner
{
get { return _Runner; }
set { _Runner = value; }
}
public bool Poll ()
{
bool ok = false;
while (PollOne ())
{
ok = true;
}
return ok;
}
public bool WaitOne (TimeSpan duration)
{
return _WaitHandle.WaitOne (duration, true);
}
protected override bool OnEventManagerDispatchException (IQEventManager eventManager, Exception ex, IQHsm hsm, IQEvent ev)
{
/* -- we're not ready for this type of thing yet. EventManagerDispatchException is an exception experienced by the eventManager
* -- while trying to dispatch an event to an hsm.
DispatchExceptionFailureEventArgs args = new DispatchExceptionFailureEventArgs (eventManager, ex, hsm, ev);
AsyncDispatchFront (hsm, new QEvent ("Failure", args));
*/
return base.OnEventManagerDispatchException (eventManager, ex, hsm, ev);
}
#endregion
#region TimeOuts
IQTimer _Timer;
public void SetTimeOut (string name, TimeSpan duration, IQHsm hsm, IQEvent ev)
{
_Timer.SetTimeOut (name, duration, hsm, ev);
}
public void SetTimeOut (string name, TimeSpan duration, IQHsm hsm, IQEvent ev, TimeOutType timeOutType)
{
_Timer.SetTimeOut (name, duration, hsm, ev, timeOutType);
}
public void SetTimeOut (string name, DateTime at, IQHsm hsm, IQEvent ev)
{
_Timer.SetTimeOut (name, at, hsm, ev);
}
public void SetTimeOut (string name, DateTime at, IQHsm hsm, IQEvent ev, TimeOutType timeOutType)
{
_Timer.SetTimeOut (name, at, hsm, ev, timeOutType);
}
public void ClearTimeOut (string name)
{
_Timer.ClearTimeOut (name);
}
private void _Timer_TimeOut(IQTimer timer, IQHsm hsm, IQEvent ev)
{
AsyncDispatchFront (hsm, ev);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using Complex = System.Numerics.Complex;
using System;
using System.Text;
using System.Collections.Generic;
using System.Numerics;
namespace Microsoft.Scripting.Utils {
using Math = System.Math;
public static class MathUtils {
/// <summary>
/// Calculates the quotient of two 32-bit signed integers rounded towards negative infinity.
/// </summary>
/// <param name="x">Dividend.</param>
/// <param name="y">Divisor.</param>
/// <returns>The quotient of the specified numbers rounded towards negative infinity, or <code>(int)Floor((double)x/(double)y)</code>.</returns>
/// <exception cref="DivideByZeroException"><paramref name="y"/> is 0.</exception>
/// <remarks>The caller must check for overflow (x = Int32.MinValue, y = -1)</remarks>
public static int FloorDivideUnchecked(int x, int y) {
int q = x / y;
if (x >= 0) {
if (y > 0) {
return q;
}
if (x % y == 0) {
return q;
}
return q - 1;
}
if (y > 0) {
if (x % y == 0) {
return q;
}
return q - 1;
}
return q;
}
/// <summary>
/// Calculates the quotient of two 64-bit signed integers rounded towards negative infinity.
/// </summary>
/// <param name="x">Dividend.</param>
/// <param name="y">Divisor.</param>
/// <returns>The quotient of the specified numbers rounded towards negative infinity, or <code>(int)Floor((double)x/(double)y)</code>.</returns>
/// <exception cref="DivideByZeroException"><paramref name="y"/> is 0.</exception>
/// <remarks>The caller must check for overflow (x = Int64.MinValue, y = -1)</remarks>
public static long FloorDivideUnchecked(long x, long y) {
long q = x / y;
if (x >= 0) {
if (y > 0) {
return q;
}
if (x % y == 0) {
return q;
}
return q - 1;
}
if (y > 0) {
if (x % y == 0) {
return q;
}
return q - 1;
}
return q;
}
/// <summary>
/// Calculates the remainder of floor division of two 32-bit signed integers.
/// </summary>
/// <param name="x">Dividend.</param>
/// <param name="y">Divisor.</param>
/// <returns>The remainder of of floor division of the specified numbers, or <code>x - (int)Floor((double)x/(double)y) * y</code>.</returns>
/// <exception cref="DivideByZeroException"><paramref name="y"/> is 0.</exception>
public static int FloorRemainder(int x, int y) {
if (y == -1) return 0;
int r = x % y;
if (x >= 0) {
if (y > 0) {
return r;
} else if (r == 0) {
return 0;
} else {
return r + y;
}
} else {
if (y > 0) {
if (r == 0) {
return 0;
} else {
return r + y;
}
} else {
return r;
}
}
}
/// <summary>
/// Calculates the remainder of floor division of two 32-bit signed integers.
/// </summary>
/// <param name="x">Dividend.</param>
/// <param name="y">Divisor.</param>
/// <returns>The remainder of of floor division of the specified numbers, or <code>x - (int)Floor((double)x/(double)y) * y</code>.</returns>
/// <exception cref="DivideByZeroException"><paramref name="y"/> is 0.</exception>
public static long FloorRemainder(long x, long y) {
if (y == -1) return 0;
long r = x % y;
if (x >= 0) {
if (y > 0) {
return r;
} else if (r == 0) {
return 0;
} else {
return r + y;
}
} else {
if (y > 0) {
if (r == 0) {
return 0;
} else {
return r + y;
}
} else {
return r;
}
}
}
/// <summary>
/// Behaves like Math.Round(value, MidpointRounding.AwayFromZero)
/// Needed because CoreCLR doesn't support this particular overload of Math.Round
/// </summary>
[Obsolete("The method has been deprecated. Call MathUtils.Round(value, 0, MidpointRounding.AwayFromZero) instead.")]
public static double RoundAwayFromZero(double value) {
return RoundAwayFromZero(value, 0);
}
private static readonly double[] _RoundPowersOfTens = new double[] { 1E0, 1E1, 1E2, 1E3, 1E4, 1E5, 1E6, 1E7, 1E8, 1E9, 1E10, 1E11, 1E12, 1E13, 1E14, 1E15 };
private static double GetPowerOf10(int precision) {
return (precision < 16) ? _RoundPowersOfTens[precision] : Math.Pow(10, precision);
}
/// <summary>
/// Behaves like Math.Round(value, precision, MidpointRounding.AwayFromZero)
/// However, it works correctly on negative precisions and cases where precision is
/// outside of the [-15, 15] range.
///
/// (This function is also needed because CoreCLR lacks this overload.)
/// </summary>
[Obsolete("The method has been deprecated. Call MathUtils.Round(value, precision, MidpointRounding.AwayFromZero) instead.")]
public static double RoundAwayFromZero(double value, int precision) {
return Round(value, precision, MidpointRounding.AwayFromZero);
}
public static bool IsNegativeZero(double self) {
return (self == 0.0 && 1.0 / self < 0);
}
public static double Round(double value, int precision, MidpointRounding mode) {
if (double.IsInfinity(value) || double.IsNaN(value)) {
return value;
}
if (precision >= 0) {
if (precision > 308) {
return value;
}
double num = GetPowerOf10(precision);
return Math.Round(value * num, mode) / num;
}
if (precision >= -308) {
// Note: this code path could be merged with the precision >= 0 path,
// (by extending the cache to negative powers of 10)
// but the results seem to be more precise if we do it this way
double num = GetPowerOf10(-precision);
return Math.Round(value / num, mode) * num;
}
// Preserve the sign of the input, including +/-0.0
return value < 0.0 || 1.0 / value < 0.0 ? -0.0 : 0.0;
}
#region Special Functions
public static double Erf(double v0) {
// Calculate the error function using the approximation method outlined in
// W. J. Cody's "Rational Chebyshev Approximations for the Error Function"
if (v0 >= 10.0) {
return 1.0;
}
if (v0 <= -10.0) {
return -1.0;
}
if (v0 > 0.47 || v0 < -0.47) {
return 1.0 - ErfComplement(v0);
}
double sq = v0 * v0;
double numer = EvalPolynomial(sq, ErfNumerCoeffs);
double denom = EvalPolynomial(sq, ErfDenomCoeffs);
return v0 * numer / denom;
}
public static double ErfComplement(double v0) {
if (v0 >= 30.0) {
return 0.0;
}
if (v0 <= -10.0) {
return 2.0;
}
double a = Math.Abs(v0);
if (a < 0.47) {
return 1.0 - Erf(v0);
}
// Different approximations are required for different ranges of v0
double res;
if (a <= 4.0) {
// Use the approximation method outlined in W. J. Cody's "Rational Chebyshev
// Approximations for the Error Function"
double numer = EvalPolynomial(a, ErfcNumerCoeffs);
double denom = EvalPolynomial(a, ErfcDenomCoeffs);
res = Math.Exp(-a * a) * numer / denom;
} else {
// Use the approximation method introduced by C. Tellambura and A. Annamalai
// in "Efficient Computation of erfc(x) for Large Arguments"
const double h = 0.5;
const double hSquared = 0.25;
const int nTerms = 10;
double sq = a * a;
res = 0.0;
for (int i = nTerms; i > 0; i--) {
double term = i * i * hSquared;
res += Math.Exp(-term) / (term + sq);
}
res = h * a * Math.Exp(-sq) / Math.PI * (res * 2 + 1.0 / sq);
}
if (v0 < 0.0) {
res = 2.0 - res;
}
return res;
}
public static double Gamma(double v0) {
// Calculate the Gamma function using the Lanczos approximation
if (double.IsNegativeInfinity(v0)) {
return double.NaN;
}
double a = Math.Abs(v0);
// Special-case integers
if (a % 1.0 == 0.0) {
// Gamma is undefined on non-positive integers
if (v0 <= 0.0) {
return double.NaN;
}
// factorial(v0 - 1)
if (a <= 25.0) {
if (a <= 2.0) {
return 1.0;
}
a -= 1.0;
v0 -= 1.0;
while (--v0 > 1.0) {
a *= v0;
}
return a;
}
}
// lim(Gamma(v0)) = 1.0 / v0 as v0 approaches 0.0
if (a < 1e-50) {
return 1.0 / v0;
}
double res;
if (v0 < -150.0) {
// If Gamma(1 - v0) could overflow for large v0, use the duplication formula to
// compute Gamma(1 - v0):
// Gamma(x) * Gamma(x + 0,5) = sqrt(pi) * 2**(1 - 2x) * Gamma(2x)
// ==> Gamma(1 - x) = Gamma((1-x)/2) * Gamma((2-x)/2) / (2**x * sqrt(pi))
// Then apply the reflection formula:
// Gamma(x) = pi / sin(pi * x) / Gamma(1 - x)
double halfV0 = v0 / 2.0;
res = Math.Pow(Math.PI, 1.5) / SinPi(v0);
res *= Math.Pow(2.0, v0);
res /= PositiveGamma(0.5 - halfV0);
res /= PositiveGamma(1.0 - halfV0);
} else if (v0 < 0.001) {
// For values less than or close to zero, just use the reflection formula
res = Math.PI / SinPi(v0);
double v1 = 1.0 - v0;
if (v0 == 1.0 - v1) {
res /= PositiveGamma(v1);
} else {
// Computing v1 has resulted in a loss of precision. To avoid this, use the
// recurrence relation Gamma(x + 1) = x * Gamma(x).
res /= -v0 * PositiveGamma(-v0);
}
} else {
res = PositiveGamma(v0);
}
return res;
}
public static double LogGamma(double v0) {
// Calculate the log of the Gamma function using the Lanczos approximation
if (double.IsInfinity(v0)) {
return double.PositiveInfinity;
}
double a = Math.Abs(v0);
// Gamma is undefined on non-positive integers
if (v0 <= 0.0 && a % 1.0 == 0.0) {
return double.NaN;
}
// lim(LGamma(v0)) = -log|v0| as v0 approaches 0.0
if (a < 1e-50) {
return -Math.Log(a);
}
double res;
if (v0 < 0.0) {
// For negative values, use the reflection formula:
// Gamma(x) = pi / sin(pi * x) / Gamma(1 - x)
// ==> LGamma(x) = log(pi / |sin(pi * x)|) - LGamma(1 - x)
res = Math.Log(Math.PI / AbsSinPi(v0));
res -= PositiveLGamma(1.0 - v0);
} else {
res = PositiveLGamma(v0);
}
return res;
}
public static double Hypot(double x, double y) {
//
// sqrt(x*x + y*y) == sqrt(x*x * (1 + (y*y)/(x*x))) ==
// sqrt(x*x) * sqrt(1 + (y/x)*(y/x)) ==
// abs(x) * sqrt(1 + (y/x)*(y/x))
//
// Handle infinities
if (double.IsInfinity(x) || double.IsInfinity(y)) {
return double.PositiveInfinity;
}
// First, get abs
if (x < 0.0) x = -x;
if (y < 0.0) y = -y;
// Obvious cases
if (x == 0.0) return y;
if (y == 0.0) return x;
// Divide smaller number by bigger number to safeguard the (y/x)*(y/x)
if (x < y) {
double temp = y; y = x; x = temp;
}
y /= x;
// calculate abs(x) * sqrt(1 + (y/x)*(y/x))
return x * System.Math.Sqrt(1 + y * y);
}
/// <summary>
/// Evaluates a polynomial in v0 where the coefficients are ordered in increasing degree
/// </summary>
private static double EvalPolynomial(double v0, double[] coeffs) {
double res = 0.0;
for (int i = coeffs.Length - 1; i >= 0; i--) {
res = checked(res * v0 + coeffs[i]);
}
return res;
}
/// <summary>
/// Evaluates a polynomial in v0 where the coefficients are ordered in increasing degree
/// if reverse is false, and increasing degree if reverse is true.
/// </summary>
private static double EvalPolynomial(double v0, double[] coeffs, bool reverse) {
if (!reverse) {
return EvalPolynomial(v0, coeffs);
}
double res = 0.0;
for (int i = 0; i < coeffs.Length; i++) {
res = checked(res * v0 + coeffs[i]);
}
return res;
}
/// <summary>
/// A numerically precise version of sin(v0 * pi)
/// </summary>
private static double SinPi(double v0) {
double res = Math.Abs(v0) % 2.0;
if (res < 0.25) {
res = Math.Sin(res * Math.PI);
} else if (res < 0.75) {
res = Math.Cos((res - 0.5) * Math.PI);
} else if (res < 1.25) {
res = -Math.Sin((res - 1.0) * Math.PI);
} else if (res < 1.75) {
res = -Math.Cos((res - 1.5) * Math.PI);
} else {
res = Math.Sin((res - 2.0) * Math.PI);
}
return v0 < 0 ? -res : res;
}
/// <summary>
/// A numerically precise version of |sin(v0 * pi)|
/// </summary>
private static double AbsSinPi(double v0) {
double res = Math.Abs(v0) % 1.0;
if (res < 0.25) {
res = Math.Sin(res * Math.PI);
} else if (res < 0.75) {
res = Math.Cos((res - 0.5) * Math.PI);
} else {
res = Math.Sin((res - 1.0) * Math.PI);
}
return Math.Abs(res);
}
// polynomial coefficients ordered by increasing degree
private static readonly double[] ErfNumerCoeffs = {
2.4266795523053175e02, 2.1979261618294152e01,
6.9963834886191355, -3.5609843701815385e-02
};
private static readonly double[] ErfDenomCoeffs = {
2.1505887586986120e02, 9.1164905404514901e01,
1.5082797630407787e01, 1.0
};
private static readonly double[] ErfcNumerCoeffs = {
3.004592610201616005e02, 4.519189537118729422e02,
3.393208167343436870e02, 1.529892850469404039e02,
4.316222722205673530e01, 7.211758250883093659,
5.641955174789739711e-01, -1.368648573827167067e-07
};
private static readonly double[] ErfcDenomCoeffs = {
3.004592609569832933e02, 7.909509253278980272e02,
9.313540948506096211e02, 6.389802644656311665e02,
2.775854447439876434e02, 7.700015293522947295e01,
1.278272731962942351e01, 1.0
};
private static readonly double[] GammaNumerCoeffs = {
4.401213842800460895436e13, 4.159045335859320051581e13,
1.801384278711799677796e13, 4.728736263475388896889e12,
8.379100836284046470415e11, 1.055837072734299344907e11,
9.701363618494999493386e09, 6.549143975482052641016e08,
3.223832294213356530668e07, 1.128514219497091438040e06,
2.666579378459858944762e04, 3.818801248632926870394e02,
2.506628274631000502415
};
private static readonly double[] GammaDenomCoeffs = {
0.0, 39916800.0, 120543840.0, 150917976.0,
105258076.0, 45995730.0, 13339535.0, 2637558.0,
357423.0, 32670.0, 1925.0, 66.0, 1.0
};
/// <summary>
/// Take the quotient of the 2 polynomials forming the Lanczos approximation
/// with N=13 and G=13.144565
/// </summary>
private static double GammaRationalFunc(double v0) {
double numer = 0.0;
double denom = 0.0;
if (v0 < 1e15) {
numer = EvalPolynomial(v0, GammaNumerCoeffs);
denom = EvalPolynomial(v0, GammaDenomCoeffs);
} else {
double vRecip = 1.0 / v0;
numer = EvalPolynomial(vRecip, GammaNumerCoeffs, true);
denom = EvalPolynomial(vRecip, GammaDenomCoeffs, true);
}
return numer / denom;
}
/// <summary>
/// Computes the Gamma function on positive values, using the Lanczos approximation.
/// Lanczos parameters are N=13 and G=13.144565.
/// </summary>
private static double PositiveGamma(double v0) {
if (v0 > 200.0) {
return Double.PositiveInfinity;
}
double vg = v0 + 12.644565; // v0 + g - 0.5
double res = GammaRationalFunc(v0);
res /= Math.Exp(vg);
if (v0 < 120.0) {
res *= Math.Pow(vg, v0 - 0.5);
} else {
// Use a smaller exponent if we're in danger of overflowing Math.Pow
double sqrt = Math.Pow(vg, v0 / 2.0 - 0.25);
res *= sqrt;
res *= sqrt;
}
return res;
}
/// <summary>
/// Computes the Log-Gamma function on positive values, using the Lanczos approximation.
/// Lanczos parameters are N=13 and G=13.144565.
/// </summary>
private static double PositiveLGamma(double v0) {
const double g = 13.144565;
double vg = v0 + g - 0.5;
double res = Math.Log(GammaRationalFunc(v0)) - g;
res += (v0 - 0.5) * (Math.Log(vg) - 1);
return res;
}
#endregion
#region BigInteger
// generated by scripts/radix_generator.py
private static readonly uint[] maxCharsPerDigit = { 0, 0, 31, 20, 15, 13, 12, 11, 10, 10, 9, 9, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6 };
private static readonly uint[] groupRadixValues = { 0, 0, 2147483648, 3486784401, 1073741824, 1220703125, 2176782336, 1977326743, 1073741824, 3486784401, 1000000000, 2357947691, 429981696, 815730721, 1475789056, 2562890625, 268435456, 410338673, 612220032, 893871739, 1280000000, 1801088541, 2494357888, 3404825447, 191102976, 244140625, 308915776, 387420489, 481890304, 594823321, 729000000, 887503681, 1073741824, 1291467969, 1544804416, 1838265625, 2176782336 };
internal static string BigIntegerToString(uint[] d, int sign, int radix, bool lowerCase) {
if (radix < 2 || radix > 36) {
throw ExceptionUtils.MakeArgumentOutOfRangeException(nameof(radix), radix, "radix must be between 2 and 36");
}
int dl = d.Length;
if (dl == 0) {
return "0";
}
List<uint> digitGroups = new List<uint>();
uint groupRadix = groupRadixValues[radix];
while (dl > 0) {
uint rem = div(d, ref dl, groupRadix);
digitGroups.Add(rem);
}
StringBuilder ret = new StringBuilder();
if (sign == -1) {
ret.Append("-");
}
int digitIndex = digitGroups.Count - 1;
char[] tmpDigits = new char[maxCharsPerDigit[radix]];
AppendRadix((uint)digitGroups[digitIndex--], (uint)radix, tmpDigits, ret, false, lowerCase);
while (digitIndex >= 0) {
AppendRadix((uint)digitGroups[digitIndex--], (uint)radix, tmpDigits, ret, true, lowerCase);
}
return ret.Length == 0 ? "0" : ret.ToString();
}
private const int BitsPerDigit = 32;
private static uint div(uint[] n, ref int nl, uint d) {
ulong rem = 0;
int i = nl;
bool seenNonZero = false;
while (--i >= 0) {
rem <<= BitsPerDigit;
rem |= n[i];
uint v = (uint)(rem / d);
n[i] = v;
if (v == 0) {
if (!seenNonZero) nl--;
} else {
seenNonZero = true;
}
rem %= d;
}
return (uint)rem;
}
private static void AppendRadix(uint rem, uint radix, char[] tmp, StringBuilder buf, bool leadingZeros, bool lowerCase) {
string symbols = lowerCase ? "0123456789abcdefghijklmnopqrstuvwxyz" : "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int digits = tmp.Length;
int i = digits;
while (i > 0 && (leadingZeros || rem != 0)) {
uint digit = rem % radix;
rem /= radix;
tmp[--i] = symbols[(int)digit];
}
if (leadingZeros) buf.Append(tmp);
else buf.Append(tmp, i, digits - i);
}
// Helper for GetRandBits
private static uint GetWord(byte[] bytes, int start, int end) {
uint four = 0;
int bits = end - start;
int shift = 0;
if (bits > 32) {
bits = 32;
}
start /= 8;
while (bits > 0) {
uint value = bytes[start];
if (bits < 8) {
value &= (1u << bits) - 1u;
}
value <<= shift;
four |= value;
bits -= 8;
shift += 8;
start++;
}
return four;
}
public static BigInteger GetRandBits(Action<byte[]> NextBytes, int bits) {
ContractUtils.Requires(bits > 0, nameof(bits));
// equivalent to (bits + 7) / 8 without possibility of overflow
int count = bits % 8 == 0 ? bits / 8 : bits / 8 + 1;
// Pad the end (most significant) with zeros if we align to the byte
// to ensure that we end up with a positive value
byte[] bytes = new byte[bits % 8 == 0 ? count + 1 : count];
NextBytes(bytes);
if (bits % 8 == 0) {
bytes[bytes.Length - 1] = 0;
} else {
bytes[bytes.Length - 1] = (byte)(bytes[bytes.Length - 1] & ((1 << (bits % 8)) - 1));
}
if (bits <= 32) {
return GetWord(bytes, 0, bits);
}
if (bits <= 64) {
ulong a = GetWord(bytes, 0, bits);
ulong b = GetWord(bytes, 32, bits);
return (a | (b << 32));
}
return new BigInteger(bytes);
}
public static BigInteger GetRandBits(this Random generator, int bits) => GetRandBits(generator.NextBytes, bits);
public static BigInteger Random(this Random generator, BigInteger limit) {
ContractUtils.Requires(limit.Sign > 0, nameof(limit));
ContractUtils.RequiresNotNull(generator, nameof(generator));
BigInteger res = BigInteger.Zero;
while (true) {
// if we've run out of significant digits, we can return the total
if (limit == BigInteger.Zero) {
return res;
}
// if we're small enough to fit in an int, do so
if (limit.AsInt32(out int iLimit)) {
return res + generator.Next(iLimit);
}
// get the 3 or 4 uppermost bytes that fit into an int
int hiData;
byte[] data = limit.ToByteArray();
int index = data.Length;
while (data[--index] == 0) ;
if (data[index] < 0x80) {
hiData = data[index] << 24;
data[index--] = (byte)0;
} else {
hiData = 0;
}
hiData |= data[index] << 16;
data[index--] = (byte)0;
hiData |= data[index] << 8;
data[index--] = (byte)0;
hiData |= data[index];
data[index--] = (byte)0;
// get a uniform random number for the uppermost portion of the bigint
byte[] randomData = new byte[index + 2];
generator.NextBytes(randomData);
randomData[index + 1] = (byte)0;
res += new BigInteger(randomData);
res += (BigInteger)generator.Next(hiData) << ((index + 1) * 8);
// sum it with a uniform random number for the remainder of the bigint
limit = new BigInteger(data);
}
}
public static bool TryToFloat64(this BigInteger self, out double result) {
result = (double)self;
if (double.IsInfinity(result)) {
result = default;
return false;
}
return true;
}
public static double ToFloat64(this BigInteger self) {
if (TryToFloat64(self, out double res)) {
return res;
}
throw new OverflowException("Value was either too large or too small for a Double.");
}
public static int BitLength(BigInteger x) {
if (x.IsZero) {
return 0;
}
byte[] bytes = BigInteger.Abs(x).ToByteArray();
int index = bytes.Length;
while (bytes[--index] == 0) ;
return index * 8 + BitLength((int)bytes[index]);
}
// Like GetBitCount(Abs(x)), except 0 maps to 0
public static int BitLength(long x) {
if (x == 0) {
return 0;
}
if (x == Int64.MinValue) {
return 64;
}
x = Math.Abs(x);
int res = 1;
if (x >= 1L << 32) {
x >>= 32;
res += 32;
}
if (x >= 1L << 16) {
x >>= 16;
res += 16;
}
if (x >= 1L << 8) {
x >>= 8;
res += 8;
}
if (x >= 1L << 4) {
x >>= 4;
res += 4;
}
if (x >= 1L << 2) {
x >>= 2;
res += 2;
}
if (x >= 1L << 1) {
res += 1;
}
return res;
}
// Like GetBitCount(Abs(x)), except 0 maps to 0
[CLSCompliant(false)]
public static int BitLengthUnsigned(ulong x) {
if (x >= 1uL << 63) {
return 64;
}
return BitLength((long)x);
}
// Like GetBitCount(Abs(x)), except 0 maps to 0
public static int BitLength(int x) {
if (x == 0) {
return 0;
}
if (x == Int32.MinValue) {
return 32;
}
x = Math.Abs(x);
int res = 1;
if (x >= 1 << 16) {
x >>= 16;
res += 16;
}
if (x >= 1 << 8) {
x >>= 8;
res += 8;
}
if (x >= 1 << 4) {
x >>= 4;
res += 4;
}
if (x >= 1 << 2) {
x >>= 2;
res += 2;
}
if (x >= 1 << 1) {
res += 1;
}
return res;
}
// Like GetBitCount(Abs(x)), except 0 maps to 0
[CLSCompliant(false)]
public static int BitLengthUnsigned(uint x) {
if (x >= 1u << 31) {
return 32;
}
return BitLength((int)x);
}
#region Extending BigInt with BigInteger API
public static bool AsInt32(this BigInteger self, out int ret) {
if (self >= Int32.MinValue && self <= Int32.MaxValue) {
ret = (Int32)self;
return true;
}
ret = 0;
return false;
}
public static bool AsInt64(this BigInteger self, out long ret) {
if (self >= Int64.MinValue && self <= Int64.MaxValue) {
ret = (long)self;
return true;
}
ret = 0;
return false;
}
[CLSCompliant(false)]
public static bool AsUInt32(this BigInteger self, out uint ret) {
if (self >= UInt32.MinValue && self <= UInt32.MaxValue) {
ret = (UInt32)self;
return true;
}
ret = 0;
return false;
}
[CLSCompliant(false)]
public static bool AsUInt64(this BigInteger self, out ulong ret) {
if (self >= UInt64.MinValue && self <= UInt64.MaxValue) {
ret = (UInt64)self;
return true;
}
ret = 0;
return false;
}
public static BigInteger Abs(this BigInteger self) {
return BigInteger.Abs(self);
}
public static bool IsZero(this BigInteger self) {
return self.IsZero;
}
public static bool IsPositive(this BigInteger self) {
return self.Sign > 0;
}
public static bool IsNegative(this BigInteger self) {
return self.Sign < 0;
}
public static double Log(this BigInteger self) {
return BigInteger.Log(self);
}
public static double Log(this BigInteger self, double baseValue) {
return BigInteger.Log(self, baseValue);
}
public static double Log10(this BigInteger self) {
return BigInteger.Log10(self);
}
public static BigInteger Power(this BigInteger self, int exp) {
return BigInteger.Pow(self, exp);
}
public static BigInteger Power(this BigInteger self, long exp) {
if (exp < 0) {
throw ExceptionUtils.MakeArgumentOutOfRangeException(nameof(exp), exp, "Must be at least 0");
}
// redirection possible?
if (exp <= int.MaxValue) {
return BigInteger.Pow(self, (int)exp);
}
// manual implementation
if (self.IsOne) {
return BigInteger.One;
}
if (self.IsZero) {
return BigInteger.Zero;
}
if (self == BigInteger.MinusOne) {
if (exp % 2 == 0) {
return BigInteger.One;
}
return BigInteger.MinusOne;
}
BigInteger result = BigInteger.One;
while (exp != 0) {
if (exp % 2 != 0) {
result *= self;
}
exp >>= 1;
self *= self;
}
return result;
}
public static BigInteger ModPow(this BigInteger self, int power, BigInteger mod) {
return BigInteger.ModPow(self, power, mod);
}
public static BigInteger ModPow(this BigInteger self, BigInteger power, BigInteger mod) {
return BigInteger.ModPow(self, power, mod);
}
public static string ToString(this BigInteger self, int radix) {
const string symbols = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (radix < 2 || radix > 36) {
throw ExceptionUtils.MakeArgumentOutOfRangeException(nameof(radix), radix, "radix must be between 2 and 36");
}
bool isNegative = false;
if (self < BigInteger.Zero) {
self = -self;
isNegative = true;
} else if (self == BigInteger.Zero) {
return "0";
}
List<char> digits = new List<char>();
while (self > 0) {
digits.Add(symbols[(int)(self % radix)]);
self /= radix;
}
StringBuilder ret = new StringBuilder();
if (isNegative) {
ret.Append('-');
}
for (int digitIndex = digits.Count - 1; digitIndex >= 0; digitIndex--) {
ret.Append(digits[digitIndex]);
}
return ret.ToString();
}
#endregion
#region Exposing underlying data
[CLSCompliant(false)]
public static uint[] GetWords(this BigInteger self) {
if (self.IsZero) {
return new uint[] { 0 };
}
GetHighestByte(self, out int hi, out byte[] bytes);
uint[] result = new uint[(hi + 1 + 3) / 4];
int i = 0;
int j = 0;
uint u = 0;
int shift = 0;
while (i < bytes.Length) {
u |= (uint)bytes[i++] << shift;
if (i % 4 == 0) {
result[j++] = u;
u = 0;
}
shift += 8;
}
if (u != 0) {
result[j] = u;
}
return result;
}
[CLSCompliant(false)]
public static uint GetWord(this BigInteger self, int index) {
return GetWords(self)[index];
}
public static int GetWordCount(this BigInteger self) {
GetHighestByte(self, out int index, out byte[] _);
return index / 4 + 1; // return (index + 1 + 3) / 4;
}
public static int GetByteCount(this BigInteger self) {
GetHighestByte(self, out int index, out byte[] _);
return index + 1;
}
public static int GetBitCount(this BigInteger self) {
if (self.IsZero) {
return 1;
}
byte[] bytes = BigInteger.Abs(self).ToByteArray();
int index = bytes.Length;
while (bytes[--index] == 0) ;
int count = index * 8;
for (int hiByte = bytes[index]; hiByte > 0; hiByte >>= 1) {
count++;
}
return count;
}
private static byte GetHighestByte(BigInteger self, out int index, out byte[] byteArray) {
byte[] bytes = BigInteger.Abs(self).ToByteArray();
if (self.IsZero) {
byteArray = bytes;
index = 0;
return 1;
}
int hi = bytes.Length;
byte b;
do {
b = bytes[--hi];
} while (b == 0);
index = hi;
byteArray = bytes;
return b;
}
#endregion
#endregion
#region Complex
public static Complex MakeReal(double real) {
return new Complex(real, 0.0);
}
public static Complex MakeImaginary(double imag) {
return new Complex(0.0, imag);
}
public static Complex MakeComplex(double real, double imag) {
return new Complex(real, imag);
}
public static double Imaginary(this Complex self) {
return self.Imaginary;
}
public static bool IsZero(this Complex self) {
return self.Equals(Complex.Zero);
}
public static Complex Conjugate(this Complex self) {
return new Complex(self.Real, -self.Imaginary);
}
public static double Abs(this Complex self) {
return Complex.Abs(self);
}
public static Complex Pow(this Complex self, Complex power) {
return Complex.Pow(self, power);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ModestTree;
namespace Zenject
{
public class InjectContext
{
public InjectContext()
{
SourceType = InjectSources.Any;
MemberName = "";
}
public InjectContext(DiContainer container, Type memberType)
: this()
{
Container = container;
MemberType = memberType;
}
public InjectContext(DiContainer container, Type memberType, object identifier)
: this(container, memberType)
{
Identifier = identifier;
}
public InjectContext(DiContainer container, Type memberType, object identifier, bool optional)
: this(container, memberType, identifier)
{
Optional = optional;
}
// The type of the object which is having its members injected
// NOTE: This is null for root calls to Resolve<> or Instantiate<>
public Type ObjectType
{
get;
set;
}
// Parent context that triggered the creation of ObjectType
// This can be used for very complex conditions using parent info such as identifiers, types, etc.
// Note that ParentContext.MemberType is not necessarily the same as ObjectType,
// since the ObjectType could be a derived type from ParentContext.MemberType
public InjectContext ParentContext
{
get;
set;
}
// The instance which is having its members injected
// Note that this is null when injecting into the constructor
public object ObjectInstance
{
get;
set;
}
// Identifier - most of the time this is null
// It will match 'foo' in this example:
// ... In an installer somewhere:
// Container.Bind<Foo>("foo").ToSingle();
// ...
// ... In a constructor:
// public Foo([Inject(Id = "foo") Foo foo)
public object Identifier
{
get;
set;
}
// ConcreteIdentifier - most of the time this is null
// It will match 'foo' in this example:
// ... In an installer somewhere:
// Container.Bind<Foo>().ToSingle("foo");
// Container.Bind<ITickable>().ToSingle<Foo>("foo");
// ...
// This allows you to create When() conditionals like this:
// ...
// Container.BindInstance("some text").When(c => c.ConcreteIdentifier == "foo");
public string ConcreteIdentifier
{
get;
set;
}
// The constructor parameter name, or field name, or property name
public string MemberName
{
get;
set;
}
// The type of the constructor parameter, field or property
public Type MemberType
{
get;
set;
}
// When optional, null is a valid value to be returned
public bool Optional
{
get;
set;
}
// When set to true, this will only look up dependencies in the local container and will not
// search in parent containers
public InjectSources SourceType
{
get;
set;
}
// When optional, this is used to provide the value
public object FallBackValue
{
get;
set;
}
// The container used for this injection
public DiContainer Container
{
get;
set;
}
public IEnumerable<InjectContext> ParentContexts
{
get
{
if (ParentContext == null)
{
yield break;
}
yield return ParentContext;
foreach (var context in ParentContext.ParentContexts)
{
yield return context;
}
}
}
public IEnumerable<InjectContext> ParentContextsAndSelf
{
get
{
yield return this;
foreach (var context in ParentContexts)
{
yield return context;
}
}
}
// This will return the types of all the objects that are being injected
// So if you have class Foo which has constructor parameter of type IBar,
// and IBar resolves to Bar, this will be equal to (Bar, Foo)
public IEnumerable<Type> AllObjectTypes
{
get
{
foreach (var context in ParentContextsAndSelf)
{
if (context.ObjectType != null)
{
yield return context.ObjectType;
}
}
}
}
public BindingId GetBindingId()
{
return new BindingId(MemberType, Identifier);
}
public InjectContext CreateSubContext(Type memberType)
{
return CreateSubContext(memberType, null);
}
public InjectContext CreateSubContext(Type memberType, object identifier)
{
var subContext = new InjectContext();
subContext.ParentContext = this;
subContext.Identifier = identifier;
subContext.MemberType = memberType;
// Clear these
subContext.ConcreteIdentifier = null;
subContext.MemberName = "";
subContext.FallBackValue = null;
// Inherit these ones by default
subContext.ObjectType = this.ObjectType;
subContext.ObjectInstance = this.ObjectInstance;
subContext.Optional = this.Optional;
subContext.SourceType = this.SourceType;
subContext.Container = this.Container;
return subContext;
}
public InjectContext Clone()
{
var clone = new InjectContext();
clone.ObjectType = this.ObjectType;
clone.ParentContext = this.ParentContext;
clone.ObjectInstance = this.ObjectInstance;
clone.Identifier = this.Identifier;
clone.ConcreteIdentifier = this.ConcreteIdentifier;
clone.MemberType = this.MemberType;
clone.MemberName = this.MemberName;
clone.Optional = this.Optional;
clone.SourceType = this.SourceType;
clone.FallBackValue = this.FallBackValue;
clone.Container = this.Container;
return clone;
}
// This is very useful to print out for debugging purposes
public string GetObjectGraphString()
{
var result = new StringBuilder();
foreach (var context in ParentContextsAndSelf.Reverse())
{
if (context.ObjectType == null)
{
continue;
}
result.AppendLine(context.ObjectType.Name());
}
return result.ToString();
}
}
}
| |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2.1
* Contact: devcenter@docusign.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter;
namespace DocuSign.eSign.Model
{
/// <summary>
/// AccountSignatureProvider
/// </summary>
[DataContract]
public partial class AccountSignatureProvider : IEquatable<AccountSignatureProvider>, IValidatableObject
{
public AccountSignatureProvider()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="AccountSignatureProvider" /> class.
/// </summary>
/// <param name="IsRequired">IsRequired.</param>
/// <param name="Priority">Priority.</param>
/// <param name="SignatureProviderDisplayName">SignatureProviderDisplayName.</param>
/// <param name="SignatureProviderId">SignatureProviderId.</param>
/// <param name="SignatureProviderName">SignatureProviderName.</param>
/// <param name="SignatureProviderOptionsMetadata">SignatureProviderOptionsMetadata.</param>
/// <param name="SignatureProviderRequiredOptions">SignatureProviderRequiredOptions.</param>
public AccountSignatureProvider(string IsRequired = default(string), string Priority = default(string), string SignatureProviderDisplayName = default(string), string SignatureProviderId = default(string), string SignatureProviderName = default(string), List<AccountSignatureProviderOption> SignatureProviderOptionsMetadata = default(List<AccountSignatureProviderOption>), List<SignatureProviderRequiredOption> SignatureProviderRequiredOptions = default(List<SignatureProviderRequiredOption>))
{
this.IsRequired = IsRequired;
this.Priority = Priority;
this.SignatureProviderDisplayName = SignatureProviderDisplayName;
this.SignatureProviderId = SignatureProviderId;
this.SignatureProviderName = SignatureProviderName;
this.SignatureProviderOptionsMetadata = SignatureProviderOptionsMetadata;
this.SignatureProviderRequiredOptions = SignatureProviderRequiredOptions;
}
/// <summary>
/// Gets or Sets IsRequired
/// </summary>
[DataMember(Name="isRequired", EmitDefaultValue=false)]
public string IsRequired { get; set; }
/// <summary>
/// Gets or Sets Priority
/// </summary>
[DataMember(Name="priority", EmitDefaultValue=false)]
public string Priority { get; set; }
/// <summary>
/// Gets or Sets SignatureProviderDisplayName
/// </summary>
[DataMember(Name="signatureProviderDisplayName", EmitDefaultValue=false)]
public string SignatureProviderDisplayName { get; set; }
/// <summary>
/// Gets or Sets SignatureProviderId
/// </summary>
[DataMember(Name="signatureProviderId", EmitDefaultValue=false)]
public string SignatureProviderId { get; set; }
/// <summary>
/// Gets or Sets SignatureProviderName
/// </summary>
[DataMember(Name="signatureProviderName", EmitDefaultValue=false)]
public string SignatureProviderName { get; set; }
/// <summary>
/// Gets or Sets SignatureProviderOptionsMetadata
/// </summary>
[DataMember(Name="signatureProviderOptionsMetadata", EmitDefaultValue=false)]
public List<AccountSignatureProviderOption> SignatureProviderOptionsMetadata { get; set; }
/// <summary>
/// Gets or Sets SignatureProviderRequiredOptions
/// </summary>
[DataMember(Name="signatureProviderRequiredOptions", EmitDefaultValue=false)]
public List<SignatureProviderRequiredOption> SignatureProviderRequiredOptions { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class AccountSignatureProvider {\n");
sb.Append(" IsRequired: ").Append(IsRequired).Append("\n");
sb.Append(" Priority: ").Append(Priority).Append("\n");
sb.Append(" SignatureProviderDisplayName: ").Append(SignatureProviderDisplayName).Append("\n");
sb.Append(" SignatureProviderId: ").Append(SignatureProviderId).Append("\n");
sb.Append(" SignatureProviderName: ").Append(SignatureProviderName).Append("\n");
sb.Append(" SignatureProviderOptionsMetadata: ").Append(SignatureProviderOptionsMetadata).Append("\n");
sb.Append(" SignatureProviderRequiredOptions: ").Append(SignatureProviderRequiredOptions).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as AccountSignatureProvider);
}
/// <summary>
/// Returns true if AccountSignatureProvider instances are equal
/// </summary>
/// <param name="other">Instance of AccountSignatureProvider to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(AccountSignatureProvider other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.IsRequired == other.IsRequired ||
this.IsRequired != null &&
this.IsRequired.Equals(other.IsRequired)
) &&
(
this.Priority == other.Priority ||
this.Priority != null &&
this.Priority.Equals(other.Priority)
) &&
(
this.SignatureProviderDisplayName == other.SignatureProviderDisplayName ||
this.SignatureProviderDisplayName != null &&
this.SignatureProviderDisplayName.Equals(other.SignatureProviderDisplayName)
) &&
(
this.SignatureProviderId == other.SignatureProviderId ||
this.SignatureProviderId != null &&
this.SignatureProviderId.Equals(other.SignatureProviderId)
) &&
(
this.SignatureProviderName == other.SignatureProviderName ||
this.SignatureProviderName != null &&
this.SignatureProviderName.Equals(other.SignatureProviderName)
) &&
(
this.SignatureProviderOptionsMetadata == other.SignatureProviderOptionsMetadata ||
this.SignatureProviderOptionsMetadata != null &&
this.SignatureProviderOptionsMetadata.SequenceEqual(other.SignatureProviderOptionsMetadata)
) &&
(
this.SignatureProviderRequiredOptions == other.SignatureProviderRequiredOptions ||
this.SignatureProviderRequiredOptions != null &&
this.SignatureProviderRequiredOptions.SequenceEqual(other.SignatureProviderRequiredOptions)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.IsRequired != null)
hash = hash * 59 + this.IsRequired.GetHashCode();
if (this.Priority != null)
hash = hash * 59 + this.Priority.GetHashCode();
if (this.SignatureProviderDisplayName != null)
hash = hash * 59 + this.SignatureProviderDisplayName.GetHashCode();
if (this.SignatureProviderId != null)
hash = hash * 59 + this.SignatureProviderId.GetHashCode();
if (this.SignatureProviderName != null)
hash = hash * 59 + this.SignatureProviderName.GetHashCode();
if (this.SignatureProviderOptionsMetadata != null)
hash = hash * 59 + this.SignatureProviderOptionsMetadata.GetHashCode();
if (this.SignatureProviderRequiredOptions != null)
hash = hash * 59 + this.SignatureProviderRequiredOptions.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Net;
using log4net;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenSim.Data;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Communications.Services;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Framework.Communications.Capabilities;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
namespace OpenSim.Grid.UserServer.Modules
{
public delegate void UserLoggedInAtLocation(UUID agentID, UUID sessionID, UUID RegionID,
ulong regionhandle, float positionX, float positionY, float positionZ,
string firstname, string lastname);
public class RegionLoginFailure
{
private const int FAIL_LIMIT = 10;
private const int FAIL_EXPIRY = 5 * 60; // in seconds (5 minutes)
private uint _lastFail;
private int _failures;
public int Count
{
get { return _failures; }
}
// Allocating one of these implies the first failure.
public RegionLoginFailure()
{
_lastFail = 0;
_failures = 0;
AddFailure();
}
// Increment the failure count and update the timestamp.
public void AddFailure()
{
_failures++;
_lastFail = (uint)Environment.TickCount;
}
// Returns true if fail count exceeds threshold
public bool IsFailed()
{
return (_failures >= FAIL_LIMIT);
}
// Returns true if more than N minutes has passed since the last failure.
public bool IsExpired()
{
return (((uint)Environment.TickCount - _lastFail) > (FAIL_EXPIRY*1000));
}
// Returns true if the count is exceeded and not expired.
public bool IsActive()
{
return IsFailed() && !IsExpired();
}
}
/// <summary>
/// Login service used in grid mode.
/// </summary>
public class UserLoginService : LoginService
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public event UserLoggedInAtLocation OnUserLoggedInAtLocation;
private UserLoggedInAtLocation handlerUserLoggedInAtLocation;
public UserConfig m_config;
private readonly IRegionProfileRouter m_regionProfileService;
protected BaseHttpServer m_httpServer;
private Dictionary<string, RegionLoginFailure> _LastRegionFailure = new Dictionary<string, RegionLoginFailure>();
public UserLoginService(
OpenSim.Framework.Communications.UserProfileManager userManager,
LibraryRootFolder libraryRootFolder, string mapServerURI, string profileServerURI,
UserConfig config, string welcomeMess, IRegionProfileRouter regionProfileService)
: base(userManager, libraryRootFolder, welcomeMess, mapServerURI, profileServerURI)
{
m_config = config;
m_defaultHomeX = m_config.DefaultX;
m_defaultHomeY = m_config.DefaultY;
m_regionProfileService = regionProfileService;
}
public void RegisterHandlers(BaseHttpServer httpServer, bool registerOpenIDHandlers)
{
m_httpServer = httpServer;
m_httpServer.AddHTTPHandler("login", ProcessHTMLLogin);
m_httpServer.AddXmlRPCHandler("login_to_simulator", XmlRpcLoginMethod);
m_httpServer.AddXmlRPCHandler("set_login_params", XmlRPCSetLoginParams);
m_httpServer.AddXmlRPCHandler("check_auth_session", XmlRPCCheckAuthSession, false);
// New Style
m_httpServer.AddStreamHandler(new XmlRpcStreamHandler("POST", Util.XmlRpcRequestPrefix("login_to_simulator"), XmlRpcLoginMethod));
m_httpServer.AddStreamHandler(new XmlRpcStreamHandler("POST", Util.XmlRpcRequestPrefix("set_login_params"), XmlRPCSetLoginParams));
m_httpServer.AddStreamHandler(new XmlRpcStreamHandler("POST", Util.XmlRpcRequestPrefix("check_auth_session"), XmlRPCCheckAuthSession));
if (registerOpenIDHandlers)
{
// Handler for OpenID avatar identity pages
m_httpServer.AddStreamHandler(new OpenIdStreamHandler("GET", "/users/", this));
// Handlers for the OpenID endpoint server
m_httpServer.AddStreamHandler(new OpenIdStreamHandler("POST", "/openid/server/", this));
m_httpServer.AddStreamHandler(new OpenIdStreamHandler("GET", "/openid/server/", this));
}
}
public void setloginlevel(int level)
{
m_minLoginLevel = level;
m_log.InfoFormat("[GRID]: Login Level set to {0} ", level);
}
public void setwelcometext(string text)
{
m_welcomeMessage = text;
m_log.InfoFormat("[GRID]: Login text set to {0} ", text);
}
public override void LogOffUser(UserProfileData theUser, string message)
{
RegionProfileData SimInfo;
try
{
SimInfo = m_regionProfileService.RequestSimProfileData(
theUser.CurrentAgent.Handle, m_config.GridServerURL,
m_config.GridSendKey, m_config.GridRecvKey);
if (SimInfo == null)
{
m_log.Error("[GRID]: Region user was in isn't currently logged in");
return;
}
}
catch (Exception)
{
m_log.Error("[GRID]: Unable to look up region to log user off");
return;
}
// Prepare notification
Hashtable SimParams = new Hashtable();
SimParams["agent_id"] = theUser.ID.ToString();
SimParams["region_secret"] = theUser.CurrentAgent.SecureSessionID.ToString();
SimParams["region_secret2"] = SimInfo.regionSecret;
//m_log.Info(SimInfo.regionSecret);
SimParams["regionhandle"] = theUser.CurrentAgent.Handle.ToString();
SimParams["message"] = message;
ArrayList SendParams = new ArrayList();
SendParams.Add(SimParams);
m_log.InfoFormat(
"[ASSUMED CRASH]: Telling region {0} @ {1},{2} ({3}) that their agent is dead: {4}",
SimInfo.regionName, SimInfo.regionLocX, SimInfo.regionLocY, SimInfo.httpServerURI,
theUser.FirstName + " " + theUser.SurName);
try
{
string methodName = "logoff_user";
XmlRpcRequest GridReq = new XmlRpcRequest(methodName, SendParams);
XmlRpcResponse GridResp = GridReq.Send(Util.XmlRpcRequestURI(SimInfo.httpServerURI, methodName), 6000);
if (GridResp.IsFault)
{
m_log.ErrorFormat(
"[LOGIN]: XMLRPC request for {0} failed, fault code: {1}, reason: {2}, This is likely an old region revision.",
SimInfo.httpServerURI, GridResp.FaultCode, GridResp.FaultString);
}
}
catch (Exception)
{
m_log.Error("[LOGIN]: Error telling region to logout user!");
}
// Prepare notification
SimParams = new Hashtable();
SimParams["agent_id"] = theUser.ID.ToString();
SimParams["region_secret"] = SimInfo.regionSecret;
//m_log.Info(SimInfo.regionSecret);
SimParams["regionhandle"] = theUser.CurrentAgent.Handle.ToString();
SimParams["message"] = message;
SendParams = new ArrayList();
SendParams.Add(SimParams);
m_log.InfoFormat(
"[ASSUMED CRASH]: Telling region {0} @ {1},{2} ({3}) that their agent is dead: {4}",
SimInfo.regionName, SimInfo.regionLocX, SimInfo.regionLocY, SimInfo.httpServerURI,
theUser.FirstName + " " + theUser.SurName);
try
{
string methodName = "logoff_user";
XmlRpcRequest GridReq = new XmlRpcRequest(methodName, SendParams);
XmlRpcResponse GridResp = GridReq.Send(Util.XmlRpcRequestURI(SimInfo.httpServerURI, methodName), 6000);
if (GridResp.IsFault)
{
m_log.ErrorFormat(
"[LOGIN]: XMLRPC request for {0} failed, fault code: {1}, reason: {2}, This is likely an old region revision.",
SimInfo.httpServerURI, GridResp.FaultCode, GridResp.FaultString);
}
}
catch (Exception)
{
m_log.Error("[LOGIN]: Error telling region to logout user!");
}
//base.LogOffUser(theUser);
}
protected override RegionInfo RequestClosestRegion(string region)
{
RegionProfileData profileData = m_regionProfileService.RequestSimProfileData(region,
m_config.GridServerURL, m_config.GridSendKey, m_config.GridRecvKey);
if (profileData != null)
{
return profileData.ToRegionInfo();
}
else
{
return null;
}
}
protected override RegionInfo GetRegionInfo(ulong homeRegionHandle)
{
RegionProfileData profileData = m_regionProfileService.RequestSimProfileData(homeRegionHandle,
m_config.GridServerURL, m_config.GridSendKey,
m_config.GridRecvKey);
if (profileData != null)
{
return profileData.ToRegionInfo();
}
else
{
return null;
}
}
protected override RegionInfo GetRegionInfo(UUID homeRegionId)
{
RegionProfileData profileData = m_regionProfileService.RequestSimProfileData(homeRegionId,
m_config.GridServerURL, m_config.GridSendKey,
m_config.GridRecvKey);
if (profileData != null)
{
return profileData.ToRegionInfo();
}
else
{
return null;
}
}
protected override bool PrepareLoginToRegion(RegionInfo regionInfo, UserProfileData user, LoginResponse response, string clientVersion)
{
return PrepareLoginToRegion(RegionProfileData.FromRegionInfo(regionInfo), user, response, clientVersion);
}
/// <summary>
/// Prepare a login to the given region. This involves both telling the region to expect a connection
/// and appropriately customising the response to the user.
/// </summary>
/// <param name="regionInfo"></param>
/// <param name="user"></param>
/// <param name="response"></param>
/// <returns>true if the region was successfully contacted, false otherwise</returns>
private bool PrepareLoginToRegion(RegionProfileData regionInfo, UserProfileData user, LoginResponse response, string clientVersion)
{
string regionName = regionInfo.regionName;
bool regionSuccess = false; // region communication result
bool userSuccess = true; // user login succeeded result, for now
try
{
lock (_LastRegionFailure)
{
if (_LastRegionFailure.ContainsKey(regionName))
{
// region failed previously
RegionLoginFailure failure = _LastRegionFailure[regionName];
if (failure.IsExpired())
{
// failure has expired, retry this region again
_LastRegionFailure.Remove(regionName);
// m_log.WarnFormat("[LOGIN]: Region '{0}' was previously down, retrying.", regionName);
}
else
{
if (failure.IsFailed())
{
// m_log.WarnFormat("[LOGIN]: Region '{0}' was recently down, skipping.", regionName);
return false; // within 5 minutes, don't repeat attempt
}
// m_log.WarnFormat("[LOGIN]: Region '{0}' was recently down but under threshold, retrying.", regionName);
}
}
}
response.SimAddress = regionInfo.OutsideIpOrResolvedHostname;
response.SimPort = regionInfo.serverPort;
response.RegionX = regionInfo.regionLocX;
response.RegionY = regionInfo.regionLocY;
string capsPath = CapsUtil.GetRandomCapsObjectPath();
response.SeedCapability = CapsUtil.GetFullCapsSeedURL(regionInfo.httpServerURI, capsPath);
// Notify the target of an incoming user
m_log.InfoFormat(
"[LOGIN]: Telling {0} @ {1},{2} ({3}) to prepare for client connection",
regionInfo.regionName, response.RegionX, response.RegionY, response.SeedCapability);
// Update agent with target sim
user.CurrentAgent.Region = regionInfo.UUID;
user.CurrentAgent.Handle = regionInfo.regionHandle;
// Prepare notification
Hashtable loginParams = new Hashtable();
loginParams["session_id"] = user.CurrentAgent.SessionID.ToString();
loginParams["secure_session_id"] = user.CurrentAgent.SecureSessionID.ToString();
loginParams["firstname"] = user.FirstName;
loginParams["lastname"] = user.SurName;
loginParams["agent_id"] = user.ID.ToString();
loginParams["circuit_code"] = (Int32)Convert.ToUInt32(response.CircuitCode);
loginParams["startpos_x"] = user.CurrentAgent.Position.X.ToString();
loginParams["startpos_y"] = user.CurrentAgent.Position.Y.ToString();
loginParams["startpos_z"] = user.CurrentAgent.Position.Z.ToString();
loginParams["regionhandle"] = user.CurrentAgent.Handle.ToString();
loginParams["caps_path"] = capsPath;
loginParams["client_version"] = clientVersion;
// Get appearance
AvatarAppearance appearance = m_userManager.GetUserAppearance(user.ID);
if (appearance != null)
{
loginParams["appearance"] = appearance.ToHashTable();
m_log.DebugFormat("[LOGIN]: Found appearance version {0} for {1} {2}", appearance.Serial, user.FirstName, user.SurName);
}
else
{
m_log.DebugFormat("[LOGIN]: Appearance not for {0} {1}. Creating default.", user.FirstName, user.SurName);
appearance = new AvatarAppearance(user.ID);
}
// Tell the client the COF version so it can use cached appearance if it matches.
response.CofVersion = appearance.Serial.ToString();
loginParams["cof_version"] = response.CofVersion;
ArrayList SendParams = new ArrayList();
SendParams.Add(loginParams);
SendParams.Add(m_config.GridSendKey);
// Send
const string METHOD_NAME = "expect_user";
XmlRpcRequest GridReq = new XmlRpcRequest(METHOD_NAME, SendParams);
XmlRpcResponse GridResp = GridReq.Send(Util.XmlRpcRequestURI(regionInfo.httpServerURI, METHOD_NAME), 6000);
if (!GridResp.IsFault)
{
// We've received a successful response from the region.
// From the perspective of communicating with the region, we were able to get a response.
// Do not mark the region down if it responds, even if it doesn't allow the user into the region.
regionSuccess = true;
if (GridResp.Value != null)
{
Hashtable resp = (Hashtable)GridResp.Value;
if (resp.ContainsKey("success"))
{
if ((string)resp["success"] == "FALSE")
{
// Tell the user their login failed.
userSuccess = false;
}
}
if (!userSuccess)
{
if (resp.ContainsKey("reason"))
{
response.ErrorMessage = resp["reason"].ToString();
}
}
}
if (userSuccess)
{
handlerUserLoggedInAtLocation = OnUserLoggedInAtLocation;
if (handlerUserLoggedInAtLocation != null)
{
handlerUserLoggedInAtLocation(user.ID, user.CurrentAgent.SessionID,
user.CurrentAgent.Region,
user.CurrentAgent.Handle,
user.CurrentAgent.Position.X,
user.CurrentAgent.Position.Y,
user.CurrentAgent.Position.Z,
user.FirstName, user.SurName);
}
}
else
{
m_log.ErrorFormat("[LOGIN]: Region responded that it is not available to accept a login from {0} at this time.", user.Name);
}
}
else
{
m_log.ErrorFormat("[LOGIN]: XmlRpc request to region failed with message {0}, code {1} ", GridResp.FaultString, GridResp.FaultCode);
}
}
catch (Exception e)
{
m_log.ErrorFormat("[LOGIN]: Region not available for login, {0}", e);
}
lock (_LastRegionFailure)
{
if (_LastRegionFailure.ContainsKey(regionName))
{
RegionLoginFailure failure = _LastRegionFailure[regionName];
if (regionSuccess)
{ // Success, so if we've been storing this as a failed region, remove that from the failed list.
m_log.WarnFormat("[LOGIN]: Region '{0}' recently down, is available again.", regionName);
_LastRegionFailure.Remove(regionName);
}
else
{
// Region not available, update cache with incremented count.
failure.AddFailure();
// m_log.WarnFormat("[LOGIN]: Region '{0}' is still down ({1}).", regionName, failure.Count);
}
}
else
{
if (!regionSuccess)
{
// Region not available, cache that temporarily.
m_log.WarnFormat("[LOGIN]: Region '{0}' is down, marking.", regionName);
_LastRegionFailure[regionName] = new RegionLoginFailure();
}
}
}
return regionSuccess && userSuccess;
}
public XmlRpcResponse XmlRPCSetLoginParams(XmlRpcRequest request, IPEndPoint remoteClient)
{
XmlRpcResponse response = new XmlRpcResponse();
Hashtable requestData = (Hashtable)request.Params[0];
UserProfileData userProfile;
Hashtable responseData = new Hashtable();
UUID uid;
string pass = requestData["password"].ToString();
if (!UUID.TryParse((string)requestData["avatar_uuid"], out uid))
{
responseData["error"] = "No authorization";
response.Value = responseData;
return response;
}
userProfile = m_userManager.GetUserProfile(uid);
if (userProfile == null ||
(!AuthenticateUser(userProfile, pass)) ||
userProfile.GodLevel < 200)
{
responseData["error"] = "No authorization";
response.Value = responseData;
return response;
}
if (requestData.ContainsKey("login_level"))
{
m_minLoginLevel = Convert.ToInt32(requestData["login_level"]);
}
if (requestData.ContainsKey("login_motd"))
{
m_welcomeMessage = requestData["login_motd"].ToString();
}
response.Value = responseData;
return response;
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Text;
using Microsoft.Extensions.Logging;
using OmniSharp.FileSystem;
using OmniSharp.FileWatching;
using OmniSharp.Roslyn;
using OmniSharp.Roslyn.EditorConfig;
using OmniSharp.Roslyn.Utilities;
using OmniSharp.Utilities;
namespace OmniSharp
{
[Export, Shared]
public class OmniSharpWorkspace : Workspace
{
public bool Initialized
{
get { return isInitialized; }
set
{
if (isInitialized == value) return;
isInitialized = value;
OnInitialized(isInitialized);
}
}
public event Action<bool> OnInitialized = delegate { };
public bool EditorConfigEnabled { get; set; }
public BufferManager BufferManager { get; private set; }
private readonly ILogger<OmniSharpWorkspace> _logger;
private readonly ConcurrentBag<Func<string, Task>> _waitForProjectModelReadyHandlers = new ConcurrentBag<Func<string, Task>>();
private readonly ConcurrentDictionary<string, ProjectInfo> miscDocumentsProjectInfos = new ConcurrentDictionary<string, ProjectInfo>();
private readonly ConcurrentDictionary<ProjectId, Predicate<string>> documentInclusionRulesPerProject = new ConcurrentDictionary<ProjectId, Predicate<string>>();
private bool isInitialized;
[ImportingConstructor]
public OmniSharpWorkspace(HostServicesAggregator aggregator, ILoggerFactory loggerFactory, IFileSystemWatcher fileSystemWatcher)
: base(aggregator.CreateHostServices(), "Custom")
{
BufferManager = new BufferManager(this, loggerFactory, fileSystemWatcher);
_logger = loggerFactory.CreateLogger<OmniSharpWorkspace>();
fileSystemWatcher.WatchDirectories(OnDirectoryRemoved);
}
public override bool CanOpenDocuments => true;
private void OnDirectoryRemoved(string path, FileChangeType changeType)
{
if (changeType == FileChangeType.DirectoryDelete)
{
var docs = CurrentSolution.Projects.SelectMany(x => x.Documents)
.Where(x => x.FilePath.StartsWith(path + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase));
foreach (var doc in docs)
{
OnDocumentRemoved(doc.Id);
}
}
}
public void AddWaitForProjectModelReadyHandler(Func<string, Task> handler)
{
_waitForProjectModelReadyHandlers.Add(handler);
}
public override void OpenDocument(DocumentId documentId, bool activate = true)
{
var doc = this.CurrentSolution.GetDocument(documentId);
if (doc != null)
{
var text = doc.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
this.OnDocumentOpened(documentId, text.Container, activate);
}
}
public override void CloseDocument(DocumentId documentId)
{
var doc = this.CurrentSolution.GetDocument(documentId);
if (doc != null)
{
var text = doc.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
var version = doc.GetTextVersionAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
var loader = TextLoader.From(TextAndVersion.Create(text, version, doc.FilePath));
this.OnDocumentClosed(documentId, loader);
}
}
public void AddProject(ProjectInfo projectInfo)
{
OnProjectAdded(projectInfo);
}
public void AddDocumentInclusionRuleForProject(ProjectId projectId, Predicate<string> documentPathFilter)
{
documentInclusionRulesPerProject[projectId] = documentPathFilter;
}
public void AddProjectReference(ProjectId projectId, ProjectReference projectReference)
{
OnProjectReferenceAdded(projectId, projectReference);
}
public void RemoveProjectReference(ProjectId projectId, ProjectReference projectReference)
{
OnProjectReferenceRemoved(projectId, projectReference);
}
public void AddMetadataReference(ProjectId projectId, MetadataReference metadataReference)
{
OnMetadataReferenceAdded(projectId, metadataReference);
}
public void RemoveMetadataReference(ProjectId projectId, MetadataReference metadataReference)
{
OnMetadataReferenceRemoved(projectId, metadataReference);
}
public DocumentId TryAddMiscellaneousDocument(string filePath, TextLoader loader, string language)
{
if (GetDocument(filePath) != null)
return null; //if the workspace already knows about this document then it is not a miscellaneous document
var projectInfo = miscDocumentsProjectInfos.GetOrAdd(language, (lang) => CreateMiscFilesProject(lang));
var documentId = AddDocument(projectInfo.Id, filePath, loader);
_logger.LogInformation($"Miscellaneous file: {filePath} added to workspace");
if (!EditorConfigEnabled)
{
return documentId;
}
var analyzerConfigFiles = projectInfo.AnalyzerConfigDocuments.Select(document => document.FilePath);
var newAnalyzerConfigFiles = EditorConfigFinder
.GetEditorConfigPaths(filePath)
.Except(analyzerConfigFiles);
foreach (var analyzerConfigFile in newAnalyzerConfigFiles)
{
AddAnalyzerConfigDocument(projectInfo.Id, analyzerConfigFile);
}
return documentId;
}
public DocumentId TryAddMiscellaneousDocument(string filePath, string language)
{
return TryAddMiscellaneousDocument(filePath, new OmniSharpTextLoader(filePath), language);
}
public bool TryRemoveMiscellaneousDocument(string filePath)
{
var documentId = GetDocumentId(filePath);
if (documentId == null || !IsMiscellaneousDocument(documentId))
return false;
RemoveDocument(documentId);
_logger.LogDebug($"Miscellaneous file: {filePath} removed from workspace");
return true;
}
public void TryPromoteMiscellaneousDocumentsToProject(Project project)
{
if (project == null)
{
throw new ArgumentNullException(nameof(project));
}
var miscProjectInfos = miscDocumentsProjectInfos.Values.ToArray();
for (var i = 0; i < miscProjectInfos.Length; i++)
{
var miscProject = CurrentSolution.GetProject(miscProjectInfos[i].Id);
var documents = miscProject.Documents.ToArray();
for (var j = 0; j < documents.Length; j++)
{
var document = documents[j];
if (FileBelongsToProject(document.FilePath, project))
{
var textLoader = new DelegatingTextLoader(document);
var documentId = DocumentId.CreateNewId(project.Id);
var documentInfo = DocumentInfo.Create(
documentId,
document.FilePath,
filePath: document.FilePath,
loader: textLoader);
// This transitively will remove the document from the misc project.
AddDocument(documentInfo);
}
}
}
}
public void UpdateDiagnosticOptionsForProject(ProjectId projectId, ImmutableDictionary<string, ReportDiagnostic> rules)
{
var project = this.CurrentSolution.GetProject(projectId);
OnCompilationOptionsChanged(projectId, project.CompilationOptions.WithSpecificDiagnosticOptions(rules));
}
public void UpdateCompilationOptionsForProject(ProjectId projectId, CompilationOptions options)
{
OnCompilationOptionsChanged(projectId, options);
}
private ProjectInfo CreateMiscFilesProject(string language)
{
var projectInfo = ProjectInfo.Create(
id: ProjectId.CreateNewId(),
version: VersionStamp.Create(),
name: $"{Configuration.OmniSharpMiscProjectName}.csproj",
metadataReferences: DefaultMetadataReferenceHelper.GetDefaultMetadataReferenceLocations()
.Select(loc => MetadataReference.CreateFromFile(loc)),
assemblyName: Configuration.OmniSharpMiscProjectName,
language: language);
AddProject(projectInfo);
return projectInfo;
}
public void AddDocument(DocumentInfo documentInfo)
{
// if the file has already been added as a misc file,
// because of a possible race condition between the updates of the project systems,
// remove the misc file and add the document as required
TryRemoveMiscellaneousDocument(documentInfo.FilePath);
OnDocumentAdded(documentInfo);
}
public DocumentId AddDocument(ProjectId projectId, string filePath, SourceCodeKind sourceCodeKind = SourceCodeKind.Regular)
{
var project = this.CurrentSolution.GetProject(projectId);
return AddDocument(project, filePath, sourceCodeKind);
}
public DocumentId AddDocument(ProjectId projectId, string filePath, TextLoader loader, SourceCodeKind sourceCodeKind = SourceCodeKind.Regular)
{
var documentId = DocumentId.CreateNewId(projectId);
var project = this.CurrentSolution.GetProject(projectId);
return AddDocument(documentId, project, filePath, loader, sourceCodeKind);
}
public DocumentId AddDocument(Project project, string filePath, SourceCodeKind sourceCodeKind = SourceCodeKind.Regular)
{
var documentId = DocumentId.CreateNewId(project.Id);
return AddDocument(documentId, project, filePath, sourceCodeKind);
}
public DocumentId AddDocument(DocumentId documentId, Project project, string filePath, SourceCodeKind sourceCodeKind = SourceCodeKind.Regular)
{
return AddDocument(documentId, project, filePath, new OmniSharpTextLoader(filePath), sourceCodeKind);
}
internal DocumentId AddDocument(DocumentId documentId, ProjectId projectId, string filePath, TextLoader loader, SourceCodeKind sourceCodeKind = SourceCodeKind.Regular)
{
var project = this.CurrentSolution.GetProject(projectId);
return AddDocument(documentId, project, filePath, loader, sourceCodeKind);
}
internal DocumentId AddDocument(DocumentId documentId, Project project, string filePath, TextLoader loader, SourceCodeKind sourceCodeKind = SourceCodeKind.Regular)
{
var basePath = Path.GetDirectoryName(project.FilePath);
var fullPath = Path.GetDirectoryName(filePath);
IEnumerable<string> folders = null;
// folder computation is best effort. in case of exceptions, we back out because it's not essential for core features
try
{
// find the relative path from project file to our document
var relativeDocumentPath = FileSystemHelper.GetRelativePath(fullPath, basePath);
// only set document's folders if
// 1. relative path was computed
// 2. path is not pointing any level up
if (relativeDocumentPath != null && !relativeDocumentPath.StartsWith(".."))
{
folders = relativeDocumentPath?.Split(new[] { Path.DirectorySeparatorChar });
}
}
catch (Exception ex)
{
_logger.LogWarning(ex, $"An error occurred when computing a relative path from {basePath} to {fullPath}. Document at {filePath} will be processed without folder structure.");
}
var documentInfo = DocumentInfo.Create(documentId, Path.GetFileName(filePath), folders: folders, filePath: filePath, loader: loader, sourceCodeKind: sourceCodeKind);
AddDocument(documentInfo);
return documentId;
}
public void RemoveDocument(DocumentId documentId)
{
OnDocumentRemoved(documentId);
}
public void RemoveProject(ProjectId projectId)
{
OnProjectRemoved(projectId);
}
public void SetCompilationOptions(ProjectId projectId, CompilationOptions options)
{
OnCompilationOptionsChanged(projectId, options);
}
public void SetParseOptions(ProjectId projectId, ParseOptions parseOptions)
{
OnParseOptionsChanged(projectId, parseOptions);
}
public void OnDocumentChanged(DocumentId documentId, SourceText text)
{
OnDocumentTextChanged(documentId, text, PreservationMode.PreserveIdentity);
}
public DocumentId GetDocumentId(string filePath)
{
var documentIds = CurrentSolution.GetDocumentIdsWithFilePath(filePath);
return documentIds.FirstOrDefault();
}
public IEnumerable<Document> GetDocuments(string filePath)
{
return CurrentSolution
.GetDocumentIdsWithFilePath(filePath)
.Select(id => CurrentSolution.GetDocument(id))
.OfType<Document>();
}
public Document GetDocument(string filePath)
{
if (string.IsNullOrWhiteSpace(filePath)) return null;
var documentId = GetDocumentId(filePath);
if (documentId == null)
{
return null;
}
return CurrentSolution.GetDocument(documentId);
}
public async Task<IEnumerable<Document>> GetDocumentsFromFullProjectModelAsync(string filePath)
{
await OnWaitForProjectModelReadyAsync(filePath);
return GetDocuments(filePath);
}
public async Task<Document> GetDocumentFromFullProjectModelAsync(string filePath)
{
await OnWaitForProjectModelReadyAsync(filePath);
return GetDocument(filePath);
}
public override bool CanApplyChange(ApplyChangesKind feature)
{
return true;
}
internal bool FileBelongsToProject(string fileName, Project project)
{
if (string.IsNullOrWhiteSpace(project.FilePath) ||
string.IsNullOrWhiteSpace(fileName))
{
return false;
}
// File path needs to be checked against any rules defined by the specific project system. (e.g. MSBuild default excluded folders)
if (documentInclusionRulesPerProject.TryGetValue(project.Id, out Predicate<string> documentInclusionFilter))
{
return documentInclusionFilter(fileName);
}
// if no custom rule set for this ProjectId, fallback to simple directory heuristic.
var fileDirectory = new FileInfo(fileName).Directory;
var projectPath = project.FilePath;
var projectDirectory = new FileInfo(projectPath).Directory.FullName;
var otherProjectDirectories = CurrentSolution.Projects
.Where(p => p != project && !string.IsNullOrWhiteSpace(p.FilePath))
.Select(p => new FileInfo(p.FilePath).Directory.FullName)
.ToImmutableArray();
while (fileDirectory != null)
{
if (string.Equals(fileDirectory.FullName, projectDirectory, StringComparison.OrdinalIgnoreCase))
{
return true;
}
// if any project is closer to the file, file should belong to that project.
if (otherProjectDirectories.Contains(fileDirectory.FullName, StringComparer.OrdinalIgnoreCase))
{
return false;
}
fileDirectory = fileDirectory.Parent;
}
return false;
}
protected override void ApplyDocumentRemoved(DocumentId documentId)
{
var document = this.CurrentSolution.GetDocument(documentId);
if (document != null)
{
DeleteDocumentFile(document.Id, document.FilePath);
this.OnDocumentRemoved(documentId);
}
}
private void DeleteDocumentFile(DocumentId id, string fullPath)
{
try
{
File.Delete(fullPath);
}
catch (IOException e)
{
LogDeletionException(e, fullPath);
}
catch (NotSupportedException e)
{
LogDeletionException(e, fullPath);
}
catch (UnauthorizedAccessException e)
{
LogDeletionException(e, fullPath);
}
}
private void LogDeletionException(Exception e, string filePath)
{
_logger.LogError(e, $"Error deleting file {filePath}");
}
protected override void ApplyDocumentAdded(DocumentInfo info, SourceText text)
{
var fullPath = info.FilePath;
this.OnDocumentAdded(info);
if (text != null)
{
this.SaveDocumentText(info.Id, fullPath, text, text.Encoding ?? Encoding.UTF8);
}
}
private void SaveDocumentText(DocumentId id, string fullPath, SourceText newText, Encoding encoding)
{
try
{
var dir = Path.GetDirectoryName(fullPath);
if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
using (var writer = new StreamWriter(fullPath, append: false, encoding: encoding))
{
newText.Write(writer);
}
}
catch (IOException e)
{
_logger.LogError(e, $"Error saving document {fullPath}");
}
}
public bool IsCapableOfSemanticDiagnostics(Document document)
{
return !IsMiscellaneousDocument(document.Id);
}
private bool IsMiscellaneousDocument(DocumentId documentId)
{
return miscDocumentsProjectInfos.Where(p => p.Value.Id == documentId.ProjectId).Any();
}
private class DelegatingTextLoader : TextLoader
{
private readonly Document _fromDocument;
public DelegatingTextLoader(Document fromDocument)
{
_fromDocument = fromDocument ?? throw new ArgumentNullException(nameof(fromDocument));
}
public override async Task<TextAndVersion> LoadTextAndVersionAsync(
Workspace workspace,
DocumentId documentId,
CancellationToken cancellationToken)
{
var sourceText = await _fromDocument.GetTextAsync();
var version = await _fromDocument.GetTextVersionAsync();
var textAndVersion = TextAndVersion.Create(sourceText, version);
return textAndVersion;
}
}
private Task OnWaitForProjectModelReadyAsync(string filePath)
{
return Task.WhenAll(_waitForProjectModelReadyHandlers.Select(h => h(filePath)));
}
public void SetAnalyzerReferences(ProjectId id, ImmutableArray<AnalyzerFileReference> analyzerReferences)
{
var project = this.CurrentSolution.GetProject(id);
var refsToAdd = analyzerReferences.Where(newRef => project.AnalyzerReferences.All(oldRef => oldRef.Display != newRef.Display));
var refsToRemove = project.AnalyzerReferences.Where(newRef => analyzerReferences.All(oldRef => oldRef.Display != newRef.Display));
foreach (var toAdd in refsToAdd)
{
_logger.LogInformation($"Adding analyzer reference: {toAdd.FullPath}");
base.OnAnalyzerReferenceAdded(id, toAdd);
}
foreach (var toRemove in refsToRemove)
{
_logger.LogInformation($"Removing analyzer reference: {toRemove.FullPath}");
base.OnAnalyzerReferenceRemoved(id, toRemove);
}
}
public void AddAdditionalDocument(ProjectId projectId, string filePath)
{
var loader = new OmniSharpTextLoader(filePath);
AddAdditionalDocument(projectId, filePath, loader);
}
public void AddAdditionalDocument(ProjectId projectId, string filePath, TextLoader loader)
{
var documentId = DocumentId.CreateNewId(projectId);
var documentInfo = DocumentInfo.Create(documentId, Path.GetFileName(filePath), filePath: filePath, loader: loader);
OnAdditionalDocumentAdded(documentInfo);
}
public void AddAnalyzerConfigDocument(ProjectId projectId, string filePath)
{
var documentId = DocumentId.CreateNewId(projectId);
var loader = new OmniSharpTextLoader(filePath);
var documentInfo = DocumentInfo.Create(documentId, Path.GetFileName(filePath), filePath: filePath, loader: loader);
OnAnalyzerConfigDocumentAdded(documentInfo);
}
public void ReloadAnalyzerConfigDocument(DocumentId documentId, string filePath)
{
var loader = new OmniSharpTextLoader(filePath);
OnAnalyzerConfigDocumentTextLoaderChanged(documentId, loader);
}
public void RemoveAdditionalDocument(DocumentId documentId)
{
OnAdditionalDocumentRemoved(documentId);
}
public void RemoveAnalyzerConfigDocument(DocumentId documentId)
{
OnAnalyzerConfigDocumentRemoved(documentId);
}
protected override void ApplyProjectChanges(ProjectChanges projectChanges)
{
// since Roslyn currently doesn't handle DefaultNamespace changes via ApplyProjectChanges
// and OnDefaultNamespaceChanged is internal, we use reflection for now
if (projectChanges.NewProject.DefaultNamespace != projectChanges.OldProject.DefaultNamespace)
{
var onDefaultNamespaceChanged = this.GetType().GetMethod("OnDefaultNamespaceChanged", BindingFlags.Instance | BindingFlags.NonPublic);
if (onDefaultNamespaceChanged != null)
{
onDefaultNamespaceChanged.Invoke(this, new object[] { projectChanges.ProjectId, projectChanges.NewProject.DefaultNamespace });
}
}
base.ApplyProjectChanges(projectChanges);
}
}
}
| |
using System;
using System.IO;
using System.Linq;
using System.Text;
using NUnit.Framework;
using Mono.Cecil.Cil;
using Mono.Cecil.Pdb;
using Mono.Cecil.PE;
namespace Mono.Cecil.Tests {
[TestFixture]
public class PortablePdbTests : BaseTestFixture {
[Test]
public void SequencePoints ()
{
TestPortablePdbModule (module => {
var type = module.GetType ("PdbTarget.Program");
var main = type.GetMethod ("Main");
AssertCode (@"
.locals init (System.Int32 a, System.String[] V_1, System.Int32 V_2, System.String arg)
.line 21,21:3,4 'C:\sources\PdbTarget\Program.cs'
IL_0000: nop
.line 22,22:4,11 'C:\sources\PdbTarget\Program.cs'
IL_0001: nop
.line 22,22:24,28 'C:\sources\PdbTarget\Program.cs'
IL_0002: ldarg.0
IL_0003: stloc.1
IL_0004: ldc.i4.0
IL_0005: stloc.2
.line hidden 'C:\sources\PdbTarget\Program.cs'
IL_0006: br.s IL_0017
.line 22,22:13,20 'C:\sources\PdbTarget\Program.cs'
IL_0008: ldloc.1
IL_0009: ldloc.2
IL_000a: ldelem.ref
IL_000b: stloc.3
.line 23,23:5,20 'C:\sources\PdbTarget\Program.cs'
IL_000c: ldloc.3
IL_000d: call System.Void System.Console::WriteLine(System.String)
IL_0012: nop
.line hidden 'C:\sources\PdbTarget\Program.cs'
IL_0013: ldloc.2
IL_0014: ldc.i4.1
IL_0015: add
IL_0016: stloc.2
.line 22,22:21,23 'C:\sources\PdbTarget\Program.cs'
IL_0017: ldloc.2
IL_0018: ldloc.1
IL_0019: ldlen
IL_001a: conv.i4
IL_001b: blt.s IL_0008
.line 25,25:4,22 'C:\sources\PdbTarget\Program.cs'
IL_001d: ldc.i4.1
IL_001e: ldc.i4.2
IL_001f: call System.Int32 System.Math::Min(System.Int32,System.Int32)
IL_0024: stloc.0
.line 26,26:3,4 'C:\sources\PdbTarget\Program.cs'
IL_0025: ret
", main);
});
}
[Test]
public void SequencePointsMultipleDocument ()
{
TestPortablePdbModule (module => {
var type = module.GetType ("PdbTarget.B");
var main = type.GetMethod (".ctor");
AssertCode (@"
.locals ()
.line 7,7:3,25 'C:\sources\PdbTarget\B.cs'
IL_0000: ldarg.0
IL_0001: ldstr """"
IL_0006: stfld System.String PdbTarget.B::s
.line 110,110:3,21 'C:\sources\PdbTarget\Program.cs'
IL_000b: ldarg.0
IL_000c: ldc.i4.2
IL_000d: stfld System.Int32 PdbTarget.B::a
.line 111,111:3,21 'C:\sources\PdbTarget\Program.cs'
IL_0012: ldarg.0
IL_0013: ldc.i4.3
IL_0014: stfld System.Int32 PdbTarget.B::b
.line 9,9:3,13 'C:\sources\PdbTarget\B.cs'
IL_0019: ldarg.0
IL_001a: call System.Void System.Object::.ctor()
IL_001f: nop
.line 10,10:3,4 'C:\sources\PdbTarget\B.cs'
IL_0020: nop
.line 11,11:4,19 'C:\sources\PdbTarget\B.cs'
IL_0021: ldstr ""B""
IL_0026: call System.Void System.Console::WriteLine(System.String)
IL_002b: nop
.line 12,12:3,4 'C:\sources\PdbTarget\B.cs'
IL_002c: ret
", main);
});
}
[Test]
public void LocalVariables ()
{
TestPortablePdbModule (module => {
var type = module.GetType ("PdbTarget.Program");
var method = type.GetMethod ("Bar");
var debug_info = method.DebugInformation;
Assert.IsNotNull (debug_info.Scope);
Assert.IsTrue (debug_info.Scope.HasScopes);
Assert.AreEqual (2, debug_info.Scope.Scopes.Count);
var scope = debug_info.Scope.Scopes [0];
Assert.IsNotNull (scope);
Assert.IsTrue (scope.HasVariables);
Assert.AreEqual (1, scope.Variables.Count);
var variable = scope.Variables [0];
Assert.AreEqual ("s", variable.Name);
Assert.IsFalse (variable.IsDebuggerHidden);
Assert.AreEqual (2, variable.Index);
scope = debug_info.Scope.Scopes [1];
Assert.IsNotNull (scope);
Assert.IsTrue (scope.HasVariables);
Assert.AreEqual (1, scope.Variables.Count);
variable = scope.Variables [0];
Assert.AreEqual ("s", variable.Name);
Assert.IsFalse (variable.IsDebuggerHidden);
Assert.AreEqual (3, variable.Index);
Assert.IsTrue (scope.HasScopes);
Assert.AreEqual (1, scope.Scopes.Count);
scope = scope.Scopes [0];
Assert.IsNotNull (scope);
Assert.IsTrue (scope.HasVariables);
Assert.AreEqual (1, scope.Variables.Count);
variable = scope.Variables [0];
Assert.AreEqual ("u", variable.Name);
Assert.IsFalse (variable.IsDebuggerHidden);
Assert.AreEqual (5, variable.Index);
});
}
[Test]
public void LocalConstants ()
{
TestPortablePdbModule (module => {
var type = module.GetType ("PdbTarget.Program");
var method = type.GetMethod ("Bar");
var debug_info = method.DebugInformation;
Assert.IsNotNull (debug_info.Scope);
Assert.IsTrue (debug_info.Scope.HasScopes);
Assert.AreEqual (2, debug_info.Scope.Scopes.Count);
var scope = debug_info.Scope.Scopes [1];
Assert.IsNotNull (scope);
Assert.IsTrue (scope.HasConstants);
Assert.AreEqual (2, scope.Constants.Count);
var constant = scope.Constants [0];
Assert.AreEqual ("b", constant.Name);
Assert.AreEqual (12, constant.Value);
Assert.AreEqual (MetadataType.Int32, constant.ConstantType.MetadataType);
constant = scope.Constants [1];
Assert.AreEqual ("c", constant.Name);
Assert.AreEqual ((decimal) 74, constant.Value);
Assert.AreEqual (MetadataType.ValueType, constant.ConstantType.MetadataType);
method = type.GetMethod ("Foo");
debug_info = method.DebugInformation;
Assert.IsNotNull (debug_info.Scope);
Assert.IsTrue (debug_info.Scope.HasConstants);
Assert.AreEqual (4, debug_info.Scope.Constants.Count);
constant = debug_info.Scope.Constants [0];
Assert.AreEqual ("s", constant.Name);
Assert.AreEqual ("const string", constant.Value);
Assert.AreEqual (MetadataType.String, constant.ConstantType.MetadataType);
constant = debug_info.Scope.Constants [1];
Assert.AreEqual ("f", constant.Name);
Assert.AreEqual (1, constant.Value);
Assert.AreEqual (MetadataType.Int32, constant.ConstantType.MetadataType);
constant = debug_info.Scope.Constants [2];
Assert.AreEqual ("o", constant.Name);
Assert.AreEqual (null, constant.Value);
Assert.AreEqual (MetadataType.Object, constant.ConstantType.MetadataType);
constant = debug_info.Scope.Constants [3];
Assert.AreEqual ("u", constant.Name);
Assert.AreEqual (null, constant.Value);
Assert.AreEqual (MetadataType.String, constant.ConstantType.MetadataType);
});
}
[Test]
public void ImportScope ()
{
TestPortablePdbModule (module => {
var type = module.GetType ("PdbTarget.Program");
var method = type.GetMethod ("Bar");
var debug_info = method.DebugInformation;
Assert.IsNotNull (debug_info.Scope);
var import = debug_info.Scope.Import;
Assert.IsNotNull (import);
Assert.IsFalse (import.HasTargets);
Assert.IsNotNull (import.Parent);
import = import.Parent;
Assert.IsTrue (import.HasTargets);
Assert.AreEqual (9, import.Targets.Count);
var target = import.Targets [0];
Assert.AreEqual (ImportTargetKind.ImportAlias, target.Kind);
Assert.AreEqual ("XML", target.Alias);
target = import.Targets [1];
Assert.AreEqual (ImportTargetKind.ImportNamespace, target.Kind);
Assert.AreEqual ("System", target.Namespace);
target = import.Targets [2];
Assert.AreEqual (ImportTargetKind.ImportNamespace, target.Kind);
Assert.AreEqual ("System.Collections.Generic", target.Namespace);
target = import.Targets [3];
Assert.AreEqual (ImportTargetKind.ImportNamespace, target.Kind);
Assert.AreEqual ("System.IO", target.Namespace);
target = import.Targets [4];
Assert.AreEqual (ImportTargetKind.ImportNamespace, target.Kind);
Assert.AreEqual ("System.Threading.Tasks", target.Namespace);
target = import.Targets [5];
Assert.AreEqual (ImportTargetKind.ImportNamespaceInAssembly, target.Kind);
Assert.AreEqual ("System.Xml.Resolvers", target.Namespace);
Assert.AreEqual ("System.Xml", target.AssemblyReference.Name);
target = import.Targets [6];
Assert.AreEqual (ImportTargetKind.ImportType, target.Kind);
Assert.AreEqual ("System.Console", target.Type.FullName);
target = import.Targets [7];
Assert.AreEqual (ImportTargetKind.ImportType, target.Kind);
Assert.AreEqual ("System.Math", target.Type.FullName);
target = import.Targets [8];
Assert.AreEqual (ImportTargetKind.DefineTypeAlias, target.Kind);
Assert.AreEqual ("Foo", target.Alias);
Assert.AreEqual ("System.Xml.XmlDocumentType", target.Type.FullName);
Assert.IsNotNull (import.Parent);
import = import.Parent;
Assert.IsTrue (import.HasTargets);
Assert.AreEqual (1, import.Targets.Count);
Assert.IsNull (import.Parent);
target = import.Targets [0];
Assert.AreEqual (ImportTargetKind.DefineAssemblyAlias, target.Kind);
Assert.AreEqual ("XML", target.Alias);
Assert.AreEqual ("System.Xml", target.AssemblyReference.Name);
});
}
[Test]
public void StateMachineKickOff ()
{
TestPortablePdbModule (module => {
var state_machine = module.GetType ("PdbTarget.Program/<Baz>d__7");
var main = state_machine.GetMethod ("MoveNext");
var symbol = main.DebugInformation;
Assert.IsNotNull (symbol);
Assert.IsNotNull (symbol.StateMachineKickOffMethod);
Assert.AreEqual ("System.Threading.Tasks.Task PdbTarget.Program::Baz(System.IO.StreamReader)", symbol.StateMachineKickOffMethod.FullName);
});
}
[Test]
public void StateMachineCustomDebugInformation ()
{
TestPortablePdbModule (module => {
var state_machine = module.GetType ("PdbTarget.Program/<Baz>d__7");
var move_next = state_machine.GetMethod ("MoveNext");
Assert.IsTrue (move_next.HasCustomDebugInformations);
var state_machine_scope = move_next.CustomDebugInformations.OfType<StateMachineScopeDebugInformation> ().FirstOrDefault ();
Assert.IsNotNull (state_machine_scope);
Assert.AreEqual (3, state_machine_scope.Scopes.Count);
Assert.AreEqual (0, state_machine_scope.Scopes [0].Start.Offset);
Assert.IsTrue (state_machine_scope.Scopes [0].End.IsEndOfMethod);
Assert.AreEqual (0, state_machine_scope.Scopes [1].Start.Offset);
Assert.AreEqual (0, state_machine_scope.Scopes [1].End.Offset);
Assert.AreEqual (184, state_machine_scope.Scopes [2].Start.Offset);
Assert.AreEqual (343, state_machine_scope.Scopes [2].End.Offset);
var async_body = move_next.CustomDebugInformations.OfType<AsyncMethodBodyDebugInformation> ().FirstOrDefault ();
Assert.IsNotNull (async_body);
Assert.AreEqual (-1, async_body.CatchHandler.Offset);
Assert.AreEqual (2, async_body.Yields.Count);
Assert.AreEqual (61, async_body.Yields [0].Offset);
Assert.AreEqual (221, async_body.Yields [1].Offset);
Assert.AreEqual (2, async_body.Resumes.Count);
Assert.AreEqual (91, async_body.Resumes [0].Offset);
Assert.AreEqual (252, async_body.Resumes [1].Offset);
Assert.AreEqual (move_next, async_body.ResumeMethods [0]);
Assert.AreEqual (move_next, async_body.ResumeMethods [1]);
});
}
[Test]
public void EmbeddedCompressedPortablePdb ()
{
TestModule("EmbeddedCompressedPdbTarget.exe", module => {
Assert.IsTrue (module.HasDebugHeader);
var header = module.GetDebugHeader ();
Assert.IsNotNull (header);
Assert.AreEqual (2, header.Entries.Length);
var cv = header.Entries [0];
Assert.AreEqual (ImageDebugType.CodeView, cv.Directory.Type);
var eppdb = header.Entries [1];
Assert.AreEqual (ImageDebugType.EmbeddedPortablePdb, eppdb.Directory.Type);
Assert.AreEqual (0x0100, eppdb.Directory.MajorVersion);
Assert.AreEqual (0x0100, eppdb.Directory.MinorVersion);
}, symbolReaderProvider: typeof (EmbeddedPortablePdbReaderProvider), symbolWriterProvider: typeof (EmbeddedPortablePdbWriterProvider));
}
[Test]
public void EmbeddedCompressedPortablePdbFromStream ()
{
var bytes = File.ReadAllBytes (GetAssemblyResourcePath ("EmbeddedCompressedPdbTarget.exe"));
var parameters = new ReaderParameters {
ReadSymbols = true,
SymbolReaderProvider = new PdbReaderProvider ()
};
var module = ModuleDefinition.ReadModule (new MemoryStream(bytes), parameters);
Assert.IsTrue (module.HasDebugHeader);
var header = module.GetDebugHeader ();
Assert.IsNotNull (header);
Assert.AreEqual (2, header.Entries.Length);
var cv = header.Entries [0];
Assert.AreEqual (ImageDebugType.CodeView, cv.Directory.Type);
var eppdb = header.Entries [1];
Assert.AreEqual (ImageDebugType.EmbeddedPortablePdb, eppdb.Directory.Type);
Assert.AreEqual (0x0100, eppdb.Directory.MajorVersion);
Assert.AreEqual (0x0100, eppdb.Directory.MinorVersion);
}
void TestPortablePdbModule (Action<ModuleDefinition> test)
{
TestModule ("PdbTarget.exe", test, symbolReaderProvider: typeof (PortablePdbReaderProvider), symbolWriterProvider: typeof (PortablePdbWriterProvider));
TestModule ("EmbeddedPdbTarget.exe", test, verify: !Platform.OnMono);
TestModule ("EmbeddedCompressedPdbTarget.exe", test, symbolReaderProvider: typeof(EmbeddedPortablePdbReaderProvider), symbolWriterProvider: typeof(EmbeddedPortablePdbWriterProvider));
}
[Test]
public void RoundTripCecilPortablePdb ()
{
TestModule ("cecil.dll", module => {
Assert.IsTrue (module.HasSymbols);
}, symbolReaderProvider: typeof (PortablePdbReaderProvider), symbolWriterProvider: typeof (PortablePdbWriterProvider));
}
[Test]
public void RoundTripLargePortablePdb ()
{
TestModule ("Mono.Android.dll", module => {
Assert.IsTrue (module.HasSymbols);
}, verify: false, symbolReaderProvider: typeof (PortablePdbReaderProvider), symbolWriterProvider: typeof (PortablePdbWriterProvider));
}
[Test]
public void EmptyPortablePdb ()
{
TestModule ("EmptyPdb.dll", module => {
Assert.IsTrue (module.HasSymbols);
}, symbolReaderProvider: typeof (PortablePdbReaderProvider), symbolWriterProvider: typeof (PortablePdbWriterProvider));
}
[Test]
public void NullClassConstant ()
{
TestModule ("xattr.dll", module => {
var type = module.GetType ("Library");
var method = type.GetMethod ("NullXAttributeConstant");
var symbol = method.DebugInformation;
Assert.IsNotNull (symbol);
Assert.AreEqual (1, symbol.Scope.Constants.Count);
var a = symbol.Scope.Constants [0];
Assert.AreEqual ("a", a.Name);
}, symbolReaderProvider: typeof (PortablePdbReaderProvider), symbolWriterProvider: typeof (PortablePdbWriterProvider));
}
[Test]
public void InvalidConstantRecord ()
{
using (var module = GetResourceModule ("mylib.dll", new ReaderParameters { SymbolReaderProvider = new PortablePdbReaderProvider () })) {
var type = module.GetType ("mylib.Say");
var method = type.GetMethod ("hello");
var symbol = method.DebugInformation;
Assert.IsNotNull (symbol);
Assert.AreEqual (0, symbol.Scope.Constants.Count);
}
}
[Test]
public void GenericInstConstantRecord ()
{
using (var module = GetResourceModule ("ReproConstGenericInst.dll", new ReaderParameters { SymbolReaderProvider = new PortablePdbReaderProvider () })) {
var type = module.GetType ("ReproConstGenericInst.Program");
var method = type.GetMethod ("Main");
var symbol = method.DebugInformation;
Assert.IsNotNull (symbol);
Assert.AreEqual (1, symbol.Scope.Constants.Count);
var list = symbol.Scope.Constants [0];
Assert.AreEqual ("list", list.Name);
Assert.AreEqual ("System.Collections.Generic.List`1<System.String>", list.ConstantType.FullName);
}
}
[Test]
public void SourceLink ()
{
TestModule ("TargetLib.dll", module => {
Assert.IsTrue (module.HasCustomDebugInformations);
Assert.AreEqual (1, module.CustomDebugInformations.Count);
var source_link = module.CustomDebugInformations [0] as SourceLinkDebugInformation;
Assert.IsNotNull (source_link);
Assert.AreEqual ("{\"documents\":{\"C:\\\\tmp\\\\SourceLinkProblem\\\\*\":\"https://raw.githubusercontent.com/bording/SourceLinkProblem/197d965ee7f1e7f8bd3cea55b5f904aeeb8cd51e/*\"}}", source_link.Content);
}, symbolReaderProvider: typeof (PortablePdbReaderProvider), symbolWriterProvider: typeof (PortablePdbWriterProvider));
}
[Test]
public void EmbeddedSource ()
{
TestModule ("embedcs.exe", module => {
}, symbolReaderProvider: typeof (PortablePdbReaderProvider), symbolWriterProvider: typeof (PortablePdbWriterProvider));
TestModule ("embedcs.exe", module => {
var program = GetDocument (module.GetType ("Program"));
var program_src = GetSourceDebugInfo (program);
Assert.IsTrue (program_src.Compress);
var program_src_content = Encoding.UTF8.GetString (program_src.Content);
Assert.AreEqual (Normalize (@"using System;
class Program
{
static void Main()
{
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
// Hello hello hello hello hello hello
Console.WriteLine(B.Do());
Console.WriteLine(A.Do());
}
}
"), Normalize (program_src_content));
var a = GetDocument (module.GetType ("A"));
var a_src = GetSourceDebugInfo (a);
Assert.IsFalse (a_src.Compress);
var a_src_content = Encoding.UTF8.GetString (a_src.Content);
Assert.AreEqual (Normalize (@"class A
{
public static string Do()
{
return ""A::Do"";
}
}"), Normalize (a_src_content));
var b = GetDocument(module.GetType ("B"));
var b_src = GetSourceDebugInfo (b);
Assert.IsFalse (b_src.compress);
var b_src_content = Encoding.UTF8.GetString (b_src.Content);
Assert.AreEqual (Normalize (@"class B
{
public static string Do()
{
return ""B::Do"";
}
}"), Normalize (b_src_content));
}, symbolReaderProvider: typeof (PortablePdbReaderProvider), symbolWriterProvider: typeof (PortablePdbWriterProvider));
}
static Document GetDocument (TypeDefinition type)
{
foreach (var method in type.Methods) {
if (!method.HasBody)
continue;
foreach (var instruction in method.Body.Instructions) {
var sp = method.DebugInformation.GetSequencePoint (instruction);
if (sp != null && sp.Document != null)
return sp.Document;
}
}
return null;
}
static EmbeddedSourceDebugInformation GetSourceDebugInfo (Document document)
{
Assert.IsTrue (document.HasCustomDebugInformations);
Assert.AreEqual (1, document.CustomDebugInformations.Count);
var source = document.CustomDebugInformations [0] as EmbeddedSourceDebugInformation;
Assert.IsNotNull (source);
return source;
}
[Test]
public void PortablePdbLineInfo ()
{
TestModule ("line.exe", module => {
var type = module.GetType ("Tests");
var main = type.GetMethod ("Main");
AssertCode (@"
.locals ()
.line 4,4:42,43 '/foo/bar.cs'
IL_0000: nop
.line 5,5:2,3 '/foo/bar.cs'
IL_0001: ret", main);
}, symbolReaderProvider: typeof (PortablePdbReaderProvider), symbolWriterProvider: typeof (PortablePdbWriterProvider));
}
public sealed class SymbolWriterProvider : ISymbolWriterProvider {
readonly DefaultSymbolWriterProvider writer_provider = new DefaultSymbolWriterProvider ();
public ISymbolWriter GetSymbolWriter (ModuleDefinition module, string fileName)
{
return new SymbolWriter (writer_provider.GetSymbolWriter (module, fileName));
}
public ISymbolWriter GetSymbolWriter (ModuleDefinition module, Stream symbolStream)
{
return new SymbolWriter (writer_provider.GetSymbolWriter (module, symbolStream));
}
}
public sealed class SymbolWriter : ISymbolWriter {
readonly ISymbolWriter symbol_writer;
public SymbolWriter (ISymbolWriter symbolWriter)
{
this.symbol_writer = symbolWriter;
}
public ImageDebugHeader GetDebugHeader ()
{
var header = symbol_writer.GetDebugHeader ();
if (!header.HasEntries)
return header;
for (int i = 0; i < header.Entries.Length; i++) {
header.Entries [i] = ProcessEntry (header.Entries [i]);
}
return header;
}
private static ImageDebugHeaderEntry ProcessEntry (ImageDebugHeaderEntry entry)
{
if (entry.Directory.Type != ImageDebugType.CodeView)
return entry;
var reader = new ByteBuffer (entry.Data);
var writer = new ByteBuffer ();
var sig = reader.ReadUInt32 ();
if (sig != 0x53445352)
return entry;
writer.WriteUInt32 (sig); // RSDS
writer.WriteBytes (reader.ReadBytes (16)); // MVID
writer.WriteUInt32 (reader.ReadUInt32 ()); // Age
var length = Array.IndexOf (entry.Data, (byte) 0, reader.position) - reader.position;
var fullPath = Encoding.UTF8.GetString (reader.ReadBytes (length));
writer.WriteBytes (Encoding.UTF8.GetBytes (Path.GetFileName (fullPath)));
writer.WriteByte (0);
var newData = new byte [writer.length];
Buffer.BlockCopy (writer.buffer, 0, newData, 0, writer.length);
var directory = entry.Directory;
directory.SizeOfData = newData.Length;
return new ImageDebugHeaderEntry (directory, newData);
}
public ISymbolReaderProvider GetReaderProvider ()
{
return symbol_writer.GetReaderProvider ();
}
public void Write (MethodDebugInformation info)
{
symbol_writer.Write (info);
}
public void Dispose ()
{
symbol_writer.Dispose ();
}
}
static string GetDebugHeaderPdbPath (ModuleDefinition module)
{
var header = module.GetDebugHeader ();
var cv = Mixin.GetCodeViewEntry (header);
Assert.IsNotNull (cv);
var length = Array.IndexOf (cv.Data, (byte)0, 24) - 24;
var bytes = new byte [length];
Buffer.BlockCopy (cv.Data, 24, bytes, 0, length);
return Encoding.UTF8.GetString (bytes);
}
[Test]
public void UseCustomSymbolWriterToChangeDebugHeaderPdbPath ()
{
const string resource = "mylib.dll";
string debug_header_pdb_path;
string dest = Path.Combine (Path.GetTempPath (), resource);
using (var module = GetResourceModule (resource, new ReaderParameters { SymbolReaderProvider = new PortablePdbReaderProvider () })) {
debug_header_pdb_path = GetDebugHeaderPdbPath (module);
Assert.IsTrue (Path.IsPathRooted (debug_header_pdb_path));
module.Write (dest, new WriterParameters { SymbolWriterProvider = new SymbolWriterProvider () });
}
using (var module = ModuleDefinition.ReadModule (dest, new ReaderParameters { SymbolReaderProvider = new PortablePdbReaderProvider () })) {
var pdb_path = GetDebugHeaderPdbPath (module);
Assert.IsFalse (Path.IsPathRooted (pdb_path));
Assert.AreEqual (Path.GetFileName (debug_header_pdb_path), pdb_path);
}
}
[Test]
public void WriteAndReadAgainModuleWithDeterministicMvid ()
{
const string resource = "mylib.dll";
string destination = Path.GetTempFileName ();
using (var module = GetResourceModule (resource, new ReaderParameters { SymbolReaderProvider = new PortablePdbReaderProvider () })) {
module.Write (destination, new WriterParameters { DeterministicMvid = true, SymbolWriterProvider = new SymbolWriterProvider () });
}
using (var module = ModuleDefinition.ReadModule (destination, new ReaderParameters { SymbolReaderProvider = new PortablePdbReaderProvider () })) {
}
}
[Test]
public void DoubleWriteAndReadAgainModuleWithDeterministicMvid ()
{
Guid mvid1_in, mvid1_out, mvid2_in, mvid2_out;
{
const string resource = "foo.dll";
string destination = Path.GetTempFileName ();
using (var module = GetResourceModule (resource, new ReaderParameters { })) {
mvid1_in = module.Mvid;
module.Write (destination, new WriterParameters { DeterministicMvid = true });
}
using (var module = ModuleDefinition.ReadModule (destination, new ReaderParameters { })) {
mvid1_out = module.Mvid;
}
}
{
const string resource = "hello2.exe";
string destination = Path.GetTempFileName ();
using (var module = GetResourceModule (resource, new ReaderParameters { })) {
mvid2_in = module.Mvid;
module.Write (destination, new WriterParameters { DeterministicMvid = true });
}
using (var module = ModuleDefinition.ReadModule (destination, new ReaderParameters { })) {
mvid2_out = module.Mvid;
}
}
Assert.AreNotEqual (mvid1_in, mvid2_in);
Assert.AreNotEqual (mvid1_out, mvid2_out);
}
[Test]
public void ClearSequencePoints ()
{
TestPortablePdbModule (module => {
var type = module.GetType ("PdbTarget.Program");
var main = type.GetMethod ("Main");
main.DebugInformation.SequencePoints.Clear ();
var destination = Path.Combine (Path.GetTempPath (), "mylib.dll");
module.Write(destination, new WriterParameters { WriteSymbols = true });
Assert.Zero (main.DebugInformation.SequencePoints.Count);
using (var resultModule = ModuleDefinition.ReadModule (destination, new ReaderParameters { ReadSymbols = true })) {
type = resultModule.GetType ("PdbTarget.Program");
main = type.GetMethod ("Main");
Assert.Zero (main.DebugInformation.SequencePoints.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.
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Xunit;
namespace System.Threading.Tests
{
public class MutexTests : RemoteExecutorTestBase
{
private const int FailedWaitTimeout = 30000;
[Fact]
public void Ctor_ConstructWaitRelease()
{
using (Mutex m = new Mutex())
{
Assert.True(m.WaitOne(FailedWaitTimeout));
m.ReleaseMutex();
}
using (Mutex m = new Mutex(false))
{
Assert.True(m.WaitOne(FailedWaitTimeout));
m.ReleaseMutex();
}
using (Mutex m = new Mutex(true))
{
Assert.True(m.WaitOne(FailedWaitTimeout));
m.ReleaseMutex();
m.ReleaseMutex();
}
}
[Fact]
public void Ctor_InvalidName()
{
AssertExtensions.Throws<ArgumentException>("name", null, () => new Mutex(false, new string('a', 1000)));
}
[Fact]
public void Ctor_ValidName()
{
string name = Guid.NewGuid().ToString("N");
bool createdNew;
using (Mutex m1 = new Mutex(false, name, out createdNew))
{
Assert.True(createdNew);
using (Mutex m2 = new Mutex(false, name, out createdNew))
{
Assert.False(createdNew);
}
}
}
[PlatformSpecific(TestPlatforms.Windows)] // named semaphores aren't supported on Unix
[Fact]
public void Ctor_NameUsedByOtherSynchronizationPrimitive_Windows()
{
string name = Guid.NewGuid().ToString("N");
using (Semaphore s = new Semaphore(1, 1, name))
{
Assert.Throws<WaitHandleCannotBeOpenedException>(() => new Mutex(false, name));
}
}
[PlatformSpecific(TestPlatforms.Windows)]
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWinRT))] // Can't create global objects in appcontainer
[SkipOnTargetFramework(
TargetFrameworkMonikers.NetFramework,
"The fix necessary for this test (PR https://github.com/dotnet/coreclr/pull/12381) is not in the .NET Framework.")]
public void Ctor_ImpersonateAnonymousAndTryCreateGlobalMutexTest()
{
ThreadTestHelpers.RunTestInBackgroundThread(() =>
{
if (!ImpersonateAnonymousToken(GetCurrentThread()))
{
// Impersonation is not allowed in the current context, this test is inappropriate in such a case
return;
}
Assert.Throws<UnauthorizedAccessException>(() => new Mutex(false, "Global\\" + Guid.NewGuid().ToString("N")));
Assert.True(RevertToSelf());
});
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsWinRT))] // Can't create global objects in appcontainer
[PlatformSpecific(TestPlatforms.Windows)]
public void Ctor_TryCreateGlobalMutexTest_Uwp()
{
ThreadTestHelpers.RunTestInBackgroundThread(() =>
Assert.Throws<UnauthorizedAccessException>(() => new Mutex(false, "Global\\" + Guid.NewGuid().ToString("N"))));
}
[Fact]
public void OpenExisting()
{
string name = Guid.NewGuid().ToString("N");
Mutex resultHandle;
Assert.False(Mutex.TryOpenExisting(name, out resultHandle));
using (Mutex m1 = new Mutex(false, name))
{
using (Mutex m2 = Mutex.OpenExisting(name))
{
Assert.True(m1.WaitOne(FailedWaitTimeout));
Assert.False(Task.Factory.StartNew(() => m2.WaitOne(0), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).Result);
m1.ReleaseMutex();
Assert.True(m2.WaitOne(FailedWaitTimeout));
Assert.False(Task.Factory.StartNew(() => m1.WaitOne(0), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).Result);
m2.ReleaseMutex();
}
Assert.True(Mutex.TryOpenExisting(name, out resultHandle));
Assert.NotNull(resultHandle);
resultHandle.Dispose();
}
}
[Fact]
public void OpenExisting_InvalidNames()
{
AssertExtensions.Throws<ArgumentNullException>("name", () => Mutex.OpenExisting(null));
AssertExtensions.Throws<ArgumentException>("name", null, () => Mutex.OpenExisting(string.Empty));
AssertExtensions.Throws<ArgumentException>("name", null, () => Mutex.OpenExisting(new string('a', 10000)));
}
[Fact]
public void OpenExisting_UnavailableName()
{
string name = Guid.NewGuid().ToString("N");
Assert.Throws<WaitHandleCannotBeOpenedException>(() => Mutex.OpenExisting(name));
Mutex ignored;
Assert.False(Mutex.TryOpenExisting(name, out ignored));
}
[PlatformSpecific(TestPlatforms.Windows)] // named semaphores aren't supported on Unix
[Fact]
public void OpenExisting_NameUsedByOtherSynchronizationPrimitive_Windows()
{
string name = Guid.NewGuid().ToString("N");
using (Semaphore sema = new Semaphore(1, 1, name))
{
Assert.Throws<WaitHandleCannotBeOpenedException>(() => Mutex.OpenExisting(name));
Mutex ignored;
Assert.False(Mutex.TryOpenExisting(name, out ignored));
}
}
private static IEnumerable<string> GetNamePrefixes()
{
yield return string.Empty;
yield return "Local\\";
// Creating global sync objects is not allowed in UWP apps
if (!PlatformDetection.IsUap)
{
yield return "Global\\";
}
}
public static IEnumerable<object[]> AbandonExisting_MemberData()
{
var nameGuidStr = Guid.NewGuid().ToString("N");
for (int waitType = 0; waitType < 2; ++waitType) // 0 == WaitOne, 1 == WaitAny
{
yield return new object[] { null, waitType };
foreach (var namePrefix in GetNamePrefixes())
{
yield return new object[] { namePrefix + nameGuidStr, waitType };
}
}
}
[Theory]
[MemberData(nameof(AbandonExisting_MemberData))]
public void AbandonExisting(string name, int waitType)
{
ThreadTestHelpers.RunTestInBackgroundThread(() =>
{
using (var m = new Mutex(false, name))
{
Task t = Task.Factory.StartNew(() =>
{
Assert.True(m.WaitOne(FailedWaitTimeout));
// don't release the mutex; abandon it on this thread
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
Assert.True(t.Wait(FailedWaitTimeout));
switch (waitType)
{
case 0: // WaitOne
Assert.Throws<AbandonedMutexException>(() => m.WaitOne(FailedWaitTimeout));
break;
case 1: // WaitAny
AbandonedMutexException ame = Assert.Throws<AbandonedMutexException>(() => WaitHandle.WaitAny(new[] { m }, FailedWaitTimeout));
Assert.Equal(0, ame.MutexIndex);
Assert.Equal(m, ame.Mutex);
break;
}
}
});
}
public static IEnumerable<object[]> CrossProcess_NamedMutex_ProtectedFileAccessAtomic_MemberData()
{
var nameGuidStr = Guid.NewGuid().ToString("N");
foreach (var namePrefix in GetNamePrefixes())
{
yield return new object[] { namePrefix + nameGuidStr };
}
}
[Theory]
[MemberData(nameof(CrossProcess_NamedMutex_ProtectedFileAccessAtomic_MemberData))]
public void CrossProcess_NamedMutex_ProtectedFileAccessAtomic(string prefix)
{
ThreadTestHelpers.RunTestInBackgroundThread(() =>
{
string mutexName = prefix + Guid.NewGuid().ToString("N");
string fileName = GetTestFilePath();
Func<string, string, int> otherProcess = (m, f) =>
{
using (var mutex = Mutex.OpenExisting(m))
{
mutex.WaitOne();
try
{ File.WriteAllText(f, "0"); }
finally { mutex.ReleaseMutex(); }
IncrementValueInFileNTimes(mutex, f, 10);
}
return SuccessExitCode;
};
using (var mutex = new Mutex(false, mutexName))
using (var remote = RemoteInvoke(otherProcess, mutexName, fileName))
{
SpinWait.SpinUntil(() => File.Exists(fileName));
IncrementValueInFileNTimes(mutex, fileName, 10);
}
Assert.Equal(20, int.Parse(File.ReadAllText(fileName)));
});
}
private static void IncrementValueInFileNTimes(Mutex mutex, string fileName, int n)
{
for (int i = 0; i < n; i++)
{
mutex.WaitOne();
try
{
int current = int.Parse(File.ReadAllText(fileName));
Thread.Sleep(10);
File.WriteAllText(fileName, (current + 1).ToString());
}
finally { mutex.ReleaseMutex(); }
}
}
[DllImport("kernel32.dll")]
private static extern IntPtr GetCurrentThread();
[DllImport("advapi32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool ImpersonateAnonymousToken(IntPtr threadHandle);
[DllImport("advapi32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool RevertToSelf();
}
}
| |
// 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.Linq;
using global::System.Text;
using global::System.Reflection;
using global::System.Diagnostics;
using global::System.Collections;
using global::System.Collections.Generic;
using global::System.Reflection.Runtime.Assemblies;
using global::System.Reflection.Runtime.TypeParsing;
using global::Internal.Reflection.Core;
using global::Internal.Reflection.Core.NonPortable;
using global::Internal.Runtime.Augments;
using global::Internal.Metadata.NativeFormat;
namespace System.Reflection.Runtime.General
{
//
// Collect various metadata reading tasks for better chunking...
//
internal static class MetadataReaderExtensions
{
public static string GetString(this ConstantStringValueHandle handle, MetadataReader reader)
{
return reader.GetConstantStringValue(handle).Value;
}
// Useful for namespace Name string which can be a null handle.
public static String GetStringOrNull(this ConstantStringValueHandle handle, MetadataReader reader)
{
if (reader.IsNull(handle))
return null;
return reader.GetConstantStringValue(handle).Value;
}
public static bool StringOrNullEquals(this ConstantStringValueHandle handle, String valueOrNull, MetadataReader reader)
{
if (valueOrNull == null)
return handle.IsNull(reader);
if (handle.IsNull(reader))
return false;
return handle.StringEquals(valueOrNull, reader);
}
// Needed for RuntimeMappingTable access
public static int AsInt(this TypeDefinitionHandle typeDefinitionHandle)
{
unsafe
{
return *(int*)&typeDefinitionHandle;
}
}
public static TypeDefinitionHandle AsTypeDefinitionHandle(this int i)
{
unsafe
{
return *(TypeDefinitionHandle*)&i;
}
}
public static int AsInt(this MethodHandle methodHandle)
{
unsafe
{
return *(int*)&methodHandle;
}
}
public static MethodHandle AsMethodHandle(this int i)
{
unsafe
{
return *(MethodHandle*)&i;
}
}
public static int AsInt(this FieldHandle fieldHandle)
{
unsafe
{
return *(int*)&fieldHandle;
}
}
public static FieldHandle AsFieldHandle(this int i)
{
unsafe
{
return *(FieldHandle*)&i;
}
}
public static bool IsTypeDefRefOrSpecHandle(this Handle handle, MetadataReader reader)
{
HandleType handleType = handle.HandleType;
return handleType == HandleType.TypeDefinition ||
handleType == HandleType.TypeReference ||
handleType == HandleType.TypeSpecification;
}
public static bool IsNamespaceDefinitionHandle(this Handle handle, MetadataReader reader)
{
HandleType handleType = handle.HandleType;
return handleType == HandleType.NamespaceDefinition;
}
public static bool IsNamespaceReferenceHandle(this Handle handle, MetadataReader reader)
{
HandleType handleType = handle.HandleType;
return handleType == HandleType.NamespaceReference;
}
// Conversion where a invalid handle type indicates bad metadata rather a mistake by the caller.
public static ScopeReferenceHandle ToExpectedScopeReferenceHandle(this Handle handle, MetadataReader reader)
{
try
{
return handle.ToScopeReferenceHandle(reader);
}
catch (ArgumentException)
{
throw new BadImageFormatException();
}
}
// Conversion where a invalid handle type indicates bad metadata rather a mistake by the caller.
public static NamespaceReferenceHandle ToExpectedNamespaceReferenceHandle(this Handle handle, MetadataReader reader)
{
try
{
return handle.ToNamespaceReferenceHandle(reader);
}
catch (ArgumentException)
{
throw new BadImageFormatException();
}
}
// Conversion where a invalid handle type indicates bad metadata rather a mistake by the caller.
public static TypeDefinitionHandle ToExpectedTypeDefinitionHandle(this Handle handle, MetadataReader reader)
{
try
{
return handle.ToTypeDefinitionHandle(reader);
}
catch (ArgumentException)
{
throw new BadImageFormatException();
}
}
public static MethodSignature ParseMethodSignature(this Handle handle, MetadataReader reader)
{
return handle.ToMethodSignatureHandle(reader).GetMethodSignature(reader);
}
public static FieldSignature ParseFieldSignature(this Handle handle, MetadataReader reader)
{
return handle.ToFieldSignatureHandle(reader).GetFieldSignature(reader);
}
public static PropertySignature ParsePropertySignature(this Handle handle, MetadataReader reader)
{
return handle.ToPropertySignatureHandle(reader).GetPropertySignature(reader);
}
//
// Used to split methods between DeclaredMethods and DeclaredConstructors.
//
public static bool IsConstructor(this MethodHandle methodHandle, MetadataReader reader)
{
Method method = methodHandle.GetMethod(reader);
return IsConstructor(ref method, reader);
}
// This is specially designed for a hot path so we make some compromises in the signature:
//
// - "method" is passed by reference even though no side-effects are intended.
//
public static bool IsConstructor(ref Method method, MetadataReader reader)
{
if ((method.Flags & (MethodAttributes.RTSpecialName | MethodAttributes.SpecialName)) != (MethodAttributes.RTSpecialName | MethodAttributes.SpecialName))
return false;
ConstantStringValueHandle nameHandle = method.Name;
return nameHandle.StringEquals(ConstructorInfo.ConstructorName, reader) || nameHandle.StringEquals(ConstructorInfo.TypeConstructorName, reader);
}
private static Exception ParseBoxedEnumConstantValue(this ConstantBoxedEnumValueHandle handle, ReflectionDomain reflectionDomain, MetadataReader reader, out Object value)
{
if (!(reflectionDomain is Internal.Reflection.Core.Execution.ExecutionDomain))
throw new PlatformNotSupportedException(); // Cannot work because boxing enums won't work in non-execution domains.
ConstantBoxedEnumValue record = handle.GetConstantBoxedEnumValue(reader);
Exception exception = null;
Type enumType = reflectionDomain.TryResolve(reader, record.Type, new TypeContext(null, null), ref exception);
if (enumType == null)
{
value = null;
return exception;
}
if (!enumType.GetTypeInfo().IsEnum)
throw new BadImageFormatException();
Type underlyingType = Enum.GetUnderlyingType(enumType);
// Now box the value as the specified enum type.
unsafe
{
switch (record.Value.HandleType)
{
case HandleType.ConstantByteValue:
{
if (underlyingType != typeof(byte))
throw new BadImageFormatException();
byte v = record.Value.ToConstantByteValueHandle(reader).GetConstantByteValue(reader).Value;
value = RuntimeAugments.Box(enumType.TypeHandle, (IntPtr)(&v));
return null;
}
case HandleType.ConstantSByteValue:
{
if (underlyingType != typeof(sbyte))
throw new BadImageFormatException();
sbyte v = record.Value.ToConstantSByteValueHandle(reader).GetConstantSByteValue(reader).Value;
value = RuntimeAugments.Box(enumType.TypeHandle, (IntPtr)(&v));
return null;
}
case HandleType.ConstantInt16Value:
{
if (underlyingType != typeof(short))
throw new BadImageFormatException();
short v = record.Value.ToConstantInt16ValueHandle(reader).GetConstantInt16Value(reader).Value;
value = RuntimeAugments.Box(enumType.TypeHandle, (IntPtr)(&v));
return null;
}
case HandleType.ConstantUInt16Value:
{
if (underlyingType != typeof(ushort))
throw new BadImageFormatException();
ushort v = record.Value.ToConstantUInt16ValueHandle(reader).GetConstantUInt16Value(reader).Value;
value = RuntimeAugments.Box(enumType.TypeHandle, (IntPtr)(&v));
return null;
}
case HandleType.ConstantInt32Value:
{
if (underlyingType != typeof(int))
throw new BadImageFormatException();
int v = record.Value.ToConstantInt32ValueHandle(reader).GetConstantInt32Value(reader).Value;
value = RuntimeAugments.Box(enumType.TypeHandle, (IntPtr)(&v));
return null;
}
case HandleType.ConstantUInt32Value:
{
if (underlyingType != typeof(uint))
throw new BadImageFormatException();
uint v = record.Value.ToConstantUInt32ValueHandle(reader).GetConstantUInt32Value(reader).Value;
value = RuntimeAugments.Box(enumType.TypeHandle, (IntPtr)(&v));
return null;
}
case HandleType.ConstantInt64Value:
{
if (underlyingType != typeof(long))
throw new BadImageFormatException();
long v = record.Value.ToConstantInt64ValueHandle(reader).GetConstantInt64Value(reader).Value;
value = RuntimeAugments.Box(enumType.TypeHandle, (IntPtr)(&v));
return null;
}
case HandleType.ConstantUInt64Value:
{
if (underlyingType != typeof(ulong))
throw new BadImageFormatException();
ulong v = record.Value.ToConstantUInt64ValueHandle(reader).GetConstantUInt64Value(reader).Value;
value = RuntimeAugments.Box(enumType.TypeHandle, (IntPtr)(&v));
return null;
}
default:
throw new BadImageFormatException();
}
}
}
public static Object ParseConstantValue(this Handle handle, ReflectionDomain reflectionDomain, MetadataReader reader)
{
Object value;
Exception exception = handle.TryParseConstantValue(reflectionDomain, reader, out value);
if (exception != null)
throw exception;
return value;
}
public static Exception TryParseConstantValue(this Handle handle, ReflectionDomain reflectionDomain, MetadataReader reader, out Object value)
{
HandleType handleType = handle.HandleType;
switch (handleType)
{
case HandleType.ConstantBooleanValue:
value = handle.ToConstantBooleanValueHandle(reader).GetConstantBooleanValue(reader).Value;
return null;
case HandleType.ConstantStringValue:
value = handle.ToConstantStringValueHandle(reader).GetConstantStringValue(reader).Value;
return null;
case HandleType.ConstantCharValue:
value = handle.ToConstantCharValueHandle(reader).GetConstantCharValue(reader).Value;
return null;
case HandleType.ConstantByteValue:
value = handle.ToConstantByteValueHandle(reader).GetConstantByteValue(reader).Value;
return null;
case HandleType.ConstantSByteValue:
value = handle.ToConstantSByteValueHandle(reader).GetConstantSByteValue(reader).Value;
return null;
case HandleType.ConstantInt16Value:
value = handle.ToConstantInt16ValueHandle(reader).GetConstantInt16Value(reader).Value;
return null;
case HandleType.ConstantUInt16Value:
value = handle.ToConstantUInt16ValueHandle(reader).GetConstantUInt16Value(reader).Value;
return null;
case HandleType.ConstantInt32Value:
value = handle.ToConstantInt32ValueHandle(reader).GetConstantInt32Value(reader).Value;
return null;
case HandleType.ConstantUInt32Value:
value = handle.ToConstantUInt32ValueHandle(reader).GetConstantUInt32Value(reader).Value;
return null;
case HandleType.ConstantInt64Value:
value = handle.ToConstantInt64ValueHandle(reader).GetConstantInt64Value(reader).Value;
return null;
case HandleType.ConstantUInt64Value:
value = handle.ToConstantUInt64ValueHandle(reader).GetConstantUInt64Value(reader).Value;
return null;
case HandleType.ConstantSingleValue:
value = handle.ToConstantSingleValueHandle(reader).GetConstantSingleValue(reader).Value;
return null;
case HandleType.ConstantDoubleValue:
value = handle.ToConstantDoubleValueHandle(reader).GetConstantDoubleValue(reader).Value;
return null;
case HandleType.TypeDefinition:
case HandleType.TypeReference:
case HandleType.TypeSpecification:
{
Exception exception = null;
value = reflectionDomain.TryResolve(reader, handle, new TypeContext(null, null), ref exception);
return (value == null) ? exception : null;
}
case HandleType.ConstantReferenceValue:
value = null;
return null;
case HandleType.ConstantBoxedEnumValue:
{
return handle.ToConstantBoxedEnumValueHandle(reader).ParseBoxedEnumConstantValue(reflectionDomain, reader, out value);
}
default:
{
Exception exception;
value = handle.TryParseConstantArray(reflectionDomain, reader, out exception);
if (value == null)
return exception;
return null;
}
}
}
public static IEnumerable TryParseConstantArray(this Handle handle, ReflectionDomain reflectionDomain, MetadataReader reader, out Exception exception)
{
exception = null;
HandleType handleType = handle.HandleType;
switch (handleType)
{
case HandleType.ConstantBooleanArray:
return handle.ToConstantBooleanArrayHandle(reader).GetConstantBooleanArray(reader).Value;
case HandleType.ConstantStringArray:
return handle.ToConstantStringArrayHandle(reader).GetConstantStringArray(reader).Value;
case HandleType.ConstantCharArray:
return handle.ToConstantCharArrayHandle(reader).GetConstantCharArray(reader).Value;
case HandleType.ConstantByteArray:
return handle.ToConstantByteArrayHandle(reader).GetConstantByteArray(reader).Value;
case HandleType.ConstantSByteArray:
return handle.ToConstantSByteArrayHandle(reader).GetConstantSByteArray(reader).Value;
case HandleType.ConstantInt16Array:
return handle.ToConstantInt16ArrayHandle(reader).GetConstantInt16Array(reader).Value;
case HandleType.ConstantUInt16Array:
return handle.ToConstantUInt16ArrayHandle(reader).GetConstantUInt16Array(reader).Value;
case HandleType.ConstantInt32Array:
return handle.ToConstantInt32ArrayHandle(reader).GetConstantInt32Array(reader).Value;
case HandleType.ConstantUInt32Array:
return handle.ToConstantUInt32ArrayHandle(reader).GetConstantUInt32Array(reader).Value;
case HandleType.ConstantInt64Array:
return handle.ToConstantInt64ArrayHandle(reader).GetConstantInt64Array(reader).Value;
case HandleType.ConstantUInt64Array:
return handle.ToConstantUInt64ArrayHandle(reader).GetConstantUInt64Array(reader).Value;
case HandleType.ConstantSingleArray:
return handle.ToConstantSingleArrayHandle(reader).GetConstantSingleArray(reader).Value;
case HandleType.ConstantDoubleArray:
return handle.ToConstantDoubleArrayHandle(reader).GetConstantDoubleArray(reader).Value;
case HandleType.ConstantHandleArray:
{
Handle[] constantHandles = handle.ToConstantHandleArrayHandle(reader).GetConstantHandleArray(reader).Value.ToArray();
object[] elements = new object[constantHandles.Length];
for (int i = 0; i < constantHandles.Length; i++)
{
exception = constantHandles[i].TryParseConstantValue(reflectionDomain, reader, out elements[i]);
if (exception != null)
return null;
}
return elements;
}
default:
throw new BadImageFormatException();
}
}
public static Handle GetAttributeTypeHandle(this CustomAttribute customAttribute,
MetadataReader reader)
{
HandleType constructorHandleType = customAttribute.Constructor.HandleType;
if (constructorHandleType == HandleType.QualifiedMethod)
return customAttribute.Constructor.ToQualifiedMethodHandle(reader).GetQualifiedMethod(reader).EnclosingType;
else if (constructorHandleType == HandleType.MemberReference)
return customAttribute.Constructor.ToMemberReferenceHandle(reader).GetMemberReference(reader).Parent;
else
throw new BadImageFormatException();
}
//
// Lightweight check to see if a custom attribute's is of a well-known type.
//
// This check performs without instantating the Type object and bloating memory usage. On the flip side,
// it doesn't check on whether the type is defined in a paricular assembly. The desktop CLR typically doesn't
// check this either so this is useful from a compat persective as well.
//
public static bool IsCustomAttributeOfType(this CustomAttributeHandle customAttributeHandle,
MetadataReader reader,
String ns,
String name)
{
String[] namespaceParts = ns.Split('.');
Handle typeHandle = customAttributeHandle.GetCustomAttribute(reader).GetAttributeTypeHandle(reader);
HandleType handleType = typeHandle.HandleType;
if (handleType == HandleType.TypeDefinition)
{
TypeDefinition typeDefinition = typeHandle.ToTypeDefinitionHandle(reader).GetTypeDefinition(reader);
if (!typeDefinition.Name.StringEquals(name, reader))
return false;
NamespaceDefinitionHandle nsHandle = typeDefinition.NamespaceDefinition;
int idx = namespaceParts.Length;
while (idx-- != 0)
{
String namespacePart = namespaceParts[idx];
NamespaceDefinition namespaceDefinition = nsHandle.GetNamespaceDefinition(reader);
if (!namespaceDefinition.Name.StringOrNullEquals(namespacePart, reader))
return false;
if (!namespaceDefinition.ParentScopeOrNamespace.IsNamespaceDefinitionHandle(reader))
return false;
nsHandle = namespaceDefinition.ParentScopeOrNamespace.ToNamespaceDefinitionHandle(reader);
}
if (!nsHandle.GetNamespaceDefinition(reader).Name.StringOrNullEquals(null, reader))
return false;
return true;
}
else if (handleType == HandleType.TypeReference)
{
TypeReference typeReference = typeHandle.ToTypeReferenceHandle(reader).GetTypeReference(reader);
if (!typeReference.TypeName.StringEquals(name, reader))
return false;
if (!typeReference.ParentNamespaceOrType.IsNamespaceReferenceHandle(reader))
return false;
NamespaceReferenceHandle nsHandle = typeReference.ParentNamespaceOrType.ToNamespaceReferenceHandle(reader);
int idx = namespaceParts.Length;
while (idx-- != 0)
{
String namespacePart = namespaceParts[idx];
NamespaceReference namespaceReference = nsHandle.GetNamespaceReference(reader);
if (!namespaceReference.Name.StringOrNullEquals(namespacePart, reader))
return false;
if (!namespaceReference.ParentScopeOrNamespace.IsNamespaceReferenceHandle(reader))
return false;
nsHandle = namespaceReference.ParentScopeOrNamespace.ToNamespaceReferenceHandle(reader);
}
if (!nsHandle.GetNamespaceReference(reader).Name.StringOrNullEquals(null, reader))
return false;
return true;
}
else
throw new NotSupportedException();
}
public static String ToNamespaceName(this NamespaceDefinitionHandle namespaceDefinitionHandle, MetadataReader reader)
{
String ns = "";
for (; ;)
{
NamespaceDefinition currentNamespaceDefinition = namespaceDefinitionHandle.GetNamespaceDefinition(reader);
String name = currentNamespaceDefinition.Name.GetStringOrNull(reader);
if (name != null)
{
if (ns.Length != 0)
ns = "." + ns;
ns = name + ns;
}
Handle nextHandle = currentNamespaceDefinition.ParentScopeOrNamespace;
HandleType handleType = nextHandle.HandleType;
if (handleType == HandleType.ScopeDefinition)
break;
if (handleType == HandleType.NamespaceDefinition)
{
namespaceDefinitionHandle = nextHandle.ToNamespaceDefinitionHandle(reader);
continue;
}
throw new BadImageFormatException(SR.Bif_InvalidMetadata);
}
return ns;
}
public static IEnumerable<NamespaceDefinitionHandle> GetTransitiveNamespaces(this MetadataReader reader, IEnumerable<NamespaceDefinitionHandle> namespaceHandles)
{
foreach (NamespaceDefinitionHandle namespaceHandle in namespaceHandles)
{
yield return namespaceHandle;
NamespaceDefinition namespaceDefinition = namespaceHandle.GetNamespaceDefinition(reader);
foreach (NamespaceDefinitionHandle childNamespaceHandle in GetTransitiveNamespaces(reader, namespaceDefinition.NamespaceDefinitions))
yield return childNamespaceHandle;
}
}
public static IEnumerable<TypeDefinitionHandle> GetTopLevelTypes(this MetadataReader reader, IEnumerable<NamespaceDefinitionHandle> namespaceHandles)
{
foreach (NamespaceDefinitionHandle namespaceHandle in namespaceHandles)
{
NamespaceDefinition namespaceDefinition = namespaceHandle.GetNamespaceDefinition(reader);
foreach (TypeDefinitionHandle typeDefinitionHandle in namespaceDefinition.TypeDefinitions)
{
yield return typeDefinitionHandle;
}
}
}
public static IEnumerable<TypeDefinitionHandle> GetTransitiveTypes(this MetadataReader reader, IEnumerable<TypeDefinitionHandle> typeDefinitionHandles, bool publicOnly)
{
foreach (TypeDefinitionHandle typeDefinitionHandle in typeDefinitionHandles)
{
TypeDefinition typeDefinition = typeDefinitionHandle.GetTypeDefinition(reader);
if (publicOnly)
{
TypeAttributes visibility = typeDefinition.Flags & TypeAttributes.VisibilityMask;
if (visibility != TypeAttributes.Public && visibility != TypeAttributes.NestedPublic)
continue;
}
yield return typeDefinitionHandle;
foreach (TypeDefinitionHandle nestedTypeDefinitionHandle in GetTransitiveTypes(reader, typeDefinition.NestedTypes, publicOnly))
yield return nestedTypeDefinitionHandle;
}
}
public static AssemblyQualifiedTypeName ToAssemblyQualifiedTypeName(this NamespaceReferenceHandle namespaceReferenceHandle, String typeName, MetadataReader reader)
{
LowLevelList<String> namespaceParts = new LowLevelList<String>(8);
NamespaceReference namespaceReference;
for (; ;)
{
namespaceReference = namespaceReferenceHandle.GetNamespaceReference(reader);
String namespacePart = namespaceReference.Name.GetStringOrNull(reader);
if (namespacePart == null)
break;
namespaceParts.Add(namespacePart);
namespaceReferenceHandle = namespaceReference.ParentScopeOrNamespace.ToExpectedNamespaceReferenceHandle(reader);
}
ScopeReferenceHandle scopeReferenceHandle = namespaceReference.ParentScopeOrNamespace.ToExpectedScopeReferenceHandle(reader);
RuntimeAssemblyName assemblyName = scopeReferenceHandle.ToRuntimeAssemblyName(reader);
return new AssemblyQualifiedTypeName(new NamespaceTypeName(namespaceParts.ToArray(), typeName), assemblyName);
}
public static RuntimeAssemblyName ToRuntimeAssemblyName(this ScopeDefinitionHandle scopeDefinitionHandle, MetadataReader reader)
{
ScopeDefinition scopeDefinition = scopeDefinitionHandle.GetScopeDefinition(reader);
return CreateRuntimeAssemblyNameFromMetadata(
reader,
scopeDefinition.Name,
scopeDefinition.MajorVersion,
scopeDefinition.MinorVersion,
scopeDefinition.BuildNumber,
scopeDefinition.RevisionNumber,
scopeDefinition.Culture,
scopeDefinition.PublicKey,
scopeDefinition.Flags
);
}
public static RuntimeAssemblyName ToRuntimeAssemblyName(this ScopeReferenceHandle scopeReferenceHandle, MetadataReader reader)
{
ScopeReference scopeReference = scopeReferenceHandle.GetScopeReference(reader);
return CreateRuntimeAssemblyNameFromMetadata(
reader,
scopeReference.Name,
scopeReference.MajorVersion,
scopeReference.MinorVersion,
scopeReference.BuildNumber,
scopeReference.RevisionNumber,
scopeReference.Culture,
scopeReference.PublicKeyOrToken,
scopeReference.Flags
);
}
private static RuntimeAssemblyName CreateRuntimeAssemblyNameFromMetadata(
MetadataReader reader,
ConstantStringValueHandle name,
ushort majorVersion,
ushort minorVersion,
ushort buildNumber,
ushort revisionNumber,
ConstantStringValueHandle culture,
IEnumerable<byte> publicKeyOrToken,
AssemblyFlags assemblyFlags)
{
AssemblyNameFlags assemblyNameFlags = AssemblyNameFlags.None;
if (0 != (assemblyFlags & AssemblyFlags.PublicKey))
assemblyNameFlags |= AssemblyNameFlags.PublicKey;
if (0 != (assemblyFlags & AssemblyFlags.Retargetable))
assemblyNameFlags |= AssemblyNameFlags.Retargetable;
int contentType = ((int)assemblyFlags) & 0x00000E00;
assemblyNameFlags |= (AssemblyNameFlags)contentType;
return new RuntimeAssemblyName(
name.GetString(reader),
new Version(majorVersion, minorVersion, buildNumber, revisionNumber),
culture.GetStringOrNull(reader),
assemblyNameFlags,
publicKeyOrToken.ToArray()
);
}
}
}
| |
using System;
using System.Xml;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Diagnostics;
namespace SharpVectors.Dom.Svg
{
public class SvgPathElement : SvgTransformableElement, ISvgPathElement, ISharpGDIPath, ISharpMarkerHost, IGraphicsElement
{
#region Constructors
internal SvgPathElement(string prefix, string localname, string ns, SvgDocument doc) : base(prefix, localname, ns, doc)
{
svgTests = new SvgTests(this);
}
#endregion
#region Implementation of ISharpMarkerHost
public PointF[] MarkerPositions
{
get
{
return ((SvgPathSegList)PathSegList).Points;
}
}
public float GetStartAngle(int index)
{
return ((SvgPathSegList)PathSegList).GetStartAngle(index);
}
public float GetEndAngle(int index)
{
return ((SvgPathSegList)PathSegList).GetEndAngle(index);
}
#endregion
#region Implementation of ISharpGDIPath
public void Invalidate()
{
}
private GraphicsPath gp = null;
public GraphicsPath GetGraphicsPath()
{
if(gp == null)
{
gp = new GraphicsPath();
PointF initPoint = new PointF(0, 0);
PointF lastPoint = new PointF(0,0);
SvgPathSegList segments = (SvgPathSegList)PathSegList;
SvgPathSeg segment;
int nElems = segments.NumberOfItems;
for(int i = 0; i<nElems; i++)
{
segment = (SvgPathSeg) segments.GetItem(i);
if(segment is SvgPathSegMoveto)
{
SvgPathSegMoveto seg = (SvgPathSegMoveto) segment;
gp.StartFigure();
lastPoint = initPoint = seg.AbsXY;
}
else if(segment is SvgPathSegLineto)
{
SvgPathSegLineto seg = (SvgPathSegLineto) segment;
PointF p = seg.AbsXY;
gp.AddLine(lastPoint.X, lastPoint.Y, p.X, p.Y);
lastPoint = p;
}
else if(segment is SvgPathSegCurveto)
{
SvgPathSegCurveto seg = (SvgPathSegCurveto)segment;
PointF xy = seg.AbsXY;
PointF x1y1 = seg.CubicX1Y1;
PointF x2y2 = seg.CubicX2Y2;
gp.AddBezier(lastPoint.X, lastPoint.Y, x1y1.X, x1y1.Y, x2y2.X, x2y2.Y, xy.X, xy.Y);
lastPoint = xy;
}
else if(segment is SvgPathSegArc)
{
SvgPathSegArc seg = (SvgPathSegArc)segment;
PointF p = seg.AbsXY;
if (lastPoint.Equals(p))
{
// If the endpoints (x, y) and (x0, y0) are identical, then this
// is equivalent to omitting the elliptical arc segment entirely.
}
else if (seg.R1 == 0 || seg.R2 == 0)
{
// Ensure radii are valid
gp.AddLine(lastPoint, p);
}
else
{
CalculatedArcValues calcValues = seg.GetCalculatedArcValues();
GraphicsPath gp2 = new GraphicsPath();
gp2.StartFigure();
gp2.AddArc(
calcValues.Cx - calcValues.CorrRx,
calcValues.Cy - calcValues.CorrRy,
calcValues.CorrRx*2,
calcValues.CorrRy*2,
calcValues.AngleStart,
calcValues.AngleExtent
);
Matrix matrix = new Matrix();
matrix.Translate(
-calcValues.Cx,
-calcValues.Cy
);
gp2.Transform(matrix);
matrix = new Matrix();
matrix.Rotate(seg.Angle);
gp2.Transform(matrix);
matrix = new Matrix();
matrix.Translate(calcValues.Cx, calcValues.Cy);
gp2.Transform(matrix);
gp.AddPath(gp2, true);
}
lastPoint = p;
}
else if(segment is SvgPathSegClosePath)
{
gp.CloseFigure();
lastPoint = initPoint;
}
}
string fillRule = GetPropertyValue("fill-rule");
if(fillRule == "evenodd") gp.FillMode = FillMode.Alternate;
else gp.FillMode = FillMode.Winding;
}
return gp;
}
#endregion
#region Implementation of ISvgPathElement
public ISvgAnimatedBoolean ExternalResourcesRequired
{
get
{
throw new NotImplementedException();
}
}
private ISvgPathSegList pathSegList;
public ISvgPathSegList PathSegList
{
get{
if(pathSegList == null)
{
pathSegList = new SvgPathSegList(this.GetAttribute("d"), false);
}
return pathSegList;
}
}
public ISvgPathSegList NormalizedPathSegList
{
get{throw new NotImplementedException();}
}
public ISvgPathSegList AnimatedPathSegList
{
get{return PathSegList;}
}
public ISvgPathSegList AnimatedNormalizedPathSegList
{
get{return NormalizedPathSegList;}
}
private ISvgAnimatedNumber _pathLength;
public ISvgAnimatedNumber PathLength
{
get
{
if(_pathLength == null)
{
_pathLength = new SvgAnimatedNumber(GetAttribute("pathLength"));
}
return _pathLength;
}
}
public float GetTotalLength()
{
return ((SvgPathSegList)PathSegList).GetTotalLength();
}
public ISvgPoint GetPointAtLength(float distance)
{
throw new NotImplementedException();
}
public int GetPathSegAtLength(float distance)
{
return ((SvgPathSegList)PathSegList).GetPathSegAtLength(distance);
}
#region Create methods
public ISvgPathSegClosePath CreateSvgPathSegClosePath()
{
return new SvgPathSegClosePath();
}
public ISvgPathSegMovetoAbs CreateSvgPathSegMovetoAbs(float x, float y)
{
return new SvgPathSegMovetoAbs(x, y);
}
public ISvgPathSegMovetoRel CreateSvgPathSegMovetoRel(float x, float y)
{
return new SvgPathSegMovetoRel(x, y);
}
public ISvgPathSegLinetoAbs CreateSvgPathSegLinetoAbs(float x, float y)
{
return new SvgPathSegLinetoAbs(x, y);
}
public ISvgPathSegLinetoRel CreateSvgPathSegLinetoRel(float x, float y)
{
return new SvgPathSegLinetoRel(x, y);
}
public ISvgPathSegCurvetoCubicAbs CreateSvgPathSegCurvetoCubicAbs(float x,
float y,
float x1,
float y1,
float x2,
float y2)
{
return new SvgPathSegCurvetoCubicAbs(x, y, x1, y1, x2, y2);
}
public ISvgPathSegCurvetoCubicRel CreateSvgPathSegCurvetoCubicRel(float x,
float y,
float x1,
float y1,
float x2,
float y2)
{
return new SvgPathSegCurvetoCubicRel(x, y, x1, y1, x2, y2);
}
public ISvgPathSegCurvetoQuadraticAbs CreateSvgPathSegCurvetoQuadraticAbs(float x,
float y,
float x1,
float y1)
{
return new SvgPathSegCurvetoQuadraticAbs(x, y, x1, y1);
}
public ISvgPathSegCurvetoQuadraticRel CreateSvgPathSegCurvetoQuadraticRel(float x,
float y,
float x1,
float y1)
{
return new SvgPathSegCurvetoQuadraticRel(x, y, x1, y1);
}
public ISvgPathSegArcAbs CreateSvgPathSegArcAbs(float x,
float y,
float r1,
float r2,
float angle,
bool largeArcFlag,
bool sweepFlag)
{
return new SvgPathSegArcAbs(x, y, r1, r2, angle, largeArcFlag, sweepFlag);
}
public ISvgPathSegArcRel CreateSvgPathSegArcRel(float x,
float y,
float r1,
float r2,
float angle,
bool largeArcFlag,
bool sweepFlag)
{
return new SvgPathSegArcRel(x, y, r1, r2, angle, largeArcFlag, sweepFlag);
}
public ISvgPathSegLinetoHorizontalAbs CreateSvgPathSegLinetoHorizontalAbs(float x)
{
return new SvgPathSegLinetoHorizontalAbs(x);
}
public ISvgPathSegLinetoHorizontalRel CreateSvgPathSegLinetoHorizontalRel(float x)
{
return new SvgPathSegLinetoHorizontalRel(x);
}
public ISvgPathSegLinetoVerticalAbs CreateSvgPathSegLinetoVerticalAbs(float y)
{
return new SvgPathSegLinetoVerticalAbs(y);
}
public ISvgPathSegLinetoVerticalRel CreateSvgPathSegLinetoVerticalRel(float y)
{
return new SvgPathSegLinetoVerticalRel(y);
}
public ISvgPathSegCurvetoCubicSmoothAbs CreateSvgPathSegCurvetoCubicSmoothAbs(float x,
float y,
float x2,
float y2)
{
return new SvgPathSegCurvetoCubicSmoothAbs(x, y, x2, y2);
}
public ISvgPathSegCurvetoCubicSmoothRel CreateSvgPathSegCurvetoCubicSmoothRel(float x,
float y,
float x2,
float y2)
{
return new SvgPathSegCurvetoCubicSmoothRel(x, y, x2, y2);
}
public ISvgPathSegCurvetoQuadraticSmoothAbs CreateSvgPathSegCurvetoQuadraticSmoothAbs(float x,
float y)
{
return new SvgPathSegCurvetoQuadraticSmoothAbs(x, y);
}
public ISvgPathSegCurvetoQuadraticSmoothRel CreateSvgPathSegCurvetoQuadraticSmoothRel(float x,
float y)
{
return new SvgPathSegCurvetoQuadraticSmoothRel(x, y);
}
#endregion
#endregion
#region Implementation of ISvgTests
private SvgTests svgTests;
public ISvgStringList RequiredFeatures
{
get { return svgTests.RequiredFeatures; }
}
public ISvgStringList RequiredExtensions
{
get { return svgTests.RequiredExtensions; }
}
public ISvgStringList SystemLanguage
{
get { return svgTests.SystemLanguage; }
}
public bool HasExtension(string extension)
{
return svgTests.HasExtension(extension);
}
#endregion
#region Update handling
public override void HandleAttributeChange(XmlAttribute attribute)
{
if(attribute.NamespaceURI.Length == 0)
{
switch(attribute.LocalName)
{
case "d":
pathSegList = null;
Invalidate();
return;
case "pathLength":
_pathLength = null;
Invalidate();
return;
case "marker-start":
case "marker-mid":
case "marker-end":
// Color.attrib, Paint.attrib
case "color":
case "fill":
case "fill-rule":
case "stroke":
case "stroke-dasharray":
case "stroke-dashoffset":
case "stroke-linecap":
case "stroke-linejoin":
case "stroke-miterlimit":
case "stroke-width":
// Opacity.attrib
case "opacity":
case "stroke-opacity":
case "fill-opacity":
// Graphics.attrib
case "display":
case "image-rendering":
case "shape-rendering":
case "text-rendering":
case "visibility":
Invalidate();
break;
case "transform":
Invalidate();
break;
}
base.HandleAttributeChange(attribute);
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Foundation;
using System.Linq;
namespace iOSHelpers
{
public static class BackgroundDownloadManager
{
public static string BaseDir = Directory.GetParent (Environment.GetFolderPath (Environment.SpecialFolder.Personal)).ToString ();
public class CompletedArgs : EventArgs
{
public BackgroundDownloadFile File { get; set; }
}
public static event EventHandler<CompletedArgs> FileCompleted;
static Dictionary<string, BackgroundDownloadFile> files;
internal static Dictionary<string, BackgroundDownloadFile> Files {
get {
if (files == null)
loadState ();
return files;
}
set {
files = value;
}
}
private static string stateFile = Path.Combine (System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal), "downloaderState");
public static Action<Dictionary<string,BackgroundDownloadFile>> SaveState { get; set; }
public static Func<Dictionary<string,BackgroundDownloadFile>> LoadState { get; set; }
static BackgroundDownloadManager()
{
try{
loadState();
}
catch(Exception ex) {
Console.WriteLine (ex);
Files = new Dictionary<string,BackgroundDownloadFile> ();
}
}
public static bool RemoveCompletedAutomatically { get; set; }
public static void RemoveCompleted()
{
var completed = BackgroundDownloadManager.CurrentDownloads.Where (x => x.Status == BackgroundDownloadManager.BackgroundDownloadFile.FileStatus.Completed).ToList ();
completed.ForEach(x=> Remove(x.Url));
}
public static void Reload ()
{
loadState ();
}
private static void loadState()
{
lock (locker) {
if (LoadState != null) {
try {
LoadState ();
return;
} catch (Exception e) {
Console.WriteLine (e);
}
}
if (!File.Exists (stateFile)) {
Files = new Dictionary<string,BackgroundDownloadFile> ();
return;
}
var formatter = new BinaryFormatter ();
using (var stream = new FileStream (stateFile, FileMode.Open, FileAccess.Read, FileShare.Read)) {
Files = (Dictionary<string,BackgroundDownloadFile>)formatter.Deserialize (stream);
stream.Close ();
}
}
}
private static void saveState()
{
lock (locker) {
if(SaveState != null)
{
try{
SaveState(Files);
return;
}
catch (Exception e){
Console.WriteLine(e);
}
}
var formatter = new BinaryFormatter ();
using (var stream = new FileStream (stateFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
formatter.Serialize (stream, Files);
stream.Close ();
}
}
}
[Serializable]
public class BackgroundDownloadFile
{
public string SessionId { get; set; }
public string Url { get; set; }
public string Destination { get; set; }
public float Percent { get; set; }
public string Error { get; internal set; }
public string TempLocation {get;set;}
public FileStatus Status {get;set;}
public enum FileStatus{
Downloading,
Completed,
Error,
Canceled,
Temporary,
}
public override string ToString ()
{
return string.Format ("[BackgroundDownloadFile: Url={0}, Destination={1}, Percent={2}, Error={3}, Status={4}]", Url, Destination, Percent, Error, Status);
}
}
static object locker = new object();
internal static Dictionary<string,TaskCompletionSource<bool> > Tasks = new Dictionary<string, TaskCompletionSource<bool> >();
static Dictionary<string,List<BackgroundDownload> > Controllers = new Dictionary<string, List<BackgroundDownload>>();
static Dictionary<string,NSUrlSessionDownloadTask> DownloadTasks = new Dictionary<string, NSUrlSessionDownloadTask>();
public static BackgroundDownloadFile[] CurrentDownloads
{
get{ return Files.Values.ToArray (); }
}
static List<BackgroundDownload> GetControllers(string url)
{
List<BackgroundDownload> list;
lock (locker)
if (!Controllers.TryGetValue (url, out list)) {
Controllers.Add (url, list = new List<BackgroundDownload> ());
if(!Tasks.ContainsKey(url))
Tasks.Add (url, new TaskCompletionSource<bool>());
}
return list;
}
public static BackgroundDownload Download(string url, string destination)
{
return Download (new Uri (url), destination);
}
public static BackgroundDownload Download(Uri url, string destination)
{
var download = new BackgroundDownload ();
//We dont want to await this. Just get it started
#pragma warning disable 4014
download.DownloadFileAsync (url, destination);
#pragma warning restore 4014
return download;
}
public static Action<BackgroundDownloadFile> DownloadError {get;set;}
public static void Errored(NSUrlSessionDownloadTask downloadTask)
{
BackgroundDownloadFile download;
var url = downloadTask.OriginalRequest.Url.AbsoluteString;
if (!Files.TryGetValue (url, out download))
return;
if (DownloadError != null)
DownloadError (download);
RemoveUrl (url);
}
internal static void AddController(string url, BackgroundDownload controller)
{
lock (locker) {
var list = GetControllers (url) ?? new List<BackgroundDownload>();
list.Add (controller);
}
BackgroundDownloadFile file;
if (!Files.TryGetValue (url, out file)) {
Console.WriteLine ("Adding URL {0}", url);
Files [url] = file = new BackgroundDownloadFile {
Destination = MakeRelativePath(BaseDir, controller.Destination),
Url = url,
SessionId = controller.SessionId
};
}
saveState ();
}
public static String MakeRelativePath(String fromPath, String toPath)
{
return toPath.Replace (fromPath, "");
}
static void RemoveUrl(string url)
{
lock (locker) {
if (Controllers.ContainsKey (url)) {
Controllers [url] = null;
Controllers.Remove (url);
}
if (DownloadTasks.ContainsKey (url)) {
DownloadTasks [url] = null;
DownloadTasks.Remove (url);
}
if(Tasks.ContainsKey(url))
Tasks.Remove (url);
}
}
internal static void UpdateProgress(NSUrlSessionDownloadTask downloadTask, nfloat progress)
{
try{
var url = downloadTask.OriginalRequest.Url.AbsoluteString;
DownloadTasks [url] = downloadTask;
UpdateProgress (url, progress);
Files[url].Percent = (float)progress;
}
catch(Exception ex) {
Console.WriteLine (ex);
}
}
internal static void UpdateProgress(string url, nfloat progress)
{
var controllers = BackgroundDownloadManager.GetControllers (url);
controllers.ForEach (x => Device.EnsureInvokedOnMainThread (() => x.Progress = progress));
}
public static void Remove(string url)
{
Console.WriteLine ("Removing URL: {0}", url);
BackgroundDownloadFile file;
if (Files.TryGetValue (url,out file)) {
if (file.Status == BackgroundDownloadFile.FileStatus.Downloading)
Cancel (url);
}
Files.Remove (url);
saveState ();
}
public static void Cancel(string url)
{
NSUrlSessionDownloadTask task;
if (DownloadTasks.TryGetValue (url, out task) && task != null) {
task.Cancel ();
}
BackgroundDownloadFile file;
if (Files.TryGetValue (url,out file)) {
file.Status = BackgroundDownloadFile.FileStatus.Canceled;
}
RemoveUrl (url);
}
public static bool AutoProcess = true;
public static void Completed(NSUrlSessionTask downloadTask,NSUrl location)
{
NSFileManager fileManager = NSFileManager.DefaultManager;
var url = downloadTask.OriginalRequest.Url.AbsoluteString;
Console.WriteLine ("Looking for: {0}",url);
NSError errorCopy = null;
foreach (var f in Files) {
Console.WriteLine ("Existing file: {0}", f.Key);
}
if(Files.ContainsKey(url))
{
var file = Files [url];
file.Status = BackgroundDownloadFile.FileStatus.Temporary;
file.Percent = 1;
if (!AutoProcess) {
var sharedFolder = fileManager.GetContainerUrl (BackgroundDownload.SharedContainerIdentifier);
fileManager.CreateDirectory (sharedFolder, true, null,out errorCopy);
var fileName = Path.GetFileName (file.Destination);
var newTemp = Path.Combine (sharedFolder.RelativePath,fileName);
var success1 = fileManager.Copy (location, NSUrl.FromFilename(newTemp), out errorCopy);
Console.WriteLine ("Success: {0} {1}", success1,errorCopy);
file.TempLocation = fileName;
saveState ();
return;
}
NSUrl originalURL = downloadTask.OriginalRequest.Url;
var dest = Path.Combine (BaseDir + file.Destination);
NSUrl destinationURL = NSUrl.FromFilename (dest);
NSError removeCopy;
fileManager.Remove (destinationURL, out removeCopy);
Console.WriteLine ("Trying to copy to {0}", dest);
var success = fileManager.Copy (location, destinationURL, out errorCopy);
if (success)
file.Status = BackgroundDownloadFile.FileStatus.Completed;
Console.WriteLine ("Success: {0} {1}", success,errorCopy);
}
else
Console.WriteLine ("Could not find the file!");
TaskCompletionSource<bool> t;
if (Tasks.TryGetValue (url, out t)) {
if (errorCopy == null) {
if (!t.TrySetResult (true))
Console.WriteLine ("ERROR");
} else {
var file = Files [url];
file.Status = BackgroundDownloadFile.FileStatus.Error;
file.Error = string.Format("Error during the copy: {0}", errorCopy.LocalizedDescription);
t.TrySetException (new Exception (file.Error));
}
BackgroundDownloadManager.Tasks.Remove (url);
}
RemoveUrl (url);
saveState ();
Console.WriteLine ("Tasks: {0}, Downloads {1}, Controllers {2} ", Tasks.Count, DownloadTasks.Count, Controllers.Count);
foreach (var f in Files) {
Console.WriteLine (f);
}
var evt = FileCompleted;
if (evt != null)
evt (downloadTask, new CompletedArgs{ File = Files [url]});
if (RemoveCompletedAutomatically)
Remove (url);
}
public static void Failed(NSUrlSession session, NSUrlSessionTask task, NSError error)
{
if (error != null)
Console.WriteLine (error.LocalizedDescription);
nfloat progress = task.BytesReceived / (nfloat)task.BytesExpectedToReceive;
var url = task.OriginalRequest.Url.AbsoluteString;
DownloadTasks.Remove (url);
UpdateProgress (url, progress);
TaskCompletionSource<bool> t;
if (BackgroundDownloadManager.Tasks.TryGetValue (task.OriginalRequest.Url.AbsoluteString, out t)) {
if (error == null) {
if (!t.TrySetResult (true))
Console.WriteLine ("ERROR");
} else {
t.TrySetException (new Exception (string.Format ("Error during the copy: {0}", error.LocalizedDescription)));
}
BackgroundDownloadManager.Tasks.Remove (task.OriginalRequest.Url.AbsoluteString);
}
RemoveUrl (url);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime;
using System.Runtime.CompilerServices;
using EditorBrowsableState = System.ComponentModel.EditorBrowsableState;
using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute;
#pragma warning disable 0809 //warning CS0809: Obsolete member 'Span<T>.Equals(object)' overrides non-obsolete member 'object.Equals(object)'
#if BIT64
using nuint = System.UInt64;
#else
using nuint = System.UInt32;
#endif
namespace System
{
/// <summary>
/// Span represents a contiguous region of arbitrary memory. Unlike arrays, it can point to either managed
/// or native memory, or to memory allocated on the stack. It is type- and memory-safe.
/// </summary>
[IsByRefLike]
public struct Span<T>
{
/// <summary>A byref or a native ptr.</summary>
private readonly ByReference<T> _pointer;
/// <summary>The number of elements this Span contains.</summary>
#if PROJECTN
[Bound]
#endif
private readonly int _length;
/// <summary>
/// Creates a new span over the entirety of the target array.
/// </summary>
/// <param name="array">The target array.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
/// reference (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span(T[] array)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if (default(T) == null && array.GetType() != typeof(T[]))
ThrowHelper.ThrowArrayTypeMismatchException();
_pointer = new ByReference<T>(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData()));
_length = array.Length;
}
/// <summary>
/// Creates a new span over the portion of the target array beginning
/// at 'start' index and covering the remainder of the array.
/// </summary>
/// <param name="array">The target array.</param>
/// <param name="start">The index at which to begin the span.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
/// reference (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> is not in the range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span(T[] array, int start)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if (default(T) == null && array.GetType() != typeof(T[]))
ThrowHelper.ThrowArrayTypeMismatchException();
if ((uint)start > (uint)array.Length)
ThrowHelper.ThrowArgumentOutOfRangeException();
_pointer = new ByReference<T>(ref Unsafe.Add(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData()), start));
_length = array.Length - start;
}
/// <summary>
/// Creates a new span over the portion of the target array beginning
/// at 'start' index and ending at 'end' index (exclusive).
/// </summary>
/// <param name="array">The target array.</param>
/// <param name="start">The index at which to begin the span.</param>
/// <param name="length">The number of items in the span.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
/// reference (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span(T[] array, int start, int length)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if (default(T) == null && array.GetType() != typeof(T[]))
ThrowHelper.ThrowArrayTypeMismatchException();
if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
ThrowHelper.ThrowArgumentOutOfRangeException();
_pointer = new ByReference<T>(ref Unsafe.Add(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData()), start));
_length = length;
}
/// <summary>
/// Creates a new span over the target unmanaged buffer. Clearly this
/// is quite dangerous, because we are creating arbitrarily typed T's
/// out of a void*-typed block of memory. And the length is not checked.
/// But if this creation is correct, then all subsequent uses are correct.
/// </summary>
/// <param name="pointer">An unmanaged pointer to memory.</param>
/// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when <typeparamref name="T"/> is reference type or contains pointers and hence cannot be stored in unmanaged memory.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="length"/> is negative.
/// </exception>
[CLSCompliant(false)]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe Span(void* pointer, int length)
{
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T));
if (length < 0)
ThrowHelper.ThrowArgumentOutOfRangeException();
_pointer = new ByReference<T>(ref Unsafe.As<byte, T>(ref *(byte*)pointer));
_length = length;
}
/// <summary>
/// Create a new span over a portion of a regular managed object. This can be useful
/// if part of a managed object represents a "fixed array." This is dangerous because neither the
/// <paramref name="length"/> is checked, nor <paramref name="obj"/> being null, nor the fact that
/// "rawPointer" actually lies within <paramref name="obj"/>.
/// </summary>
/// <param name="obj">The managed object that contains the data to span over.</param>
/// <param name="objectData">A reference to data within that object.</param>
/// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Span<T> DangerousCreate(object obj, ref T objectData, int length) => new Span<T>(ref objectData, length);
// Constructor for internal use only.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Span(ref T ptr, int length)
{
Debug.Assert(length >= 0);
_pointer = new ByReference<T>(ref ptr);
_length = length;
}
/// <summary>
/// Returns a reference to the 0th element of the Span. If the Span is empty, returns a reference to the location where the 0th element
/// would have been stored. Such a reference can be used for pinning but must never be dereferenced.
/// </summary>
public ref T DangerousGetPinnableReference()
{
return ref _pointer.Value;
}
/// <summary>
/// The number of items in the span.
/// </summary>
public int Length => _length;
/// <summary>
/// Returns true if Length is 0.
/// </summary>
public bool IsEmpty => _length == 0;
/// <summary>
/// Returns a reference to specified element of the Span.
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
/// <exception cref="System.IndexOutOfRangeException">
/// Thrown when index less than 0 or index greater than or equal to Length
/// </exception>
public ref T this[int index]
{
#if PROJECTN
[BoundsChecking]
get
{
return ref Unsafe.Add(ref _pointer.Value, index);
}
#else
#if CORERT
[Intrinsic]
#endif
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if ((uint)index >= (uint)_length)
ThrowHelper.ThrowIndexOutOfRangeException();
return ref Unsafe.Add(ref _pointer.Value, index);
}
#endif
}
/// <summary>
/// Clears the contents of this span.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Clear()
{
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
Span.ClearWithReferences(ref Unsafe.As<T, IntPtr>(ref _pointer.Value), (nuint)_length * (nuint)(Unsafe.SizeOf<T>() / sizeof(nuint)));
}
else
{
Span.ClearWithoutReferences(ref Unsafe.As<T, byte>(ref _pointer.Value), (nuint)_length * (nuint)Unsafe.SizeOf<T>());
}
}
/// <summary>
/// Fills the contents of this span with the given value.
/// </summary>
public void Fill(T value)
{
if (Unsafe.SizeOf<T>() == 1)
{
uint length = (uint)_length;
if (length == 0)
return;
T tmp = value; // Avoid taking address of the "value" argument. It would regress performance of the loop below.
Unsafe.InitBlockUnaligned(ref Unsafe.As<T, byte>(ref _pointer.Value), Unsafe.As<T, byte>(ref tmp), length);
}
else
{
// Do all math as nuint to avoid unnecessary 64->32->64 bit integer truncations
nuint length = (uint)_length;
if (length == 0)
return;
ref T r = ref DangerousGetPinnableReference();
// TODO: Create block fill for value types of power of two sizes e.g. 2,4,8,16
nuint elementSize = (uint)Unsafe.SizeOf<T>();
nuint i = 0;
for (; i < (length & ~(nuint)7); i += 8)
{
Unsafe.AddByteOffset<T>(ref r, (i + 0) * elementSize) = value;
Unsafe.AddByteOffset<T>(ref r, (i + 1) * elementSize) = value;
Unsafe.AddByteOffset<T>(ref r, (i + 2) * elementSize) = value;
Unsafe.AddByteOffset<T>(ref r, (i + 3) * elementSize) = value;
Unsafe.AddByteOffset<T>(ref r, (i + 4) * elementSize) = value;
Unsafe.AddByteOffset<T>(ref r, (i + 5) * elementSize) = value;
Unsafe.AddByteOffset<T>(ref r, (i + 6) * elementSize) = value;
Unsafe.AddByteOffset<T>(ref r, (i + 7) * elementSize) = value;
}
if (i < (length & ~(nuint)3))
{
Unsafe.AddByteOffset<T>(ref r, (i + 0) * elementSize) = value;
Unsafe.AddByteOffset<T>(ref r, (i + 1) * elementSize) = value;
Unsafe.AddByteOffset<T>(ref r, (i + 2) * elementSize) = value;
Unsafe.AddByteOffset<T>(ref r, (i + 3) * elementSize) = value;
i += 4;
}
for (; i < length; i++)
{
Unsafe.AddByteOffset<T>(ref r, i * elementSize) = value;
}
}
}
/// <summary>
/// Copies the contents of this span into destination span. If the source
/// and destinations overlap, this method behaves as if the original values in
/// a temporary location before the destination is overwritten.
/// </summary>
/// <param name="destination">The span to copy items into.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when the destination Span is shorter than the source Span.
/// </exception>
public void CopyTo(Span<T> destination)
{
if (!TryCopyTo(destination))
ThrowHelper.ThrowArgumentException_DestinationTooShort();
}
/// <summary>
/// Copies the contents of this span into destination span. If the source
/// and destinations overlap, this method behaves as if the original values in
/// a temporary location before the destination is overwritten.
/// </summary>
/// <param name="destination">The span to copy items into.</param>
/// <returns>If the destination span is shorter than the source span, this method
/// return false and no data is written to the destination.</returns>
public bool TryCopyTo(Span<T> destination)
{
if ((uint)_length > (uint)destination.Length)
return false;
Span.CopyTo<T>(ref destination._pointer.Value, ref _pointer.Value, _length);
return true;
}
/// <summary>
/// Returns true if left and right point at the same memory and have the same length. Note that
/// this does *not* check to see if the *contents* are equal.
/// </summary>
public static bool operator ==(Span<T> left, Span<T> right)
{
return left._length == right._length && Unsafe.AreSame<T>(ref left._pointer.Value, ref right._pointer.Value);
}
/// <summary>
/// Returns false if left and right point at the same memory and have the same length. Note that
/// this does *not* check to see if the *contents* are equal.
/// </summary>
public static bool operator !=(Span<T> left, Span<T> right) => !(left == right);
/// <summary>
/// This method is not supported as spans cannot be boxed. To compare two spans, use operator==.
/// <exception cref="System.NotSupportedException">
/// Always thrown by this method.
/// </exception>
/// </summary>
[Obsolete("Equals() on Span will always throw an exception. Use == instead.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj)
{
throw new NotSupportedException(SR.NotSupported_CannotCallEqualsOnSpan);
}
/// <summary>
/// This method is not supported as spans cannot be boxed.
/// <exception cref="System.NotSupportedException">
/// Always thrown by this method.
/// </exception>
/// </summary>
[Obsolete("GetHashCode() on Span will always throw an exception.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode()
{
throw new NotSupportedException(SR.NotSupported_CannotCallGetHashCodeOnSpan);
}
/// <summary>
/// Defines an implicit conversion of an array to a <see cref="Span{T}"/>
/// </summary>
public static implicit operator Span<T>(T[] array) => new Span<T>(array);
/// <summary>
/// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="Span{T}"/>
/// </summary>
public static implicit operator Span<T>(ArraySegment<T> arraySegment) => new Span<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count);
/// <summary>
/// Defines an implicit conversion of a <see cref="Span{T}"/> to a <see cref="ReadOnlySpan{T}"/>
/// </summary>
public static implicit operator ReadOnlySpan<T>(Span<T> span) => new ReadOnlySpan<T>(ref span._pointer.Value, span._length);
/// <summary>
/// Forms a slice out of the given span, beginning at 'start'.
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> index is not in range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span<T> Slice(int start)
{
if ((uint)start > (uint)_length)
ThrowHelper.ThrowArgumentOutOfRangeException();
return new Span<T>(ref Unsafe.Add(ref _pointer.Value, start), _length - start);
}
/// <summary>
/// Forms a slice out of the given span, beginning at 'start', of given length
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <param name="length">The desired length for the slice (exclusive).</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span<T> Slice(int start, int length)
{
if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start))
ThrowHelper.ThrowArgumentOutOfRangeException();
return new Span<T>(ref Unsafe.Add(ref _pointer.Value, start), length);
}
/// <summary>
/// Copies the contents of this span into a new array. This heap
/// allocates, so should generally be avoided, however it is sometimes
/// necessary to bridge the gap with APIs written in terms of arrays.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T[] ToArray()
{
if (_length == 0)
return Array.Empty<T>();
var destination = new T[_length];
Span.CopyTo<T>(ref Unsafe.As<byte, T>(ref destination.GetRawSzArrayData()), ref _pointer.Value, _length);
return destination;
}
// <summary>
/// Returns an empty <see cref="Span{T}"/>
/// </summary>
public static Span<T> Empty => default(Span<T>);
}
}
| |
using Lucene.Net.Diagnostics;
using Lucene.Net.Support;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace Lucene.Net.Index
{
/*
* 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.
*/
/// <summary>
/// <para>This class implements a <see cref="MergePolicy"/> that tries
/// to merge segments into levels of exponentially
/// increasing size, where each level has fewer segments than
/// the value of the merge factor. Whenever extra segments
/// (beyond the merge factor upper bound) are encountered,
/// all segments within the level are merged. You can get or
/// set the merge factor using <see cref="MergeFactor"/>.</para>
///
/// <para>This class is abstract and requires a subclass to
/// define the <see cref="MergePolicy.Size(SegmentCommitInfo)"/> method which specifies how a
/// segment's size is determined. <see cref="LogDocMergePolicy"/>
/// is one subclass that measures size by document count in
/// the segment. <see cref="LogByteSizeMergePolicy"/> is another
/// subclass that measures size as the total byte size of the
/// file(s) for the segment.</para>
/// </summary>
public abstract class LogMergePolicy : MergePolicy
{
/// <summary>
/// Defines the allowed range of log(size) for each
/// level. A level is computed by taking the max segment
/// log size, minus LEVEL_LOG_SPAN, and finding all
/// segments falling within that range.
/// </summary>
public static readonly double LEVEL_LOG_SPAN = 0.75;
/// <summary>
/// Default merge factor, which is how many segments are
/// merged at a time
/// </summary>
public static readonly int DEFAULT_MERGE_FACTOR = 10;
/// <summary>
/// Default maximum segment size. A segment of this size
/// or larger will never be merged. </summary>
/// <seealso cref="MaxMergeDocs"/>
public static readonly int DEFAULT_MAX_MERGE_DOCS = int.MaxValue;
/// <summary>
/// Default noCFSRatio. If a merge's size is >= 10% of
/// the index, then we disable compound file for it. </summary>
/// <seealso cref="MergePolicy.NoCFSRatio"/>
public new static readonly double DEFAULT_NO_CFS_RATIO = 0.1;
/// <summary>
/// How many segments to merge at a time. </summary>
protected int m_mergeFactor = DEFAULT_MERGE_FACTOR;
/// <summary>
/// Any segments whose size is smaller than this value
/// will be rounded up to this value. This ensures that
/// tiny segments are aggressively merged.
/// </summary>
protected long m_minMergeSize;
/// <summary>
/// If the size of a segment exceeds this value then it
/// will never be merged.
/// </summary>
protected long m_maxMergeSize;
// Although the core MPs set it explicitly, we must default in case someone
// out there wrote his own LMP ...
/// <summary>
/// If the size of a segment exceeds this value then it
/// will never be merged during <see cref="IndexWriter.ForceMerge(int)"/>.
/// </summary>
protected long m_maxMergeSizeForForcedMerge = long.MaxValue;
/// <summary>
/// If a segment has more than this many documents then it
/// will never be merged.
/// </summary>
protected int m_maxMergeDocs = DEFAULT_MAX_MERGE_DOCS;
/// <summary>
/// If true, we pro-rate a segment's size by the
/// percentage of non-deleted documents.
/// </summary>
protected bool m_calibrateSizeByDeletes = true;
/// <summary>
/// Sole constructor. (For invocation by subclass
/// constructors, typically implicit.)
/// </summary>
public LogMergePolicy()
: base(DEFAULT_NO_CFS_RATIO, MergePolicy.DEFAULT_MAX_CFS_SEGMENT_SIZE)
{
}
/// <summary>
/// Returns true if <see cref="LogMergePolicy"/> is enabled in <see cref="IndexWriter.infoStream"/>.
/// </summary>
protected virtual bool IsVerbose
{
get
{
IndexWriter w = m_writer.Get();
return w != null && w.infoStream.IsEnabled("LMP");
}
}
/// <summary>
/// Print a debug message to <see cref="IndexWriter.infoStream"/>.
/// </summary>
protected virtual void Message(string message)
{
if (IsVerbose)
{
m_writer.Get().infoStream.Message("LMP", message);
}
}
/// <summary>
/// Gets or Sets the number of segments that are merged at
/// once and also controls the total number of segments
/// allowed to accumulate in the index.
/// <para/>
/// This determines how often segment indices are merged by
/// <see cref="IndexWriter.AddDocument(IEnumerable{IIndexableField})"/>. With smaller values, less RAM is used
/// while indexing, and searches are
/// faster, but indexing speed is slower. With larger
/// values, more RAM is used during indexing, and while
/// searches is slower, indexing is
/// faster. Thus larger values (> 10) are best for batch
/// index creation, and smaller values (< 10) for indices
/// that are interactively maintained.
/// </summary>
public virtual int MergeFactor
{
get => m_mergeFactor;
set
{
if (value < 2)
{
throw new ArgumentException("mergeFactor cannot be less than 2");
}
this.m_mergeFactor = value;
}
}
/// <summary>
/// Gets or Sets whether the segment size should be calibrated by
/// the number of deletes when choosing segments for merge.
/// </summary>
public virtual bool CalibrateSizeByDeletes
{
get => m_calibrateSizeByDeletes;
set => this.m_calibrateSizeByDeletes = value;
}
protected override void Dispose(bool disposing)
{
}
/// <summary>
/// Return the number of documents in the provided
/// <see cref="SegmentCommitInfo"/>, pro-rated by percentage of
/// non-deleted documents if
/// <see cref="CalibrateSizeByDeletes"/> is set.
/// </summary>
protected virtual long SizeDocs(SegmentCommitInfo info)
{
if (m_calibrateSizeByDeletes)
{
int delCount = m_writer.Get().NumDeletedDocs(info);
if (Debugging.AssertsEnabled) Debugging.Assert(delCount <= info.Info.DocCount);
return (info.Info.DocCount - (long)delCount);
}
else
{
return info.Info.DocCount;
}
}
/// <summary>
/// Return the byte size of the provided
/// <see cref="SegmentCommitInfo"/>, pro-rated by percentage of
/// non-deleted documents if
/// <see cref="CalibrateSizeByDeletes"/> is set.
/// </summary>
protected virtual long SizeBytes(SegmentCommitInfo info)
{
if (m_calibrateSizeByDeletes)
{
return base.Size(info);
}
return info.GetSizeInBytes();
}
/// <summary>
/// Returns <c>true</c> if the number of segments eligible for
/// merging is less than or equal to the specified
/// <paramref name="maxNumSegments"/>.
/// </summary>
protected virtual bool IsMerged(SegmentInfos infos, int maxNumSegments, IDictionary<SegmentCommitInfo, bool?> segmentsToMerge)
{
int numSegments = infos.Count;
int numToMerge = 0;
SegmentCommitInfo mergeInfo = null;
bool segmentIsOriginal = false;
for (int i = 0; i < numSegments && numToMerge <= maxNumSegments; i++)
{
SegmentCommitInfo info = infos.Info(i);
bool? isOriginal;
segmentsToMerge.TryGetValue(info, out isOriginal);
if (isOriginal != null)
{
segmentIsOriginal = isOriginal.Value;
numToMerge++;
mergeInfo = info;
}
}
return numToMerge <= maxNumSegments && (numToMerge != 1 || !segmentIsOriginal || IsMerged(infos, mergeInfo));
}
/// <summary>
/// Returns the merges necessary to merge the index, taking the max merge
/// size or max merge docs into consideration. this method attempts to respect
/// the <paramref name="maxNumSegments"/> parameter, however it might be, due to size
/// constraints, that more than that number of segments will remain in the
/// index. Also, this method does not guarantee that exactly
/// <paramref name="maxNumSegments"/> will remain, but <= that number.
/// </summary>
private MergeSpecification FindForcedMergesSizeLimit(SegmentInfos infos, int maxNumSegments, int last)
{
MergeSpecification spec = new MergeSpecification();
IList<SegmentCommitInfo> segments = infos.AsList();
int start = last - 1;
while (start >= 0)
{
SegmentCommitInfo info = infos.Info(start);
if (Size(info) > m_maxMergeSizeForForcedMerge || SizeDocs(info) > m_maxMergeDocs)
{
if (IsVerbose)
{
Message("findForcedMergesSizeLimit: skip segment=" + info + ": size is > maxMergeSize (" + m_maxMergeSizeForForcedMerge + ") or sizeDocs is > maxMergeDocs (" + m_maxMergeDocs + ")");
}
// need to skip that segment + add a merge for the 'right' segments,
// unless there is only 1 which is merged.
if (last - start - 1 > 1 || (start != last - 1 && !IsMerged(infos, infos.Info(start + 1))))
{
// there is more than 1 segment to the right of
// this one, or a mergeable single segment.
spec.Add(new OneMerge(segments.SubList(start + 1, last)));
}
last = start;
}
else if (last - start == m_mergeFactor)
{
// mergeFactor eligible segments were found, add them as a merge.
spec.Add(new OneMerge(segments.SubList(start, last)));
last = start;
}
--start;
}
// Add any left-over segments, unless there is just 1
// already fully merged
if (last > 0 && (++start + 1 < last || !IsMerged(infos, infos.Info(start))))
{
spec.Add(new OneMerge(segments.SubList(start, last)));
}
return spec.Merges.Count == 0 ? null : spec;
}
/// <summary>
/// Returns the merges necessary to <see cref="IndexWriter.ForceMerge(int)"/> the index. this method constraints
/// the returned merges only by the <paramref name="maxNumSegments"/> parameter, and
/// guaranteed that exactly that number of segments will remain in the index.
/// </summary>
private MergeSpecification FindForcedMergesMaxNumSegments(SegmentInfos infos, int maxNumSegments, int last)
{
var spec = new MergeSpecification();
var segments = infos.AsList();
// First, enroll all "full" merges (size
// mergeFactor) to potentially be run concurrently:
while (last - maxNumSegments + 1 >= m_mergeFactor)
{
spec.Add(new OneMerge(segments.SubList(last - m_mergeFactor, last)));
last -= m_mergeFactor;
}
// Only if there are no full merges pending do we
// add a final partial (< mergeFactor segments) merge:
if (0 == spec.Merges.Count)
{
if (maxNumSegments == 1)
{
// Since we must merge down to 1 segment, the
// choice is simple:
if (last > 1 || !IsMerged(infos, infos.Info(0)))
{
spec.Add(new OneMerge(segments.SubList(0, last)));
}
}
else if (last > maxNumSegments)
{
// Take care to pick a partial merge that is
// least cost, but does not make the index too
// lopsided. If we always just picked the
// partial tail then we could produce a highly
// lopsided index over time:
// We must merge this many segments to leave
// maxNumSegments in the index (from when
// forceMerge was first kicked off):
int finalMergeSize = last - maxNumSegments + 1;
// Consider all possible starting points:
long bestSize = 0;
int bestStart = 0;
for (int i = 0; i < last - finalMergeSize + 1; i++)
{
long sumSize = 0;
for (int j = 0; j < finalMergeSize; j++)
{
sumSize += Size(infos.Info(j + i));
}
if (i == 0 || (sumSize < 2 * Size(infos.Info(i - 1)) && sumSize < bestSize))
{
bestStart = i;
bestSize = sumSize;
}
}
spec.Add(new OneMerge(segments.SubList(bestStart, bestStart + finalMergeSize)));
}
}
return spec.Merges.Count == 0 ? null : spec;
}
// LUCENENET TODO: Get rid of the nullable in IDictionary<SegmentCommitInfo, bool?>, if possible
/// <summary>
/// Returns the merges necessary to merge the index down
/// to a specified number of segments.
/// this respects the <see cref="m_maxMergeSizeForForcedMerge"/> setting.
/// By default, and assuming <c>maxNumSegments=1</c>, only
/// one segment will be left in the index, where that segment
/// has no deletions pending nor separate norms, and it is in
/// compound file format if the current useCompoundFile
/// setting is <c>true</c>. This method returns multiple merges
/// (mergeFactor at a time) so the <see cref="MergeScheduler"/>
/// in use may make use of concurrency.
/// </summary>
public override MergeSpecification FindForcedMerges(SegmentInfos infos, int maxNumSegments, IDictionary<SegmentCommitInfo, bool?> segmentsToMerge)
{
if (Debugging.AssertsEnabled) Debugging.Assert(maxNumSegments > 0);
if (IsVerbose)
{
Message("findForcedMerges: maxNumSegs=" + maxNumSegments + " segsToMerge=" +
string.Format(J2N.Text.StringFormatter.InvariantCulture, "{0}", segmentsToMerge));
}
// If the segments are already merged (e.g. there's only 1 segment), or
// there are <maxNumSegments:.
if (IsMerged(infos, maxNumSegments, segmentsToMerge))
{
if (IsVerbose)
{
Message("already merged; skip");
}
return null;
}
// Find the newest (rightmost) segment that needs to
// be merged (other segments may have been flushed
// since merging started):
int last = infos.Count;
while (last > 0)
{
SegmentCommitInfo info = infos.Info(--last);
if (segmentsToMerge.ContainsKey(info))
{
last++;
break;
}
}
if (last == 0)
{
if (IsVerbose)
{
Message("last == 0; skip");
}
return null;
}
// There is only one segment already, and it is merged
if (maxNumSegments == 1 && last == 1 && IsMerged(infos, infos.Info(0)))
{
if (IsVerbose)
{
Message("already 1 seg; skip");
}
return null;
}
// Check if there are any segments above the threshold
bool anyTooLarge = false;
for (int i = 0; i < last; i++)
{
SegmentCommitInfo info = infos.Info(i);
if (Size(info) > m_maxMergeSizeForForcedMerge || SizeDocs(info) > m_maxMergeDocs)
{
anyTooLarge = true;
break;
}
}
if (anyTooLarge)
{
return FindForcedMergesSizeLimit(infos, maxNumSegments, last);
}
else
{
return FindForcedMergesMaxNumSegments(infos, maxNumSegments, last);
}
}
/// <summary>
/// Finds merges necessary to force-merge all deletes from the
/// index. We simply merge adjacent segments that have
/// deletes, up to mergeFactor at a time.
/// </summary>
public override MergeSpecification FindForcedDeletesMerges(SegmentInfos segmentInfos)
{
var segments = segmentInfos.AsList();
int numSegments = segments.Count;
if (IsVerbose)
{
Message("findForcedDeleteMerges: " + numSegments + " segments");
}
var spec = new MergeSpecification();
int firstSegmentWithDeletions = -1;
IndexWriter w = m_writer.Get();
if (Debugging.AssertsEnabled) Debugging.Assert(w != null);
for (int i = 0; i < numSegments; i++)
{
SegmentCommitInfo info = segmentInfos.Info(i);
int delCount = w.NumDeletedDocs(info);
if (delCount > 0)
{
if (IsVerbose)
{
Message(" segment " + info.Info.Name + " has deletions");
}
if (firstSegmentWithDeletions == -1)
{
firstSegmentWithDeletions = i;
}
else if (i - firstSegmentWithDeletions == m_mergeFactor)
{
// We've seen mergeFactor segments in a row with
// deletions, so force a merge now:
if (IsVerbose)
{
Message(" add merge " + firstSegmentWithDeletions + " to " + (i - 1) + " inclusive");
}
spec.Add(new OneMerge(segments.SubList(firstSegmentWithDeletions, i)));
firstSegmentWithDeletions = i;
}
}
else if (firstSegmentWithDeletions != -1)
{
// End of a sequence of segments with deletions, so,
// merge those past segments even if it's fewer than
// mergeFactor segments
if (IsVerbose)
{
Message(" add merge " + firstSegmentWithDeletions + " to " + (i - 1) + " inclusive");
}
spec.Add(new OneMerge(segments.SubList(firstSegmentWithDeletions, i)));
firstSegmentWithDeletions = -1;
}
}
if (firstSegmentWithDeletions != -1)
{
if (IsVerbose)
{
Message(" add merge " + firstSegmentWithDeletions + " to " + (numSegments - 1) + " inclusive");
}
spec.Add(new OneMerge(segments.SubList(firstSegmentWithDeletions, numSegments)));
}
return spec;
}
private class SegmentInfoAndLevel : IComparable<SegmentInfoAndLevel>
{
internal readonly SegmentCommitInfo info;
internal readonly float level;
private int index;
public SegmentInfoAndLevel(SegmentCommitInfo info, float level, int index)
{
this.info = info;
this.level = level;
this.index = index;
}
// Sorts largest to smallest
public virtual int CompareTo(SegmentInfoAndLevel other)
{
return other.level.CompareTo(level);
}
}
/// <summary>
/// Checks if any merges are now necessary and returns a
/// <see cref="MergePolicy.MergeSpecification"/> if so. A merge
/// is necessary when there are more than
/// <see cref="MergeFactor"/> segments at a given level. When
/// multiple levels have too many segments, this method
/// will return multiple merges, allowing the
/// <see cref="MergeScheduler"/> to use concurrency.
/// </summary>
public override MergeSpecification FindMerges(MergeTrigger mergeTrigger, SegmentInfos infos)
{
int numSegments = infos.Count;
if (IsVerbose)
{
Message("findMerges: " + numSegments + " segments");
}
// Compute levels, which is just log (base mergeFactor)
// of the size of each segment
IList<SegmentInfoAndLevel> levels = new List<SegmentInfoAndLevel>();
var norm = (float)Math.Log(m_mergeFactor);
ICollection<SegmentCommitInfo> mergingSegments = m_writer.Get().MergingSegments;
for (int i = 0; i < numSegments; i++)
{
SegmentCommitInfo info = infos.Info(i);
long size = Size(info);
// Floor tiny segments
if (size < 1)
{
size = 1;
}
SegmentInfoAndLevel infoLevel = new SegmentInfoAndLevel(info, (float)Math.Log(size) / norm, i);
levels.Add(infoLevel);
if (IsVerbose)
{
long segBytes = SizeBytes(info);
string extra = mergingSegments.Contains(info) ? " [merging]" : "";
if (size >= m_maxMergeSize)
{
extra += " [skip: too large]";
}
Message("seg=" + m_writer.Get().SegString(info) + " level=" + infoLevel.level + " size=" + String.Format(CultureInfo.InvariantCulture, "{0:0.00} MB", segBytes / 1024 / 1024.0) + extra);
}
}
float levelFloor;
if (m_minMergeSize <= 0)
{
levelFloor = (float)0.0;
}
else
{
levelFloor = (float)(Math.Log(m_minMergeSize) / norm);
}
// Now, we quantize the log values into levels. The
// first level is any segment whose log size is within
// LEVEL_LOG_SPAN of the max size, or, who has such as
// segment "to the right". Then, we find the max of all
// other segments and use that to define the next level
// segment, etc.
MergeSpecification spec = null;
int numMergeableSegments = levels.Count;
int start = 0;
while (start < numMergeableSegments)
{
// Find max level of all segments not already
// quantized.
float maxLevel = levels[start].level;
for (int i = 1 + start; i < numMergeableSegments; i++)
{
float level = levels[i].level;
if (level > maxLevel)
{
maxLevel = level;
}
}
// Now search backwards for the rightmost segment that
// falls into this level:
float levelBottom;
if (maxLevel <= levelFloor)
{
// All remaining segments fall into the min level
levelBottom = -1.0F;
}
else
{
levelBottom = (float)(maxLevel - LEVEL_LOG_SPAN);
// Force a boundary at the level floor
if (levelBottom < levelFloor && maxLevel >= levelFloor)
{
levelBottom = levelFloor;
}
}
int upto = numMergeableSegments - 1;
while (upto >= start)
{
if (levels[upto].level >= levelBottom)
{
break;
}
upto--;
}
if (IsVerbose)
{
Message(" level " + levelBottom.ToString("0.0") + " to " + maxLevel.ToString("0.0") + ": " + (1 + upto - start) + " segments");
}
// Finally, record all merges that are viable at this level:
int end = start + m_mergeFactor;
while (end <= 1 + upto)
{
bool anyTooLarge = false;
bool anyMerging = false;
for (int i = start; i < end; i++)
{
SegmentCommitInfo info = levels[i].info;
anyTooLarge |= (Size(info) >= m_maxMergeSize || SizeDocs(info) >= m_maxMergeDocs);
if (mergingSegments.Contains(info))
{
anyMerging = true;
break;
}
}
if (anyMerging)
{
// skip
}
else if (!anyTooLarge)
{
if (spec == null)
{
spec = new MergeSpecification();
}
IList<SegmentCommitInfo> mergeInfos = new List<SegmentCommitInfo>();
for (int i = start; i < end; i++)
{
mergeInfos.Add(levels[i].info);
if (Debugging.AssertsEnabled) Debugging.Assert(infos.Contains(levels[i].info));
}
if (IsVerbose)
{
Message(" add merge=" + m_writer.Get().SegString(mergeInfos) + " start=" + start + " end=" + end);
}
spec.Add(new OneMerge(mergeInfos));
}
else if (IsVerbose)
{
Message(" " + start + " to " + end + ": contains segment over maxMergeSize or maxMergeDocs; skipping");
}
start = end;
end = start + m_mergeFactor;
}
start = 1 + upto;
}
return spec;
}
/// <summary>
/// <para>Determines the largest segment (measured by
/// document count) that may be merged with other segments.
/// Small values (e.g., less than 10,000) are best for
/// interactive indexing, as this limits the length of
/// pauses while indexing to a few seconds. Larger values
/// are best for batched indexing and speedier
/// searches.</para>
///
/// <para>The default value is <see cref="int.MaxValue"/>.</para>
///
/// <para>The default merge policy
/// (<see cref="LogByteSizeMergePolicy"/>) also allows you to set this
/// limit by net size (in MB) of the segment, using
/// <see cref="LogByteSizeMergePolicy.MaxMergeMB"/>.</para>
/// </summary>
public virtual int MaxMergeDocs
{
get => m_maxMergeDocs;
set => this.m_maxMergeDocs = value;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder("[" + this.GetType().Name + ": ");
sb.Append("minMergeSize=").Append(m_minMergeSize).Append(", ");
sb.Append("mergeFactor=").Append(m_mergeFactor).Append(", ");
sb.Append("maxMergeSize=").Append(m_maxMergeSize).Append(", ");
sb.Append("maxMergeSizeForForcedMerge=").Append(m_maxMergeSizeForForcedMerge).Append(", ");
sb.Append("calibrateSizeByDeletes=").Append(m_calibrateSizeByDeletes).Append(", ");
sb.Append("maxMergeDocs=").Append(m_maxMergeDocs).Append(", ");
sb.Append("maxCFSSegmentSizeMB=").Append(MaxCFSSegmentSizeMB).Append(", ");
sb.Append("noCFSRatio=").Append(m_noCFSRatio);
sb.Append("]");
return sb.ToString();
}
}
}
| |
#if NET20
// Taken and adapted from: https://github.com/mono/mono/blob/mono-3.12.1/mcs/class/System/System.Collections.Generic/SortedSet.cs
//
// Authors:
// Jb Evain <jbevain@novell.com>
// Marek Safar (marek.safar@gmail.com)
//
// Copyright (C) 2010 Novell, Inc (http://www.novell.com)
// Copyright (C) 2014 Xamarin Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.CodeDom.Compiler;
using System.Diagnostics;
using System.Runtime.Serialization;
// ReSharper disable All
namespace System.Collections.Generic
{
/// <summary>
/// Backport of <c>System.Collections.Generic.SortedSet{T}</c>.
/// </summary>
[GeneratedCode("Mono BCL", "3.2")] // ignore in code analysis
[Serializable]
[DebuggerDisplay ("Count={Count}")]
public class SortedSet<T> : ICollection<T>, ISerializable, IDeserializationCallback
{
class Node : RBTree.Node
{
public T item;
public Node(T item)
{
this.item = item;
}
public override void SwapValue(RBTree.Node other)
{
var o = (Node)other;
var i = this.item;
this.item = o.item;
o.item = i;
}
}
class NodeHelper : RBTree.INodeHelper<T>
{
static NodeHelper Default = new NodeHelper(Comparer<T>.Default);
public IComparer<T> comparer;
public int Compare(T item, RBTree.Node node)
{
return comparer.Compare(item, ((Node)node).item);
}
public RBTree.Node CreateNode(T item)
{
return new Node(item);
}
NodeHelper(IComparer<T> comparer)
{
this.comparer = comparer;
}
public static NodeHelper GetHelper(IComparer<T> comparer)
{
if (comparer == null || comparer == Comparer<T>.Default)
return Default;
return new NodeHelper(comparer);
}
}
RBTree tree;
NodeHelper helper;
SerializationInfo si;
public SortedSet()
: this(Comparer<T>.Default)
{
}
public SortedSet(IEnumerable<T> collection)
: this(collection, Comparer<T>.Default)
{
}
public SortedSet(IEnumerable<T> collection, IComparer<T> comparer)
: this(comparer)
{
if (collection == null)
throw new ArgumentNullException("collection");
foreach (var item in collection)
Add(item);
}
public SortedSet(IComparer<T> comparer)
{
this.helper = NodeHelper.GetHelper(comparer);
this.tree = new RBTree(this.helper);
}
protected SortedSet(SerializationInfo info, StreamingContext context)
{
this.si = info;
}
public IComparer<T> Comparer
{
get { return helper.comparer; }
}
public int Count
{
get { return GetCount(); }
}
public T Max
{
get { return GetMax(); }
}
public T Min
{
get { return GetMin(); }
}
internal virtual T GetMax()
{
if (tree.Count == 0)
return default(T);
return GetItem(tree.Count - 1);
}
internal virtual T GetMin()
{
if (tree.Count == 0)
return default(T);
return GetItem(0);
}
internal virtual int GetCount()
{
return tree.Count;
}
T GetItem(int index)
{
return ((Node)tree[index]).item;
}
public bool Add(T item)
{
return TryAdd(item);
}
internal virtual bool TryAdd(T item)
{
var node = new Node(item);
return tree.Intern(item, node) == node;
}
public virtual void Clear()
{
tree.Clear();
}
public virtual bool Contains(T item)
{
return tree.Lookup(item) != null;
}
public void CopyTo(T[] array)
{
CopyTo(array, 0, Count);
}
public void CopyTo(T[] array, int index)
{
CopyTo(array, index, Count);
}
public void CopyTo(T[] array, int index, int count)
{
if (array == null)
throw new ArgumentNullException("array");
if (index < 0)
throw new ArgumentOutOfRangeException("index");
if (index > array.Length)
throw new ArgumentException("index larger than largest valid index of array");
if (array.Length - index < count)
throw new ArgumentException("destination array cannot hold the requested elements");
foreach (Node node in tree)
{
if (count-- == 0)
break;
array[index++] = node.item;
}
}
public bool Remove(T item)
{
return TryRemove(item);
}
internal virtual bool TryRemove(T item)
{
return tree.Remove(item) != null;
}
public int RemoveWhere(Predicate<T> match)
{
var array = ToArray();
int count = 0;
foreach (var item in array)
{
if (!match(item))
continue;
Remove(item);
count++;
}
return count;
}
public IEnumerable<T> Reverse()
{
for (int i = tree.Count - 1; i >= 0; i--)
yield return GetItem(i);
}
T[] ToArray()
{
var array = new T[this.Count];
CopyTo(array);
return array;
}
public Enumerator GetEnumerator()
{
return TryGetEnumerator();
}
internal virtual Enumerator TryGetEnumerator()
{
return new Enumerator(this);
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public static IEqualityComparer<SortedSet<T>> CreateSetComparer()
{
throw new NotImplementedException();
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new NotImplementedException();
}
public void OnDeserialization(object sender)
{
throw new NotImplementedException();
}
public void ExceptWith(IEnumerable<T> other)
{
if (other == this)
{
Clear();
return;
}
CheckArgumentNotNull(other, "other");
foreach (T item in other)
Remove(item);
}
public virtual SortedSet<T> GetViewBetween(T lowerValue, T upperValue)
{
if (Comparer.Compare(lowerValue, upperValue) > 0)
throw new ArgumentException("The lowerValue is bigger than upperValue");
return new SortedSubSet(this, lowerValue, upperValue);
}
public virtual void IntersectWith(IEnumerable<T> other)
{
CheckArgumentNotNull(other, "other");
RBTree newtree = new RBTree(helper);
foreach (T item in other)
{
var node = tree.Remove(item);
if (node != null)
newtree.Intern(item, node);
}
tree = newtree;
}
public bool IsProperSubsetOf(IEnumerable<T> other)
{
CheckArgumentNotNull(other, "other");
if (Count == 0)
{
foreach (T item in other)
return true; // this idiom means: if 'other' is non-empty, return true
return false;
}
return is_subset_of(other, true);
}
public bool IsProperSupersetOf(IEnumerable<T> other)
{
CheckArgumentNotNull(other, "other");
if (Count == 0)
return false;
return is_superset_of(other, true);
}
public bool IsSubsetOf(IEnumerable<T> other)
{
CheckArgumentNotNull(other, "other");
if (Count == 0)
return true;
return is_subset_of(other, false);
}
public bool IsSupersetOf(IEnumerable<T> other)
{
CheckArgumentNotNull(other, "other");
if (Count == 0)
{
foreach (T item in other)
return false; // this idiom means: if 'other' is non-empty, return false
return true;
}
return is_superset_of(other, false);
}
// Precondition: Count != 0, other != null
bool is_subset_of(IEnumerable<T> other, bool proper)
{
SortedSet<T> that = nodups(other);
if (Count > that.Count)
return false;
// Count != 0 && Count <= that.Count => that.Count != 0
if (proper && Count == that.Count)
return false;
return that.covers(this);
}
// Precondition: Count != 0, other != null
bool is_superset_of(IEnumerable<T> other, bool proper)
{
SortedSet<T> that = nodups(other);
if (that.Count == 0)
return true;
if (Count < that.Count)
return false;
if (proper && Count == that.Count)
return false;
return this.covers(that);
}
public bool Overlaps(IEnumerable<T> other)
{
CheckArgumentNotNull(other, "other");
if (Count == 0)
return false;
// Don't use 'nodups' here. Only optimize the SortedSet<T> case
SortedSet<T> that = other as SortedSet<T>;
if (that != null && that.Comparer != Comparer)
that = null;
if (that != null)
return that.Count != 0 && overlaps(that);
foreach (T item in other)
if (Contains(item))
return true;
return false;
}
public bool SetEquals(IEnumerable<T> other)
{
CheckArgumentNotNull(other, "other");
if (Count == 0)
{
foreach (T item in other)
return false;
return true;
}
SortedSet<T> that = nodups(other);
if (Count != that.Count)
return false;
using (var t = that.GetEnumerator())
{
foreach (T item in this)
{
if (!t.MoveNext())
throw new SystemException("count wrong somewhere: this longer than that");
if (Comparer.Compare(item, t.Current) != 0)
return false;
}
if (t.MoveNext())
throw new SystemException("count wrong somewhere: this shorter than that");
return true;
}
}
SortedSet<T> nodups(IEnumerable<T> other)
{
SortedSet<T> that = other as SortedSet<T>;
if (that != null && that.Comparer == Comparer)
return that;
return new SortedSet<T>(other, Comparer);
}
bool covers(SortedSet<T> that)
{
using (var t = that.GetEnumerator())
{
if (!t.MoveNext())
return true;
foreach (T item in this)
{
int cmp = Comparer.Compare(item, t.Current);
if (cmp > 0)
return false;
if (cmp == 0 && !t.MoveNext())
return true;
}
return false;
}
}
bool overlaps(SortedSet<T> that)
{
using (var t = that.GetEnumerator())
{
if (!t.MoveNext())
return false;
foreach (T item in this)
{
int cmp;
while ((cmp = Comparer.Compare(item, t.Current)) > 0)
{
if (!t.MoveNext())
return false;
}
if (cmp == 0)
return true;
}
return false;
}
}
public void SymmetricExceptWith(IEnumerable<T> other)
{
if (other == this)
{
Clear();
return;
}
SortedSet<T> that_minus_this = new SortedSet<T>(Comparer);
// compute this - that and that - this in parallel
foreach (T item in nodups(other))
if (!Remove(item))
that_minus_this.Add(item);
UnionWith(that_minus_this);
}
public void UnionWith(IEnumerable<T> other)
{
CheckArgumentNotNull(other, "other");
foreach (T item in other)
Add(item);
}
static void CheckArgumentNotNull(object arg, string name)
{
if (arg == null)
throw new ArgumentNullException(name);
}
void ICollection<T>.Add(T item)
{
Add(item);
}
bool ICollection<T>.IsReadOnly
{
get { return false; }
}
[Serializable]
public struct Enumerator : IEnumerator<T>, IDisposable
{
RBTree.NodeEnumerator host;
IComparer<T> comparer;
T current;
T upper;
internal Enumerator(SortedSet<T> set)
: this()
{
host = set.tree.GetEnumerator();
}
internal Enumerator(SortedSet<T> set, T lower, T upper)
: this()
{
host = set.tree.GetSuffixEnumerator(lower);
comparer = set.Comparer;
this.upper = upper;
}
public T Current
{
get { return current; }
}
object IEnumerator.Current
{
get
{
host.check_current();
return ((Node)host.Current).item;
}
}
public bool MoveNext()
{
if (!host.MoveNext())
return false;
current = ((Node)host.Current).item;
return comparer == null || comparer.Compare(upper, current) >= 0;
}
public void Dispose()
{
host.Dispose();
}
void IEnumerator.Reset()
{
host.Reset();
}
}
[Serializable]
sealed class SortedSubSet : SortedSet<T>, IEnumerable<T>, IEnumerable
{
SortedSet<T> set;
T lower;
T upper;
public SortedSubSet(SortedSet<T> set, T lower, T upper)
: base(set.Comparer)
{
this.set = set;
this.lower = lower;
this.upper = upper;
}
internal override T GetMin()
{
RBTree.Node lb = null, ub = null;
set.tree.Bound(lower, ref lb, ref ub);
if (ub == null || set.helper.Compare(upper, ub) < 0)
return default(T);
return ((Node)ub).item;
}
internal override T GetMax()
{
RBTree.Node lb = null, ub = null;
set.tree.Bound(upper, ref lb, ref ub);
if (lb == null || set.helper.Compare(lower, lb) > 0)
return default(T);
return ((Node)lb).item;
}
internal override int GetCount()
{
int count = 0;
using (var e = set.tree.GetSuffixEnumerator(lower))
{
while (e.MoveNext() && set.helper.Compare(upper, e.Current) >= 0)
++count;
}
return count;
}
internal override bool TryAdd(T item)
{
if (!InRange(item))
throw new ArgumentOutOfRangeException("item");
return set.TryAdd(item);
}
internal override bool TryRemove(T item)
{
if (!InRange(item))
return false;
return set.TryRemove(item);
}
public override bool Contains(T item)
{
if (!InRange(item))
return false;
return set.Contains(item);
}
public override void Clear()
{
set.RemoveWhere(InRange);
}
bool InRange(T item)
{
return Comparer.Compare(item, lower) >= 0
&& Comparer.Compare(item, upper) <= 0;
}
public override SortedSet<T> GetViewBetween(T lowerValue, T upperValue)
{
if (Comparer.Compare(lowerValue, upperValue) > 0)
throw new ArgumentException("The lowerValue is bigger than upperValue");
if (!InRange(lowerValue))
throw new ArgumentOutOfRangeException("lowerValue");
if (!InRange(upperValue))
throw new ArgumentOutOfRangeException("upperValue");
return new SortedSubSet(set, lowerValue, upperValue);
}
internal override Enumerator TryGetEnumerator()
{
return new Enumerator(set, lower, upper);
}
public override void IntersectWith(IEnumerable<T> other)
{
CheckArgumentNotNull(other, "other");
var slice = new SortedSet<T>(this);
slice.IntersectWith(other);
Clear();
set.UnionWith(slice);
}
}
}
}
#else
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.SortedSet<>))]
#endif
| |
//-----------------------------------------------------------------------------
// Torque
// Copyright GarageGames, LLC 2011
//-----------------------------------------------------------------------------
// GrenadeLauncher weapon.
// This script file contains all of the necessary datablocks needed for the
// GrenadeLauncher. These datablocks include sound profiles, light descriptions,
// particle effects, explosions, projectiles, items (weapon and ammo), shell
// casings (if any), and finally the weapon image which contains the state
// machine that determines how the weapon operates.
// The various "fire" methods/modes are handled in weapons.cs through a "weapon"
// namespace function. This reduces duplicated code, although a unique fire
// method could still be implemented for this weapon.
// ----------------------------------------------------------------------------
// Sound profiles
// ----------------------------------------------------------------------------
datablock SFXProfile(GrenadeLauncherReloadSound)
{
filename = "art/sound/weapons/Crossbow_reload";
description = AudioClose3d;
preload = true;
};
datablock SFXProfile(GrenadeLauncherFireSound)
{
filename = "art/sound/weapons/relbow_mono_01";
description = AudioClose3d;
preload = true;
};
datablock SFXProfile(GrenadeLauncherFireEmptySound)
{
filename = "art/sound/weapons/Crossbow_firing_empty";
description = AudioClose3d;
preload = true;
};
datablock SFXProfile(GrenadeLauncherExplosionSound)
{
filename = "art/sound/weapons/Crossbow_explosion";
description = AudioDefault3d;
preload = true;
};
// ----------------------------------------------------------------------------
// Lights for the projectile(s)
// ----------------------------------------------------------------------------
datablock LightDescription(GrenadeLauncherLightDesc)
{
range = 1.0;
color = "1 1 1";
brightness = 2.0;
animationType = PulseLightAnim;
animationPeriod = 0.25;
//flareType = SimpleLightFlare0;
};
datablock LightDescription(GrenadeLauncherWaterLightDesc)
{
radius = 2.0;
color = "1 1 1";
brightness = 2.0;
animationType = PulseLightAnim;
animationPeriod = 0.25;
//flareType = SimpleLightFlare0;
};
//----------------------------------------------------------------------------
// Debris
//----------------------------------------------------------------------------
datablock ParticleData(GrenadeDebrisFireParticle)
{
textureName = "art/shapes/particles/impact";
dragCoeffiecient = 0.0;
gravityCoefficient = -1;
inheritedVelFactor = 0.0;
constantAcceleration = 0.0;
lifetimeMS = 300;
lifetimeVarianceMS = 100;
useInvAlpha = false;
spinSpeed = 1;
spinRandomMin = -280.0;
spinRandomMax = 280.0;
colors[0] = "1.0 0.6 0.2 0.1";
colors[1] = "1.0 0.5 0 0.5";
colors[2] = "0.1 0.1 0.1 0.0";
sizes[0] = 1.0;
sizes[1] = 2.0;
sizes[2] = 1.0;
times[0] = 0.0;
times[1] = 0.5;
times[2] = 1.0;
};
datablock ParticleEmitterData(GrenadeDebrisFireEmitter)
{
ejectionPeriodMS = 8;
periodVarianceMS = 4;
ejectionVelocity = 5.0;
velocityVariance = 3.0;
thetaMin = 0.0;
thetaMax = 180.0;
phiReferenceVel = 0;
phiVariance = 360;
ejectionoffset = 0.3;
particles = "GrenadeDebrisFireParticle";
};
datablock DebrisData(GrenadeDebris)
{
shapeFile = "art/shapes/weapons/ramrifle/debris.dts";
emitters[0] = GrenadeDebrisFireEmitter;
elasticity = 0.4;
friction = 0.25;
numBounces = 3;
bounceVariance = 1;
explodeOnMaxBounce = false;
staticOnMaxBounce = false;
snapOnMaxBounce = false;
minSpinSpeed = 200;
maxSpinSpeed = 600;
render2D = false;
lifetime = 4;
lifetimeVariance = 1.5;
velocity = 15;
velocityVariance = 5;
fade = true;
useRadiusMass = true;
baseRadius = 0.3;
gravModifier = 1.0;
terminalVelocity = 20;
ignoreWater = false;
};
// ----------------------------------------------------------------------------
// Splash effects
// ----------------------------------------------------------------------------
datablock ParticleData(GrenadeSplashMist)
{
dragCoefficient = 1.0;
windCoefficient = 2.0;
gravityCoefficient = 0.3;
inheritedVelFactor = 0.0;
constantAcceleration = 0.0;
lifetimeMS = 600;
lifetimeVarianceMS = 100;
useInvAlpha = false;
spinRandomMin = -90.0;
spinRandomMax = 500.0;
spinSpeed = 1;
textureName = "art/shapes/particles/smoke";
colors[0] = "0.7 0.8 1.0 1.0";
colors[1] = "0.7 0.8 1.0 0.5";
colors[2] = "0.7 0.8 1.0 0.0";
sizes[0] = 0.2;
sizes[1] = 0.4;
sizes[2] = 0.8;
times[0] = 0.0;
times[1] = 0.5;
times[2] = 1.0;
};
datablock ParticleEmitterData(GrenadeSplashMistEmitter)
{
ejectionPeriodMS = 5;
periodVarianceMS = 0;
ejectionVelocity = 3.0;
velocityVariance = 2.0;
ejectionOffset = 0.15;
thetaMin = 85;
thetaMax = 85;
phiReferenceVel = 0;
phiVariance = 360;
overrideAdvance = false;
lifetimeMS = 250;
particles = "GrenadeSplashMist";
};
datablock ParticleData(GrenadeSplashParticle)
{
dragCoefficient = 1;
windCoefficient = 0.9;
gravityCoefficient = 0.3;
inheritedVelFactor = 0.2;
constantAcceleration = -1.4;
lifetimeMS = 600;
lifetimeVarianceMS = 200;
textureName = "art/shapes/particles/droplet";
colors[0] = "0.7 0.8 1.0 1.0";
colors[1] = "0.7 0.8 1.0 0.5";
colors[2] = "0.7 0.8 1.0 0.0";
sizes[0] = 0.5;
sizes[1] = 0.25;
sizes[2] = 0.25;
times[0] = 0.0;
times[1] = 0.5;
times[2] = 1.0;
};
datablock ParticleEmitterData(GrenadeSplashEmitter)
{
ejectionPeriodMS = 4;
periodVarianceMS = 0;
ejectionVelocity = 7.3;
velocityVariance = 2.0;
ejectionOffset = 0.0;
thetaMin = 30;
thetaMax = 80;
phiReferenceVel = 00;
phiVariance = 360;
overrideAdvance = false;
orientParticles = true;
orientOnVelocity = true;
lifetimeMS = 100;
particles = "GrenadeSplashParticle";
};
datablock ParticleData(GrenadeSplashRingParticle)
{
textureName = "art/shapes/particles/wake";
dragCoefficient = 0.0;
gravityCoefficient = 0.0;
inheritedVelFactor = 0.0;
lifetimeMS = 2500;
lifetimeVarianceMS = 200;
windCoefficient = 0.0;
useInvAlpha = 1;
spinRandomMin = 30.0;
spinRandomMax = 30.0;
spinSpeed = 1;
animateTexture = true;
framesPerSec = 1;
animTexTiling = "2 1";
animTexFrames = "0 1";
colors[0] = "0.7 0.8 1.0 1.0";
colors[1] = "0.7 0.8 1.0 0.5";
colors[2] = "0.7 0.8 1.0 0.0";
sizes[0] = 2.0;
sizes[1] = 4.0;
sizes[2] = 8.0;
times[0] = 0.0;
times[1] = 0.5;
times[2] = 1.0;
};
datablock ParticleEmitterData(GrenadeSplashRingEmitter)
{
lifetimeMS = "100";
ejectionPeriodMS = 200;
periodVarianceMS = 10;
ejectionVelocity = 0;
velocityVariance = 0;
ejectionOffset = 0;
thetaMin = 89;
thetaMax = 90;
phiReferenceVel = 0;
phiVariance = 1;
alignParticles = 1;
alignDirection = "0 0 1";
particles = "GrenadeSplashRingParticle";
};
datablock SplashData(GrenadeSplash)
{
// numSegments = 15;
// ejectionFreq = 15;
// ejectionAngle = 40;
// ringLifetime = 0.5;
// lifetimeMS = 300;
// velocity = 4.0;
// startRadius = 0.0;
// acceleration = -3.0;
// texWrap = 5.0;
// texture = "art/shapes/particles/splash";
emitter[0] = GrenadeSplashEmitter;
emitter[1] = GrenadeSplashMistEmitter;
emitter[2] = GrenadeSplashRingEmitter;
// colors[0] = "0.7 0.8 1.0 0.0";
// colors[1] = "0.7 0.8 1.0 0.3";
// colors[2] = "0.7 0.8 1.0 0.7";
// colors[3] = "0.7 0.8 1.0 0.0";
//
// times[0] = 0.0;
// times[1] = 0.4;
// times[2] = 0.8;
// times[3] = 1.0;
};
// ----------------------------------------------------------------------------
// Explosion Particle effects
// ----------------------------------------------------------------------------
datablock ParticleData(GrenadeExpFire)
{
textureName = "art/shapes/particles/fireball";
dragCoeffiecient = 0;
windCoeffiecient = 0.5;
gravityCoefficient = -0.300366;
inheritedVelFactor = 0.299413;
constantAcceleration = 0.2;
lifetimeMS = 2000;//3000;
lifetimeVarianceMS = 299;//200;
useInvAlpha = false;
spinRandomMin = -80.0;
spinRandomMax = 0;
spinSpeed = 1;
colors[0] = "0.795276 0.393701 0 0.795276";
colors[1] = "0.19685 0.0944882 0 0.393701";
colors[2] = "0 0 0 0";
sizes[0] = 0.75;//2;
sizes[1] = 1.5;
sizes[2] = 3;//0.5;
times[0] = 0.0;
times[1] = 0.498039;
times[2] = 1.0;
animTexName = "art/shapes/particles/Fireball";
times[3] = "1";
};
datablock ParticleEmitterData(GrenadeExpFireEmitter)
{
ejectionPeriodMS = 10;
periodVarianceMS = 5;//0;
ejectionVelocity = 4;//1.0;
velocityVariance = 1;//0.5;
thetaMin = 0.0;
thetaMax = 180.0;
lifetimeMS = 250;
particles = "GrenadeExpFire";
};
datablock ParticleData(GrenadeExpDust)
{
textureName = "art/shapes/particles/smoke";
dragCoefficient = 1.0;
gravityCoefficient = -0.01;
inheritedVelFactor = 0.0;
constantAcceleration = 0.0;
lifetimeMS = 2500;
lifetimeVarianceMS = 500;
useInvAlpha = true;
spinSpeed = 1;
spinRandomMin = -90.0;
spinRandomMax = 90.0;
colors[0] = "0.6 0.6 0.6 0.3";
colors[1] = "0.6 0.6 0.6 0.3";
colors[2] = "0.6 0.6 0.6 0.0";
sizes[0] = 1.6;
sizes[1] = 2.0;
sizes[2] = 2.4;
times[0] = 0.0;
times[1] = 0.7;
times[2] = 1.0;
};
datablock ParticleEmitterData(GrenadeExpDustEmitter)
{
ejectionPeriodMS = 1;
periodVarianceMS = 0;
ejectionVelocity = 15;
velocityVariance = 0.0;
ejectionOffset = 0.0;
thetaMin = 85;
thetaMax = 85;
phiReferenceVel = 0;
phiVariance = 360;
overrideAdvances = false;
lifetimeMS = 200;
particles = "GrenadeExpDust";
};
datablock ParticleData(GrenadeExpSpark)
{
textureName = "art/shapes/particles/ricochet";
dragCoefficient = 1;
gravityCoefficient = 0.0;
inheritedVelFactor = 0.2;
constantAcceleration = 0.0;
lifetimeMS = 500;
lifetimeVarianceMS = 250;
colors[0] = "0.6 0.4 0.3 1";
colors[1] = "0.6 0.4 0.3 1";
colors[2] = "1.0 0.4 0.3 0";
sizes[0] = 0.5;
sizes[1] = 0.75;
sizes[2] = 1;
times[0] = 0;
times[1] = 0.5;
times[2] = 1;
};
datablock ParticleEmitterData(GrenadeExpSparkEmitter)
{
ejectionPeriodMS = 2;
periodVarianceMS = 0;
ejectionVelocity = 20;
velocityVariance = 10;
ejectionOffset = 0.0;
thetaMin = 0;
thetaMax = 120;
phiReferenceVel = 0;
phiVariance = 360;
overrideAdvances = false;
orientParticles = true;
lifetimeMS = 100;
particles = "GrenadeExpSpark";
};
datablock ParticleData(GrenadeExpSparks)
{
textureName = "art/shapes/particles/droplet";
dragCoefficient = 1;
gravityCoefficient = 0.0;
inheritedVelFactor = 0.2;
constantAcceleration = 0.0;
lifetimeMS = 500;
lifetimeVarianceMS = 350;
colors[0] = "0.6 0.4 0.3 1.0";
colors[1] = "0.6 0.4 0.3 0.6";
colors[2] = "1.0 0.4 0.3 0.0";
sizes[0] = 0.5;
sizes[1] = 0.5;
sizes[2] = 0.75;
times[0] = 0.0;
times[1] = 0.5;
times[2] = 1.0;
};
datablock ParticleEmitterData(GrenadeExpSparksEmitter)
{
ejectionPeriodMS = 2;
periodVarianceMS = 0;
ejectionVelocity = 12;
velocityVariance = 6.75;
ejectionOffset = 0.0;
thetaMin = 0;
thetaMax = 60;
phiReferenceVel = 0;
phiVariance = 360;
overrideAdvances = false;
orientParticles = true;
lifetimeMS = 100;
particles = "GrenadeExpSparks";
};
datablock ParticleData(GrenadeExpSmoke)
{
textureName = "art/shapes/particles/smoke";
dragCoeffiecient = 0;
gravityCoefficient = -0.40293;
inheritedVelFactor = 0.0;
constantAcceleration = 0.0;
lifetimeMS = 800;
lifetimeVarianceMS = 299;
useInvAlpha = true;
spinSpeed = 1;
spinRandomMin = -80.0;
spinRandomMax = 0;
colors[0] = "0.8 0.8 0.8 0.4";
colors[1] = "0.5 0.5 0.5 0.5";
colors[2] = "0.75 0.75 0.75 0";
sizes[0] = 4.49857;
sizes[1] = 7.49863;
sizes[2] = 11.2495;
times[0] = 0;
times[1] = 0.498039;
times[2] = 1;
animTexName = "art/shapes/particles/smoke";
times[3] = "1";
};
datablock ParticleEmitterData(GrenadeExpSmokeEmitter)
{
ejectionPeriodMS = 15;
periodVarianceMS = 5;
ejectionVelocity = 2.4;
velocityVariance = 1.2;
thetaMin = 0.0;
thetaMax = 180.0;
ejectionOffset = 1;
particles = "GrenadeExpSmoke";
};
// ----------------------------------------------------------------------------
// Water Explosion
// ----------------------------------------------------------------------------
datablock ParticleData(GLWaterExpDust)
{
textureName = "art/shapes/particles/steam";
dragCoefficient = 1.0;
gravityCoefficient = -0.01;
inheritedVelFactor = 0.0;
constantAcceleration = 0.0;
lifetimeMS = 2500;
lifetimeVarianceMS = 250;
useInvAlpha = false;
spinSpeed = 1;
spinRandomMin = -90.0;
spinRandomMax = 500.0;
colors[0] = "0.6 0.6 1.0 0.5";
colors[1] = "0.6 0.6 1.0 0.3";
sizes[0] = 0.25;
sizes[1] = 1.5;
times[0] = 0.0;
times[1] = 1.0;
};
datablock ParticleEmitterData(GLWaterExpDustEmitter)
{
ejectionPeriodMS = 1;
periodVarianceMS = 0;
ejectionVelocity = 10;
velocityVariance = 0.0;
ejectionOffset = 0.0;
thetaMin = 85;
thetaMax = 85;
phiReferenceVel = 0;
phiVariance = 360;
overrideAdvances = false;
lifetimeMS = 75;
particles = "GLWaterExpDust";
};
datablock ParticleData(GLWaterExpSparks)
{
textureName = "art/shapes/particles/spark_wet";
dragCoefficient = 1;
gravityCoefficient = 0.0;
inheritedVelFactor = 0.2;
constantAcceleration = 0.0;
lifetimeMS = 500;
lifetimeVarianceMS = 250;
colors[0] = "0.6 0.6 1.0 1.0";
colors[1] = "0.6 0.6 1.0 1.0";
colors[2] = "0.6 0.6 1.0 0.0";
sizes[0] = 0.5;
sizes[1] = 0.5;
sizes[2] = 0.75;
times[0] = 0.0;
times[1] = 0.5;
times[2] = 1.0;
};
datablock ParticleEmitterData(GLWaterExpSparkEmitter)
{
ejectionPeriodMS = 2;
periodVarianceMS = 0;
ejectionVelocity = 12;
velocityVariance = 6.75;
ejectionOffset = 0.0;
thetaMin = 0;
thetaMax = 60;
phiReferenceVel = 0;
phiVariance = 360;
overrideAdvances = false;
orientParticles = true;
lifetimeMS = 100;
particles = "GLWaterExpSparks";
};
datablock ParticleData(GLWaterExpSmoke)
{
textureName = "art/shapes/particles/smoke";
dragCoeffiecient = 0.4;
gravityCoefficient = -0.25;
inheritedVelFactor = 0.025;
constantAcceleration = -1.1;
lifetimeMS = 1250;
lifetimeVarianceMS = 0;
useInvAlpha = false;
spinSpeed = 1;
spinRandomMin = -200.0;
spinRandomMax = 200.0;
colors[0] = "0.1 0.1 1.0 1.0";
colors[1] = "0.4 0.4 1.0 1.0";
colors[2] = "0.4 0.4 1.0 0.0";
sizes[0] = 2.0;
sizes[1] = 6.0;
sizes[2] = 2.0;
times[0] = 0.0;
times[1] = 0.5;
times[2] = 1.0;
};
datablock ParticleEmitterData(GLWaterExpSmokeEmitter)
{
ejectionPeriodMS = 15;
periodVarianceMS = 0;
ejectionVelocity = 6.25;
velocityVariance = 0.25;
thetaMin = 0.0;
thetaMax = 90.0;
lifetimeMS = 250;
particles = "GLWaterExpSmoke";
};
datablock ParticleData(GLWaterExpBubbles)
{
textureName = "art/shapes/particles/millsplash01";
dragCoefficient = 0.0;
gravityCoefficient = -0.05;
inheritedVelFactor = 0.0;
constantAcceleration = 0.0;
lifetimeMS = 1500;
lifetimeVarianceMS = 250;
useInvAlpha = false;
spinRandomMin = -100.0;
spinRandomMax = 100.0;
spinSpeed = 1;
colors[0] = "0.7 0.8 1.0 0.0";
colors[1] = "0.7 0.8 1.0 0.4";
colors[2] = "0.7 0.8 1.0 0.0";
sizes[0] = 0.2;
sizes[1] = 0.4;
sizes[2] = 0.8;
times[0] = 0.0;
times[1] = 0.5;
times[2] = 1.0;
};
datablock ParticleEmitterData(GLWaterExpBubbleEmitter)
{
ejectionPeriodMS = 5;
periodVarianceMS = 0;
ejectionVelocity = 1.0;
ejectionOffset = 3.0;
velocityVariance = 0.5;
thetaMin = 0;
thetaMax = 80;
phiReferenceVel = 0;
phiVariance = 360;
overrideAdvances = false;
particles = "GLWaterExpBubbles";
};
datablock ExplosionData(GrenadeLauncherWaterExplosion)
{
//soundProfile = GLWaterExplosionSound;
emitter[0] = GLWaterExpDustEmitter;
emitter[1] = GLWaterExpSparkEmitter;
emitter[2] = GLWaterExpSmokeEmitter;
emitter[3] = GLWaterExpBubbleEmitter;
shakeCamera = true;
camShakeFreq = "10.0 11.0 9.0";
camShakeAmp = "20.0 20.0 20.0";
camShakeDuration = 1.5;
camShakeRadius = 20.0;
lightStartRadius = 20.0;
lightEndRadius = 0.0;
lightStartColor = "0.9 0.9 0.8";
lightEndColor = "0.6 0.6 1.0";
lightStartBrightness = 2.0;
lightEndBrightness = 0.0;
};
// ----------------------------------------------------------------------------
// Dry/Air Explosion Objects
// ----------------------------------------------------------------------------
datablock ExplosionData(GrenadeSubExplosion)
{
offset = 0.25;
emitter[0] = GrenadeExpSparkEmitter;
lightStartRadius = 4.0;
lightEndRadius = 0.0;
lightStartColor = "0.9 0.7 0.7";
lightEndColor = "0.9 0.7 0.7";
lightStartBrightness = 2.0;
lightEndBrightness = 0.0;
};
datablock ExplosionData(GrenadeLauncherExplosion)
{
soundProfile = GrenadeLauncherExplosionSound;
lifeTimeMS = 400; // Quick flash, short burn, and moderate dispersal
// Volume particles
particleEmitter = GrenadeExpFireEmitter;
particleDensity = 75;
particleRadius = 2.25;
// Point emission
emitter[0] = GrenadeExpDustEmitter;
emitter[1] = GrenadeExpSparksEmitter;
emitter[2] = GrenadeExpSmokeEmitter;
// Sub explosion objects
subExplosion[0] = GrenadeSubExplosion;
// Camera Shaking
shakeCamera = true;
camShakeFreq = "10.0 11.0 9.0";
camShakeAmp = "15.0 15.0 15.0";
camShakeDuration = 1.5;
camShakeRadius = 20;
// Exploding debris
debris = GrenadeDebris;
debrisThetaMin = 10;
debrisThetaMax = 60;
debrisNum = 4;
debrisNumVariance = 2;
debrisVelocity = 25;
debrisVelocityVariance = 5;
lightStartRadius = 4.0;
lightEndRadius = 0.0;
lightStartColor = "1.0 1.0 1.0";
lightEndColor = "1.0 1.0 1.0";
lightStartBrightness = 4.0;
lightEndBrightness = 0.0;
lightNormalOffset = 2.0;
};
// ----------------------------------------------------------------------------
// Underwater Grenade projectile trail
// ----------------------------------------------------------------------------
datablock ParticleData(GrenadeTrailWaterParticle)
{
textureName = "art/shapes/particles/bubble";
dragCoefficient = 0.0;
gravityCoefficient = 0.1;
inheritedVelFactor = 0.0;
constantAcceleration = 0.0;
lifetimeMS = 1500;
lifetimeVarianceMS = 600;
useInvAlpha = false;
spinRandomMin = -100.0;
spinRandomMax = 100.0;
spinSpeed = 1;
colors[0] = "0.7 0.8 1.0 1.0";
colors[1] = "0.7 0.8 1.0 0.4";
colors[2] = "0.7 0.8 1.0 0.0";
sizes[0] = 0.05;
sizes[1] = 0.05;
sizes[2] = 0.05;
times[0] = 0.0;
times[1] = 0.5;
times[2] = 1.0;
};
datablock ParticleEmitterData(GrenadeTrailWaterEmitter)
{
ejectionPeriodMS = 5;
periodVarianceMS = 0;
ejectionVelocity = 1.0;
ejectionOffset = 0.1;
velocityVariance = 0.5;
thetaMin = 0.0;
thetaMax = 80.0;
phiReferenceVel = 0;
phiVariance = 360;
overrideAdvances = false;
particles = GrenadeTrailWaterParticle;
};
// ----------------------------------------------------------------------------
// Normal-fire Projectile Object
// ----------------------------------------------------------------------------
datablock ParticleData(GrenadeProjSmokeTrail)
{
textureName = "art/shapes/particles/smoke";
dragCoeffiecient = 0.0;
gravityCoefficient = -0.2;
inheritedVelFactor = 0.0;
constantAcceleration = 0.0;
lifetimeMS = 750;
lifetimeVarianceMS = 250;
useInvAlpha = true;
spinRandomMin = -60;
spinRandomMax = 60;
spinSpeed = 1;
colors[0] = "0.9 0.8 0.8 0.6";
colors[1] = "0.6 0.6 0.6 0.9";
colors[2] = "0.3 0.3 0.3 0";
sizes[0] = 0.25;
sizes[1] = 0.5;
sizes[2] = 0.75;
times[0] = 0.0;
times[1] = 0.4;
times[2] = 1.0;
};
datablock ParticleEmitterData(GrenadeProjSmokeTrailEmitter)
{
ejectionPeriodMS = 10;
periodVarianceMS = 0;
ejectionVelocity = 0.75;
velocityVariance = 0;
thetaMin = 0.0;
thetaMax = 0.0;
phiReferenceVel = 90;
phiVariance = 0;
particles = "GrenadeProjSmokeTrail";
};
datablock ProjectileData(GrenadeLauncherProjectile)
{
projectileShapeName = "art/shapes/weapons/SwarmGun/rocket.dts";
directDamage = 30;
radiusDamage = 30;
damageRadius = 5;
areaImpulse = 2000;
explosion = GrenadeLauncherExplosion;
waterExplosion = GrenadeLauncherWaterExplosion;
decal = ScorchRXDecal;
splash = GrenadeSplash;
particleEmitter = GrenadeProjSmokeTrailEmitter;
particleWaterEmitter = GrenadeTrailWaterEmitter;
muzzleVelocity = 30;
velInheritFactor = 0.3;
armingDelay = 2000;
lifetime = 10000;
fadeDelay = 4500;
bounceElasticity = 0.4;
bounceFriction = 0.3;
isBallistic = true;
gravityMod = 0.9;
lightDesc = GrenadeLauncherLightDesc;
damageType = "GrenadeDamage";
};
// ----------------------------------------------------------------------------
// Underwater Projectile
// ----------------------------------------------------------------------------
datablock ProjectileData(GrenadeWetProjectile)
{
projectileShapeName = "art/shapes/weapons/SwarmGun/rocket.dts";
directDamage = 20;
radiusDamage = 10;
damageRadius = 10;
areaImpulse = 2000;
explosion = GrenadeLauncherWaterExplosion;
particleEmitter = GrenadeProjSmokeTrailEmitter;
particleWaterEmitter = GrenadeTrailWaterEmitter;
muzzleVelocity = 10;
velInheritFactor = 0.3;
armingDelay = 2000;
lifetime = 10000;
fadeDelay = 4500;
bounceElasticity = 0.2;
bounceFriction = 0.4;
isBallistic = true;
gravityMod = 0.80;
lightDesc = GrenadeLauncherWaterLightDesc;
damageType = "GrenadeDamage";
};
// ----------------------------------------------------------------------------
// The manually detonated grenade Item that we will blow up.
// ----------------------------------------------------------------------------
datablock ItemData(Detonade)
{
shapeFile = "art/shapes/weapons/SwarmGun/rocket.dts";
mass = 0.1;
elasticity = 0.1;
friction = 0.9;
rotate = true;
pickupRadius = 0;
maxDamage = 1.5;
destroyedLevel = 1.5;
explosion = GrenadeLauncherExplosion;
underwaterExplosion = GrenadeLauncherWaterExplosion;
};
// ----------------------------------------------------------------------------
// Shell that's ejected during reload.
// ----------------------------------------------------------------------------
datablock DebrisData(GrenadeLauncherShellCasing)
{
shapeFile = "art/shapes/weapons/SwarmGun/rocket.dts";
lifetime = 6.0;
minSpinSpeed = 300.0;
maxSpinSpeed = 400.0;
elasticity = 0.65;
friction = 0.05;
numBounces = 5;
staticOnMaxBounce = true;
snapOnMaxBounce = false;
fade = true;
};
// ----------------------------------------------------------------------------
// Ammo Item
// ----------------------------------------------------------------------------
datablock ItemData(GrenadeLauncherAmmo)
{
// Mission editor category
category = "Ammo";
// Add the Ammo namespace as a parent. The ammo namespace provides
// common ammo related functions and hooks into the inventory system.
className = "Ammo";
// Basic Item properties
shapeFile = "art/shapes/weapons/ramrifle/debris.dts";
mass = 2;
elasticity = 0.2;
friction = 0.6;
// Dynamic properties defined by the scripts
pickUpName = "Grenades";
maxInventory = 20;
};
// ----------------------------------------------------------------------------
// Weapon Item. This is the item that exists in the world,
// i.e. when it's been dropped, thrown or is acting as re-spawnable item.
// When the weapon is mounted onto a shape, the Image is used.
// ----------------------------------------------------------------------------
datablock ItemData(GrenadeLauncher)
{
// Mission editor category
category = "Weapon";
// Hook into Item Weapon class hierarchy. The weapon namespace
// provides common weapon handling functions in addition to hooks
// into the inventory system.
className = "Weapon";
// Basic Item properties
shapefile = "art/shapes/weapons/ramrifle/base.dts";
mass = 5;
elasticity = 0.2;
friction = 0.6;
emap = true;
// Dynamic properties defined by the scripts
pickUpName = "a RamRifle";
description = "grenade launcher";
image = GrenadeLauncherImage;
// weaponHUD
previewImage = 'ramrifle.png';
reticle = 'reticle_ramrifle';
};
// ----------------------------------------------------------------------------
// Image which does all the work. Images do not normally exist in
// the world, they can only be mounted on ShapeBase objects.
// ----------------------------------------------------------------------------
datablock ShapeBaseImageData(GrenadeLauncherImage)
{
// Basic Item properties
shapefile = "art/shapes/weapons/ramrifle/base.dts";
emap = true;
// Specify mount point & offset for 3rd person, and eye offset
// for first person rendering.
mountPoint = 0;
offset = "0.0 0.0 0.1";//"0.0 0.085 0.09";
//rotation = "1 0 0 -20";
eyeOffset = "0.25 0.4 -0.4"; // 0.25=right/left 0.5=forward/backward, -0.5=up/down
// When firing from a point offset from the eye, muzzle correction
// will adjust the muzzle vector to point to the eye LOS point.
// Since this weapon doesn't actually fire from the muzzle point,
// we need to turn this off.
correctMuzzleVector = false;
// Add the WeaponImage namespace as a parent, WeaponImage namespace
// provides some hooks into the inventory system.
className = "WeaponImage";
// Projectile && Ammo.
item = GrenadeLauncher;
ammo = GrenadeLauncherAmmo;
projectile = GrenadeLauncherProjectile;
wetProjectile = GrenadeWetProjectile;
projectileType = Projectile;
// shell casings
casing = GrenadeLauncherShellCasing;
shellExitDir = "1.0 0.3 1.0";
shellExitOffset = "0.15 -0.56 -0.1";
shellExitVariance = 15.0;
shellVelocity = 3.0;
// Let there be light - NoLight, ConstantLight, PulsingLight, WeaponFireLight.
lightType = "WeaponFireLight";
lightColor = "1.0 1.0 0.9";
lightDuration = 200;
lightRadius = 20;
// Images have a state system which controls how the animations
// are run, which sounds are played, script callbacks, etc. This
// state system is downloaded to the client so that clients can
// predict state changes and animate accordingly. The following
// system supports basic ready->fire->reload transitions as
// well as a no-ammo->dryfire idle state.
// Initial start up state
stateName[0] = "Preactivate";
stateTransitionOnLoaded[0] = "Activate";
stateTransitionOnNoAmmo[0] = "NoAmmo";
// Activating the gun.
// Called when the weapon is first mounted and there is ammo.
stateName[1] = "Activate";
stateTransitionOnTimeout[1] = "Ready";
stateTimeoutValue[1] = 0.6;
stateSequence[1] = "Activate";
// Ready to fire, just waiting for the trigger
stateName[2] = "Ready";
stateTransitionOnNoAmmo[2] = "NoAmmo";
stateTransitionOnTriggerDown[2] = "CheckWet";
//stateTransitionOnAltTriggerDown[2] = "CheckWetAlt";
stateSequence[2] = "Ready";
// Fire the weapon. Calls the fire script which does the actual work.
stateName[3] = "Fire";
stateTransitionOnTimeout[3] = "PostFire";
stateTimeoutValue[3] = 0.4;
stateFire[3] = true;
stateRecoil[3] = LightRecoil;
stateAllowImageChange[3] = false;
stateSequence[3] = "Fire";
stateScript[3] = "onFire";
stateSound[3] = GrenadeLauncherFireSound;
// Check ammo
stateName[4] = "PostFire";
stateTransitionOnAmmo[4] = "Reload";
stateTransitionOnNoAmmo[4] = "NoAmmo";
// Play the reload animation, and transition into
stateName[5] = "Reload";
stateTransitionOnTimeout[5] = "Ready";
stateTimeoutValue[5] = 0.2;
stateAllowImageChange[5] = false;
stateSequence[5] = "Reload";
stateEjectShell[5] = false; // set to true to enable shell casing eject
stateSound[5] = GrenadeLauncherReloadSound;
// No ammo in the weapon, just idle until something shows up.
// Play the dry fire sound if the trigger iS pulled.
stateName[6] = "NoAmmo";
stateTransitionOnAmmo[6] = "Reload";
stateSequence[6] = "NoAmmo";
stateTransitionOnTriggerDown[6] = "DryFire";
// No ammo dry fire
stateName[7] = "DryFire";
stateTimeoutValue[7] = 1.0;
stateTransitionOnTimeout[7] = "NoAmmo";
stateSound[7] = GrenadeLauncherFireEmptySound;
// Check if wet
stateName[8] = "CheckWet";
stateTransitionOnWet[8] = "WetFire";
stateTransitionOnNotWet[8] = "Fire";
// Check if alt wet
stateName[9] = "CheckWetAlt";
stateTransitionOnWet[9] = "WetFire";
stateTransitionOnNotWet[9] = "AltFire";
// Wet fire
stateName[10] = "WetFire";
stateTransitionOnTimeout[10] = "PostFire";
stateTimeoutValue[10] = 0.4;
stateFire[10] = true;
stateRecoil[10] = LightRecoil;
stateAllowImageChange[10] = false;
stateSequence[10] = "Fire";
stateScript[10] = "onWetFire";
stateSound[10] = GrenadeLauncherFireSound;
// Alt-fire for the weapon. Calls the alt-fire script to do the actual work.
stateName[11] = "altFire";
stateTransitionOnTimeout[11] = "PostFire";
stateTimeoutValue[11] = 0.4;
stateFire[11] = true;
stateRecoil[11] = LightRecoil;
stateAllowImageChange[11] = false;
stateSequence[11] = "Fire";
stateScript[11] = "onAltFire";
stateSound[11] = GrenadeLauncherFireSound;
};
| |
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Backoffice_Registrasi_LABAddBaru : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Session["SIMRS.UserId"] == null)
{
Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx");
}
int UserId = (int)Session["SIMRS.UserId"];
if (Session["RegistrasiLAB"] == null)
{
Response.Redirect(Request.ApplicationPath + "/Backoffice/UnAuthorize.aspx");
}
btnSave.Text = "<center><img alt=\"" + Resources.GetString("", "Save") + "\" src=\"" + Request.ApplicationPath + "/images/save_f2.gif\" align=\"middle\" border=\"0\" name=\"save\" value=\"save\"><center>";
btnCancel.Text = "<center><img alt=\"" + Resources.GetString("", "Cancel") + "\" src=\"" + Request.ApplicationPath + "/images/cancel_f2.gif\" align=\"middle\" border=\"0\" name=\"cancel\" value=\"cancel\"><center>";
GetListStatus();
GetListStatusPerkawinan();
GetListAgama();
GetListPendidikan();
GetListJenisPenjamin();
GetListHubungan();
txtTanggalRegistrasi.Text = DateTime.Now.ToString("dd/MM/yyyy");
GetNomorRegistrasi();
GetNomorTunggu();
GetListKelompokPemeriksaan();
GetListSatuanKerja();
GetListSatuanKerjaPenjamin();
}
}
public void GetListStatus()
{
string StatusId = "";
SIMRS.DataAccess.RS_Status myObj = new SIMRS.DataAccess.RS_Status();
DataTable dt = myObj.GetList();
cmbStatusPasien.Items.Clear();
int i = 0;
cmbStatusPasien.Items.Add("");
cmbStatusPasien.Items[i].Text = "";
cmbStatusPasien.Items[i].Value = "";
cmbStatusPenjamin.Items.Add("");
cmbStatusPenjamin.Items[i].Text = "";
cmbStatusPenjamin.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbStatusPasien.Items.Add("");
cmbStatusPasien.Items[i].Text = dr["Nama"].ToString();
cmbStatusPasien.Items[i].Value = dr["Id"].ToString();
cmbStatusPenjamin.Items.Add("");
cmbStatusPenjamin.Items[i].Text = dr["Nama"].ToString();
cmbStatusPenjamin.Items[i].Value = dr["Id"].ToString();
if (dr["Id"].ToString() == StatusId)
{
cmbStatusPasien.SelectedIndex = i;
cmbStatusPenjamin.SelectedIndex = i;
}
i++;
}
}
public void GetListPangkatPasien()
{
string PangkatId = "";
SIMRS.DataAccess.RS_Pangkat myObj = new SIMRS.DataAccess.RS_Pangkat();
if (cmbStatusPasien.SelectedIndex > 0)
myObj.StatusId = int.Parse(cmbStatusPasien.SelectedItem.Value);
DataTable dt = myObj.GetListByStatusId();
cmbPangkatPasien.Items.Clear();
int i = 0;
cmbPangkatPasien.Items.Add("");
cmbPangkatPasien.Items[i].Text = "";
cmbPangkatPasien.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbPangkatPasien.Items.Add("");
cmbPangkatPasien.Items[i].Text = dr["Nama"].ToString();
cmbPangkatPasien.Items[i].Value = dr["Id"].ToString();
if (dr["Id"].ToString() == PangkatId)
{
cmbPangkatPasien.SelectedIndex = i;
}
i++;
}
}
public void GetListPangkatPenjamin()
{
string PangkatId = "";
SIMRS.DataAccess.RS_Pangkat myObj = new SIMRS.DataAccess.RS_Pangkat();
if (cmbStatusPenjamin.SelectedIndex > 0)
myObj.StatusId = int.Parse(cmbStatusPenjamin.SelectedItem.Value);
DataTable dt = myObj.GetListByStatusId();
cmbPangkatPenjamin.Items.Clear();
int i = 0;
cmbPangkatPenjamin.Items.Add("");
cmbPangkatPenjamin.Items[i].Text = "";
cmbPangkatPenjamin.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbPangkatPenjamin.Items.Add("");
cmbPangkatPenjamin.Items[i].Text = dr["Nama"].ToString();
cmbPangkatPenjamin.Items[i].Value = dr["Id"].ToString();
if (dr["Id"].ToString() == PangkatId)
{
cmbPangkatPenjamin.SelectedIndex = i;
}
i++;
}
}
public void GetNomorTunggu()
{
SIMRS.DataAccess.RS_RawatJalan myObj = new SIMRS.DataAccess.RS_RawatJalan();
myObj.PoliklinikId = 42; // LAB
myObj.TanggalBerobat = DateTime.Parse(txtTanggalRegistrasi.Text);
txtNomorTunggu.Text = myObj.GetNomorTunggu().ToString();
}
public void GetListStatusPerkawinan()
{
string StatusPerkawinanId = "";
BkNet.DataAccess.StatusPerkawinan myObj = new BkNet.DataAccess.StatusPerkawinan();
DataTable dt = myObj.GetList();
cmbStatusPerkawinan.Items.Clear();
int i = 0;
cmbStatusPerkawinan.Items.Add("");
cmbStatusPerkawinan.Items[i].Text = "";
cmbStatusPerkawinan.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbStatusPerkawinan.Items.Add("");
cmbStatusPerkawinan.Items[i].Text = dr["Nama"].ToString();
cmbStatusPerkawinan.Items[i].Value = dr["Id"].ToString();
if (dr["Id"].ToString() == StatusPerkawinanId)
cmbStatusPerkawinan.SelectedIndex = i;
i++;
}
}
public void GetListAgama()
{
string AgamaId = "";
BkNet.DataAccess.Agama myObj = new BkNet.DataAccess.Agama();
DataTable dt = myObj.GetList();
cmbAgama.Items.Clear();
int i = 0;
cmbAgama.Items.Add("");
cmbAgama.Items[i].Text = "";
cmbAgama.Items[i].Value = "";
cmbAgamaPenjamin.Items.Add("");
cmbAgamaPenjamin.Items[i].Text = "";
cmbAgamaPenjamin.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbAgama.Items.Add("");
cmbAgama.Items[i].Text = dr["Nama"].ToString();
cmbAgama.Items[i].Value = dr["Id"].ToString();
cmbAgamaPenjamin.Items.Add("");
cmbAgamaPenjamin.Items[i].Text = dr["Nama"].ToString();
cmbAgamaPenjamin.Items[i].Value = dr["Id"].ToString();
if (dr["Id"].ToString() == AgamaId)
cmbAgama.SelectedIndex = i;
i++;
}
}
public void GetListPendidikan()
{
string PendidikanId = "";
BkNet.DataAccess.Pendidikan myObj = new BkNet.DataAccess.Pendidikan();
DataTable dt = myObj.GetList();
cmbPendidikan.Items.Clear();
int i = 0;
cmbPendidikan.Items.Add("");
cmbPendidikan.Items[i].Text = "";
cmbPendidikan.Items[i].Value = "";
cmbPendidikanPenjamin.Items.Add("");
cmbPendidikanPenjamin.Items[i].Text = "";
cmbPendidikanPenjamin.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbPendidikan.Items.Add("");
cmbPendidikan.Items[i].Text = "[" + dr["Kode"].ToString() + "] " + dr["Nama"].ToString();
cmbPendidikan.Items[i].Value = dr["Id"].ToString();
cmbPendidikanPenjamin.Items.Add("");
cmbPendidikanPenjamin.Items[i].Text = "[" + dr["Kode"].ToString() + "] " + dr["Nama"].ToString();
cmbPendidikanPenjamin.Items[i].Value = dr["Id"].ToString();
if (dr["Id"].ToString() == PendidikanId)
cmbPendidikan.SelectedIndex = i;
i++;
}
}
public void GetListJenisPenjamin()
{
string JenisPenjaminId = "";
SIMRS.DataAccess.RS_JenisPenjamin myObj = new SIMRS.DataAccess.RS_JenisPenjamin();
DataTable dt = myObj.GetList();
cmbJenisPenjamin.Items.Clear();
int i = 0;
foreach (DataRow dr in dt.Rows)
{
cmbJenisPenjamin.Items.Add("");
cmbJenisPenjamin.Items[i].Text = dr["Nama"].ToString();
cmbJenisPenjamin.Items[i].Value = dr["Id"].ToString();
if (dr["Id"].ToString() == JenisPenjaminId)
cmbJenisPenjamin.SelectedIndex = i;
i++;
}
}
public void GetListHubungan()
{
string HubunganId = "";
SIMRS.DataAccess.RS_Hubungan myObj = new SIMRS.DataAccess.RS_Hubungan();
DataTable dt = myObj.GetList();
cmbHubungan.Items.Clear();
int i = 0;
cmbHubungan.Items.Add("");
cmbHubungan.Items[i].Text = "";
cmbHubungan.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbHubungan.Items.Add("");
cmbHubungan.Items[i].Text = dr["Nama"].ToString();
cmbHubungan.Items[i].Value = dr["Id"].ToString();
if (dr["Id"].ToString() == HubunganId)
cmbHubungan.SelectedIndex = i;
i++;
}
}
public void GetNomorRegistrasi()
{
SIMRS.DataAccess.RS_RawatJalan myObj = new SIMRS.DataAccess.RS_RawatJalan();
myObj.PoliklinikId = 42;//LAB
myObj.TanggalBerobat = DateTime.Parse(txtTanggalRegistrasi.Text);
txtNoRegistrasi.Text = myObj.GetNomorRegistrasi();
}
public void GetListKelompokPemeriksaan()
{
SIMRS.DataAccess.RS_KelompokPemeriksaan myObj = new SIMRS.DataAccess.RS_KelompokPemeriksaan();
myObj.JenisPemeriksaanId = 1;//Laboratorium
DataTable dt = myObj.GetListByJenisPemeriksaanId();
cmbKelompokPemeriksaan.Items.Clear();
int i = 0;
//cmbKelompokPemeriksaan.Items.Add("");
//cmbKelompokPemeriksaan.Items[i].Text = "";
//cmbKelompokPemeriksaan.Items[i].Value = "";
//i++;
foreach (DataRow dr in dt.Rows)
{
cmbKelompokPemeriksaan.Items.Add("");
cmbKelompokPemeriksaan.Items[i].Text = dr["Nama"].ToString();
cmbKelompokPemeriksaan.Items[i].Value = dr["Id"].ToString();
i++;
}
cmbKelompokPemeriksaan.SelectedIndex = 0;
GetListPemeriksaan();
}
public DataSet GetDataPemeriksaan()
{
DataSet ds = new DataSet();
if (Session["dsLayananLAB"] != null)
ds = (DataSet)Session["dsLayananLAB"];
else
{
SIMRS.DataAccess.RS_Layanan myObj = new SIMRS.DataAccess.RS_Layanan();
myObj.PoliklinikId = 42;//Polklinik LAB
DataTable myData = myObj.SelectAllWPoliklinikIdLogic();
ds.Tables.Add(myData);
Session.Add("dsLayananLAB", ds);
}
return ds;
}
public void GetListPemeriksaan()
{
DataSet ds = new DataSet();
ds = GetDataPemeriksaan();
lstRefPemeriksaan.DataTextField = "Nama";
lstRefPemeriksaan.DataValueField = "Id";
//lstRefPemeriksaan.DataSource = ds.Tables[0].DefaultView;
//lstRefPemeriksaan.DataBind();
DataView dv = ds.Tables[0].DefaultView;
dv.RowFilter = " KelompokPemeriksaanId = " + cmbKelompokPemeriksaan.SelectedItem.Value;
lstRefPemeriksaan.DataSource = dv;
lstRefPemeriksaan.DataBind();
}
public void OnSave(Object sender, EventArgs e)
{
lblError.Text = "";
if (Session["SIMRS.UserId"] == null)
{
Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx");
}
int UserId = (int)Session["SIMRS.UserId"];
if (!Page.IsValid)
{
return;
}
string noRM1 = txtNoRM.Text.Replace("_","");
string noRM2 = noRM1.Replace(".","");
if (noRM2 == "")
{
lblError.Text = "Nomor Rekam Medis Harus diisi";
return;
}
else if (noRM2.Length < 5)
{
lblError.Text = "Nomor Rekam Medis Harus diisi dengan benar";
return;
}
//if(noRM1.Substring(noRM1.LastIndexOf(".")) == "")
SIMRS.DataAccess.RS_Pasien myPasien = new SIMRS.DataAccess.RS_Pasien();
//txtNoRM.Text = txtNoRM1.Text + "." + txtNoRM2.Text + "." + txtNoRM3.Text;
myPasien.PasienId = 0;
myPasien.NoRM = txtNoRM.Text.Replace("_", "");
myPasien.Nama = txtNama.Text;
if (cmbStatusPasien.SelectedIndex > 0)
myPasien.StatusId = int.Parse(cmbStatusPasien.SelectedItem.Value);
if (cmbPangkatPasien.SelectedIndex > 0)
myPasien.PangkatId = int.Parse(cmbPangkatPasien.SelectedItem.Value);
myPasien.NoAskes = txtNoASKES.Text;
myPasien.NoKTP = txtNoKTP.Text;
myPasien.GolDarah = txtGolDarah.Text;
myPasien.NRP = txtNrpPasien.Text;
myPasien.Jabatan = txtJabatanPasien.Text;
//myPasien.Kesatuan = txtKesatuanPasien.Text;
myPasien.Kesatuan = cmbSatuanKerja.SelectedItem.ToString();
myPasien.AlamatKesatuan = txtAlamatKesatuanPasien.Text;
myPasien.TempatLahir = txtTempatLahir.Text;
if (txtTanggalLahir.Text != "")
myPasien.TanggalLahir = DateTime.Parse(txtTanggalLahir.Text);
myPasien.Alamat = txtAlamatPasien.Text;
myPasien.Telepon = txtTeleponPasien.Text;
if (cmbJenisKelamin.SelectedIndex > 0)
myPasien.JenisKelamin = cmbJenisKelamin.SelectedItem.Value;
if (cmbStatusPerkawinan.SelectedIndex > 0)
myPasien.StatusPerkawinanId = int.Parse(cmbStatusPerkawinan.SelectedItem.Value);
if (cmbAgama.SelectedIndex > 0)
myPasien.AgamaId = int.Parse(cmbAgama.SelectedItem.Value);
if (cmbPendidikan.SelectedIndex > 0)
myPasien.PendidikanId = int.Parse(cmbPendidikan.SelectedItem.Value);
myPasien.Pekerjaan = txtPekerjaan.Text;
myPasien.AlamatKantor = txtAlamatKantorPasien.Text;
myPasien.TeleponKantor = txtTeleponKantorPasien.Text;
myPasien.Keterangan = txtKeteranganPasien.Text;
myPasien.CreatedBy = UserId;
myPasien.CreatedDate = DateTime.Now;
if (myPasien.IsExist())
{
lblError.Text = myPasien.ErrorMessage.ToString();
return;
}
else
{
myPasien.Insert();
int PenjaminId = 0;
if (cmbJenisPenjamin.SelectedIndex > 0)
{
//Input Data Penjamin
SIMRS.DataAccess.RS_Penjamin myPenj = new SIMRS.DataAccess.RS_Penjamin();
myPenj.PenjaminId = 0;
if (cmbJenisPenjamin.SelectedIndex == 1)
{
myPenj.Nama = txtNamaPenjamin.Text;
if (cmbHubungan.SelectedIndex > 0)
myPenj.HubunganId = int.Parse(cmbHubungan.SelectedItem.Value);
myPenj.Umur = txtUmurPenjamin.Text;
myPenj.Alamat = txtAlamatPenjamin.Text;
myPenj.Telepon = txtTeleponPenjamin.Text;
if (cmbAgamaPenjamin.SelectedIndex > 0)
myPenj.AgamaId = int.Parse(cmbAgamaPenjamin.SelectedItem.Value);
if (cmbPendidikanPenjamin.SelectedIndex > 0)
myPenj.PendidikanId = int.Parse(cmbPendidikanPenjamin.SelectedItem.Value);
if (cmbPangkatPenjamin.SelectedIndex > 0)
myPenj.PangkatId = int.Parse(cmbPangkatPenjamin.SelectedItem.Value);
myPenj.NoKTP = txtNoKTPPenjamin.Text;
myPenj.GolDarah = txtGolDarahPenjamin.Text;
myPenj.NRP = txtNRPPenjamin.Text;
//myPenj.Kesatuan = txtKesatuanPenjamin.Text;
myPenj.Kesatuan = cmbSatuanKerjaPenjamin.SelectedItem.ToString();
myPenj.AlamatKesatuan = txtAlamatKesatuanPenjamin.Text;
myPenj.Keterangan = txtKeteranganPenjamin.Text;
}
else
{
myPenj.Nama = txtNamaPerusahaan.Text;
myPenj.NamaKontak = txtNamaKontak.Text;
myPenj.Alamat = txtAlamatPerusahaan.Text;
myPenj.Telepon = txtTeleponPerusahaan.Text;
myPenj.Fax = txtFAXPerusahaan.Text;
}
myPenj.CreatedBy = UserId;
myPenj.CreatedDate = DateTime.Now;
myPenj.Insert();
PenjaminId = (int)myPenj.PenjaminId;
}
//Input Data Registrasi
SIMRS.DataAccess.RS_Registrasi myReg = new SIMRS.DataAccess.RS_Registrasi();
myReg.RegistrasiId = 0;
myReg.PasienId = myPasien.PasienId;
GetNomorRegistrasi();
myReg.NoRegistrasi = txtNoRegistrasi.Text;
myReg.JenisRegistrasiId = 1;
myReg.TanggalRegistrasi = DateTime.Parse(txtTanggalRegistrasi.Text);
myReg.JenisPenjaminId = int.Parse(cmbJenisPenjamin.SelectedItem.Value);
if (PenjaminId != 0)
myReg.PenjaminId = PenjaminId;
myReg.CreatedBy = UserId;
myReg.CreatedDate = DateTime.Now;
myReg.Insert();
//Input Data Rawat Jalan
SIMRS.DataAccess.RS_RawatJalan myRJ = new SIMRS.DataAccess.RS_RawatJalan();
myRJ.RawatJalanId = 0;
myRJ.RegistrasiId = myReg.RegistrasiId;
myRJ.PoliklinikId = 42;// LAB
myRJ.TanggalBerobat = DateTime.Parse(txtTanggalRegistrasi.Text);
GetNomorTunggu();
if (txtNomorTunggu.Text != "" )
myRJ.NomorTunggu = int.Parse(txtNomorTunggu.Text);
myRJ.Status = 0;//Baru daftar
myRJ.CreatedBy = UserId;
myRJ.CreatedDate = DateTime.Now;
myRJ.Insert();
////Input Data Layanan
SIMRS.DataAccess.RS_RJLayanan myLayanan = new SIMRS.DataAccess.RS_RJLayanan();
SIMRS.DataAccess.RS_Layanan myTarif = new SIMRS.DataAccess.RS_Layanan();
if (lstPemeriksaan.Items.Count > 0)
{
string[] kellay;
string[] Namakellay;
DataTable dt;
for (int i = 0; i < lstPemeriksaan.Items.Count; i++)
{
myLayanan.RJLayananId = 0;
myLayanan.RawatJalanId = myRJ.RawatJalanId;
myLayanan.JenisLayananId = 3;
kellay = lstPemeriksaan.Items[i].Value.Split('|');
Namakellay = lstPemeriksaan.Items[i].Text.Split(':');
myLayanan.KelompokLayananId = 2;
myLayanan.LayananId = int.Parse(kellay[1]);
myLayanan.NamaLayanan = Namakellay[1];
myTarif.Id = int.Parse(kellay[1]);
dt = myTarif.GetTarifRIByLayananId(0);
if (dt.Rows.Count > 0)
myLayanan.Tarif = dt.Rows[0]["Tarif"].ToString() != "" ? (Decimal)dt.Rows[0]["Tarif"] : 0;
else
myLayanan.Tarif = 0;
myLayanan.JumlahSatuan = double.Parse("1");
myLayanan.Discount = 0;
myLayanan.BiayaTambahan = 0;
myLayanan.JumlahTagihan = myLayanan.Tarif;
myLayanan.Keterangan = "";
myLayanan.CreatedBy = UserId;
myLayanan.CreatedDate = DateTime.Now;
myLayanan.Insert();
}
}
//=================
string CurrentPage = "";
if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "")
CurrentPage = Request.QueryString["CurrentPage"].ToString();
Response.Redirect("LABView.aspx?CurrentPage=" + CurrentPage + "&RawatJalanId=" + myRJ.RawatJalanId);
}
}
public void OnCancel(Object sender, EventArgs e)
{
string CurrentPage = "";
if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "")
CurrentPage = Request.QueryString["CurrentPage"].ToString();
Response.Redirect("LABList.aspx?CurrentPage=" + CurrentPage);
}
protected void cmbJenisPenjamin_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbJenisPenjamin.SelectedIndex == 1)
{
tblPenjaminKeluarga.Visible = true;
tblPenjaminPerusahaan.Visible = false;
}
else if (cmbJenisPenjamin.SelectedIndex == 2 || cmbJenisPenjamin.SelectedIndex == 3)
{
tblPenjaminKeluarga.Visible = false;
tblPenjaminPerusahaan.Visible = true;
}
else
{
tblPenjaminKeluarga.Visible = false;
tblPenjaminPerusahaan.Visible = false;
}
}
protected void txtTanggalRegistrasi_TextChanged(object sender, EventArgs e)
{
GetNomorTunggu();
GetNomorRegistrasi();
}
protected void cmbStatusPasien_SelectedIndexChanged(object sender, EventArgs e)
{
GetListPangkatPasien();
}
protected void cmbStatusPenjamin_SelectedIndexChanged(object sender, EventArgs e)
{
GetListPangkatPenjamin();
}
protected void cmbKelompokPemeriksaan_SelectedIndexChanged(object sender, EventArgs e)
{
GetListPemeriksaan();
}
protected void btnAddPemeriksaan_Click(object sender, EventArgs e)
{
if (lstRefPemeriksaan.SelectedIndex != -1)
{
int i = lstPemeriksaan.Items.Count;
bool exist = false;
string selectValue =cmbKelompokPemeriksaan.SelectedItem.Value + "|" + lstRefPemeriksaan.SelectedItem.Value;
for (int j = 0; j < i; j++)
{
if (lstPemeriksaan.Items[j].Value == selectValue)
{
exist = true;
break;
}
}
if (!exist)
{
ListItem newItem = new ListItem();
newItem.Text = cmbKelompokPemeriksaan.SelectedItem.Text + ": " + lstRefPemeriksaan.SelectedItem.Text;
newItem.Value = cmbKelompokPemeriksaan.SelectedItem.Value + "|" + lstRefPemeriksaan.SelectedItem.Value;
lstPemeriksaan.Items.Add(newItem);
}
}
}
protected void btnRemovePemeriksaan_Click(object sender, EventArgs e)
{
if (lstPemeriksaan.SelectedIndex != -1)
{
lstPemeriksaan.Items.RemoveAt(lstPemeriksaan.SelectedIndex);
}
}
protected void btnCek_Click(object sender, EventArgs e)
{
SIMRS.DataAccess.RS_Pasien myPasien = new SIMRS.DataAccess.RS_Pasien();
myPasien.NoRM = txtNoRM.Text.Replace("_", "");
if (myPasien.IsExistRM())
{
lblCek.Text = "No.RM sudah terpakai";
return;
}
else
{
lblCek.Text = "No.RM belum terpakai";
return;
}
}
public void GetListSatuanKerja()
{
string SatuanKerjaId = "";
SIMRS.DataAccess.RS_SatuanKerja myObj = new SIMRS.DataAccess.RS_SatuanKerja();
DataTable dt = myObj.GetList();
cmbSatuanKerja.Items.Clear();
int i = 0;
cmbSatuanKerja.Items.Add("");
cmbSatuanKerja.Items[i].Text = "";
cmbSatuanKerja.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbSatuanKerja.Items.Add("");
cmbSatuanKerja.Items[i].Text = dr["NamaSatker"].ToString();
cmbSatuanKerja.Items[i].Value = dr["IdSatuanKerja"].ToString();
if (dr["IdSatuanKerja"].ToString() == SatuanKerjaId)
cmbSatuanKerja.SelectedIndex = i;
i++;
}
}
public void GetListSatuanKerjaPenjamin()
{
string SatuanKerjaId = "";
SIMRS.DataAccess.RS_SatuanKerja myObj = new SIMRS.DataAccess.RS_SatuanKerja();
DataTable dt = myObj.GetList();
cmbSatuanKerjaPenjamin.Items.Clear();
int i = 0;
cmbSatuanKerjaPenjamin.Items.Add("");
cmbSatuanKerjaPenjamin.Items[i].Text = "";
cmbSatuanKerjaPenjamin.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbSatuanKerjaPenjamin.Items.Add("");
cmbSatuanKerjaPenjamin.Items[i].Text = dr["NamaSatker"].ToString();
cmbSatuanKerjaPenjamin.Items[i].Value = dr["IdSatuanKerja"].ToString();
if (dr["IdSatuanKerja"].ToString() == SatuanKerjaId)
cmbSatuanKerjaPenjamin.SelectedIndex = i;
i++;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Windows;
using Microsoft.WindowsAPICodePack.DirectX.Controls;
using Microsoft.WindowsAPICodePack.DirectX.Direct2D1;
using Microsoft.WindowsAPICodePack.DirectX.DirectWrite;
using DWrite = Microsoft.WindowsAPICodePack.DirectX.DirectWrite;
namespace Microsoft.WindowsAPICodePack.Samples
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
D2DFactory d2dFactory;
DWriteFactory dwriteFactory;
HwndRenderTarget renderTarget;
SolidColorBrush blackBrush;
BitmapBrush gridPatternBitmapBrush;
SolidColorBrush solidBrush1;
SolidColorBrush solidBrush2;
SolidColorBrush solidBrush3;
LinearGradientBrush linearGradientBrush;
RadialGradientBrush radialGradientBrush;
TextFormat textFormat;
TextLayout textLayout;
int x1 = 70, x2 = 82, x3 = 25, x4 = 75, x5 = 54;
public Window1()
{
InitializeComponent();
host.Loaded += new RoutedEventHandler(host_Loaded);
host.SizeChanged += new SizeChangedEventHandler(host_SizeChanged);
}
void host_Loaded(object sender, RoutedEventArgs e)
{
// Create the D2D Factory
d2dFactory = D2DFactory.CreateFactory(D2DFactoryType.SingleThreaded);
// Create the DWrite Factory
dwriteFactory = DWriteFactory.CreateFactory();
// Start rendering now!
host.Render = Render;
host.InvalidateVisual();
}
void host_SizeChanged(object sender, SizeChangedEventArgs e)
{
if (renderTarget != null)
{
// Resize the render targrt to the actual host size
renderTarget.Resize(new SizeU((uint)(host.ActualWidth), (uint)(host.ActualHeight)));
}
InvalidateVisual();
}
/// <summary>
/// This method creates the render target and all associated D2D and DWrite resources
/// </summary>
void CreateDeviceResources()
{
// Only calls if resources have not been initialize before
if (renderTarget == null)
{
// The text format
textFormat = dwriteFactory.CreateTextFormat("Bodoni MT", 24, DWrite.FontWeight.Normal, DWrite.FontStyle.Italic, DWrite.FontStretch.Normal);
// Create the render target
SizeU size = new SizeU((uint)host.ActualWidth, (uint)host.ActualHeight);
RenderTargetProperties props = new RenderTargetProperties();
HwndRenderTargetProperties hwndProps = new HwndRenderTargetProperties(host.Handle, size, PresentOptions.None);
renderTarget = d2dFactory.CreateHwndRenderTarget(props, hwndProps);
// A black brush to be used for drawing text
ColorF cf = new ColorF(0, 0, 0, 1);
blackBrush = renderTarget.CreateSolidColorBrush(cf);
// Create a linear gradient.
GradientStop[] stops =
{
new GradientStop(1, new ColorF(1f, 0f, 0f, 0.25f)),
new GradientStop(0, new ColorF(0f, 0f, 1f, 1f))
};
GradientStopCollection pGradientStops = renderTarget.CreateGradientStopCollection(stops, Gamma.Linear, ExtendMode.Wrap);
LinearGradientBrushProperties gradBrushProps = new LinearGradientBrushProperties(new Point2F(50, 25), new Point2F(25, 50));
linearGradientBrush = renderTarget.CreateLinearGradientBrush(gradBrushProps, pGradientStops);
gridPatternBitmapBrush = CreateGridPatternBrush(renderTarget);
solidBrush1 = renderTarget.CreateSolidColorBrush(new ColorF(0.3F, 0.5F, 0.65F, 0.25F));
solidBrush2 = renderTarget.CreateSolidColorBrush(new ColorF(0.0F, 0.0F, 0.65F, 0.5F));
solidBrush3 = renderTarget.CreateSolidColorBrush(new ColorF(0.9F, 0.5F, 0.3F, 0.75F));
// Create a linear gradient.
stops[0] = new GradientStop(1, new ColorF(0f, 0f, 0f, 0.25f));
stops[1] = new GradientStop(0, new ColorF(1f, 1f, 0.2f, 1f));
GradientStopCollection radiantGradientStops = renderTarget.CreateGradientStopCollection(stops, Gamma.Linear, ExtendMode.Wrap);
RadialGradientBrushProperties radialBrushProps = new RadialGradientBrushProperties(new Point2F(25, 25), new Point2F(0, 0), 10, 10);
radialGradientBrush = renderTarget.CreateRadialGradientBrush(radialBrushProps, radiantGradientStops);
}
}
/// <summary>
/// Create the grid pattern (squares) brush
/// </summary>
/// <param name="target"></param>
/// <returns></returns>
BitmapBrush CreateGridPatternBrush(RenderTarget target)
{
// Create a compatible render target.
BitmapRenderTarget compatibleRenderTarget =
target.CreateCompatibleRenderTarget(CompatibleRenderTargetOptions.None, new SizeF(10.0f, 10.0f));
//// Draw a pattern.
SolidColorBrush spGridBrush = compatibleRenderTarget.CreateSolidColorBrush(new ColorF(0.93f, 0.94f, 0.96f, 1.0f));
compatibleRenderTarget.BeginDraw();
compatibleRenderTarget.FillRectangle(new RectF(0.0f, 0.0f, 10.0f, 1.0f), spGridBrush);
compatibleRenderTarget.FillRectangle(new RectF(0.0f, 0.1f, 1.0f, 10.0f), spGridBrush);
compatibleRenderTarget.EndDraw();
//// Retrieve the bitmap from the render target.
D2DBitmap spGridBitmap;
spGridBitmap = compatibleRenderTarget.Bitmap;
//// Choose the tiling mode for the bitmap brush.
BitmapBrushProperties brushProperties = new BitmapBrushProperties(ExtendMode.Wrap, ExtendMode.Wrap, BitmapInterpolationMode.Linear);
//// Create the bitmap brush.
return renderTarget.CreateBitmapBrush(spGridBitmap, brushProperties);
}
private void Render()
{
CreateDeviceResources();
if (renderTarget.IsOccluded)
return;
SizeF renderTargetSize = renderTarget.Size;
renderTarget.BeginDraw();
renderTarget.Clear(new ColorF(1, 1, 1, 0));
// Paint a grid background.
RectF rf = new RectF(0.0f, 0.0f, renderTargetSize.Width, renderTargetSize.Height);
renderTarget.FillRectangle(rf, gridPatternBitmapBrush);
float curLeft = 0;
rf = new RectF(
curLeft,
renderTargetSize.Height,
(curLeft + renderTargetSize.Width / 5.0F),
renderTargetSize.Height - renderTargetSize.Height * ((float)x1 / 100.0F));
renderTarget.FillRectangle(rf, solidBrush1);
textLayout = dwriteFactory.CreateTextLayout(String.Format(" {0}%", x1), textFormat, renderTargetSize.Width / 5.0F, 30);
renderTarget.DrawTextLayout(
new Point2F(curLeft, renderTargetSize.Height - 30),
textLayout,
blackBrush);
curLeft = (curLeft + renderTargetSize.Width / 5.0F);
rf = new RectF(
curLeft,
renderTargetSize.Height,
(curLeft + renderTargetSize.Width / 5.0F),
renderTargetSize.Height - renderTargetSize.Height * ((float)x2 / 100.0F));
renderTarget.FillRectangle(rf, radialGradientBrush);
renderTarget.DrawText(
String.Format(" {0}%", x2),
textFormat,
new RectF(curLeft, renderTargetSize.Height - 30, (curLeft + renderTargetSize.Width / 5.0F), renderTargetSize.Height), blackBrush);
curLeft = (curLeft + renderTargetSize.Width / 5.0F);
rf = new RectF(
curLeft,
renderTargetSize.Height,
(curLeft + renderTargetSize.Width / 5.0F),
renderTargetSize.Height - renderTargetSize.Height * ((float)x3 / 100.0F));
renderTarget.FillRectangle(rf, solidBrush3);
renderTarget.DrawText(
String.Format(" {0}%", x3),
textFormat,
new RectF(curLeft, renderTargetSize.Height - 30, (curLeft + renderTargetSize.Width / 5.0F), renderTargetSize.Height), blackBrush);
curLeft = (curLeft + renderTargetSize.Width / 5.0F);
rf = new RectF(
curLeft,
renderTargetSize.Height,
(curLeft + renderTargetSize.Width / 5.0F),
renderTargetSize.Height - renderTargetSize.Height * ((float)x4 / 100.0F));
renderTarget.FillRectangle(rf, linearGradientBrush);
renderTarget.DrawText(
String.Format(" {0}%", x4),
textFormat,
new RectF(curLeft, renderTargetSize.Height - 30, (curLeft + renderTargetSize.Width / 5.0F), renderTargetSize.Height), blackBrush);
curLeft = (curLeft + renderTargetSize.Width / 5.0F);
rf = new RectF(
curLeft,
renderTargetSize.Height,
(curLeft + renderTargetSize.Width / 5.0F),
renderTargetSize.Height - renderTargetSize.Height * ((float)x5 / 100.0F));
renderTarget.FillRectangle(rf, solidBrush2);
renderTarget.DrawText(
String.Format(" {0}%", x5),
textFormat,
new RectF(curLeft, renderTargetSize.Height - 30, (curLeft + renderTargetSize.Width / 5.0F), renderTargetSize.Height), blackBrush);
renderTarget.EndDraw();
}
private void generate_Data(object sender, RoutedEventArgs e)
{
Random rand = new Random((int)Environment.TickCount);
x1 = rand.Next(100);
x2 = rand.Next(100);
x3 = rand.Next(100);
x4 = rand.Next(100);
x5 = rand.Next(100);
Render();
}
}
}
| |
#if UNITY_EDITOR
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEditor;
using System.Linq;
using System.Reflection;
using UnityEditor.Callbacks;
namespace Sabresaurus.SabreCSG
{
[ExecuteInEditMode]
public class CSGModel : CSGModelBase
{
#if UNITY_EDITOR
[SerializeField,HideInInspector]
bool firstRun = true;
const int MODEL_VERSION = 1;
// Warning disabled as this field is not in use yet, but helps future proof some cases
#pragma warning disable 414
[SerializeField,HideInInspector]
int modelVersion = 0;
#pragma warning restore 414
[SerializeField,HideInInspector]
bool autoRebuild = false;
bool editMode = false;
bool mouseIsDragging = false;
bool mouseIsHeld = false;
// Tools
Tool activeTool = null;
// Used to track what objects have been previously clicked on, so that the user can cycle click through objects
// on the same (or similar) ray cast
List<GameObject> previousHits = new List<GameObject>();
List<GameObject> lastHitSet = new List<GameObject>();
// Marked as serialized to persist through recompiles, used by draw tool
[SerializeField,HideInInspector]
Brush lastSelectedBrush = null;
float currentFrameTimestamp = 0;
float currentFrameDelta = 0;
static bool anyCSGModelsInEditMode = false;
static UnityEngine.Object[] deferredSelection = null;
public float CurrentFrameDelta {
get {
return currentFrameDelta;
}
}
Dictionary<MainMode, Tool> tools = new Dictionary<MainMode, Tool>()
{
{ MainMode.Resize, new ResizeEditor() },
{ MainMode.Vertex, new VertexEditor() },
{ MainMode.Face, new SurfaceEditor() },
{ MainMode.Clip, new ClipEditor() },
{ MainMode.Draw, new DrawEditor() },
};
// Dictionary<OverrideMode, Tool> overrideTools = new Dictionary<OverrideMode, Tool>()
// {
// { OverrideMode.Clip, new ClipEditor() },
// { OverrideMode.Draw, new DrawEditor() },
// };
public bool MouseIsDragging
{
get
{
return mouseIsDragging;
}
}
public bool MouseIsHeld
{
get
{
return mouseIsHeld;
}
}
public Brush LastSelectedBrush
{
get
{
return lastSelectedBrush;
}
}
public bool AutoRebuild {
get {
return autoRebuild;
}
set {
autoRebuild = value;
}
}
protected override void Start ()
{
UpdateUtility.RunCleanup();
base.Start ();
if(firstRun)
{
// Make sure editing is turned on
EditMode = true;
firstRun = false;
EditorHelper.SetDirty(this);
}
// Make sure we are correctly tracking whether any CSG Models are actually in edit mode
bool wereAnyInEditMode = anyCSGModelsInEditMode;
anyCSGModelsInEditMode = false;
CSGModel[] csgModels = FindObjectsOfType<CSGModel>();
// Loop through all the CSG Models in the scene and check if any are in edit mode
for (int i = 0; i < csgModels.Length; i++)
{
if(csgModels[i] != this
&& csgModels[i].EditMode)
{
anyCSGModelsInEditMode = true;
}
}
// If the status of whether any Models are in edit mode has changed, make sure all the brushes update their
// visibility. For example we moved from editing a CSG Model to opening another scene where no CSG Model is
// in edit mode. wereAnyInEditMode would be true and anyCSGModelsInEditMode would now be false
if(anyCSGModelsInEditMode != wereAnyInEditMode)
{
for (int i = 0; i < csgModels.Length; i++)
{
if(csgModels[i] != null && csgModels[i].gameObject != null)
{
csgModels[i].UpdateBrushVisibility();
}
}
}
if(modelVersion < MODEL_VERSION)
{
// Upgrading or a new model, so grab all the brushes in case it's an upgrade
brushes = new List<Brush>(transform.GetComponentsInChildren<Brush>(false));
// Make sure all brushes have a valid brush cache and need rebuilding
for (int i = 0; i < brushes.Count; i++)
{
if(brushes[i] != null)
{
brushes[i].RecachePolygons(true);
}
}
// Force all brushes to recalculate intersections
for (int i = 0; i < brushes.Count; i++)
{
if(brushes[i] != null)
{
brushes[i].RecalculateIntersections(brushes, false);
}
}
// Finally now that the potential upgrade is complete, track that the model is the correct version now
modelVersion = MODEL_VERSION;
}
}
public override void OnBuildComplete ()
{
base.OnBuildComplete ();
EditorUtility.ClearProgressBar();
EditorHelper.SetDirty(this);
SetContextDirty();
}
public void OnSceneGUI(SceneView sceneView)
{
if(Event.current.type == EventType.ExecuteCommand)
{
if(Event.current.commandName == "Duplicate")
{
if(EditorHelper.DuplicateSelection())
{
Event.current.Use();
}
}
}
Event e = Event.current;
if(!EditMode)
{
return;
}
RadialMenu.OnEarlySceneGUI(sceneView);
// Frame rate tracking
if(e.type == EventType.Repaint)
{
currentFrameDelta = Time.realtimeSinceStartup - currentFrameTimestamp;
currentFrameTimestamp = Time.realtimeSinceStartup;
}
// Raw checks for tracking mouse events (use raw so that consumed events are not ignored)
if (e.rawType == EventType.MouseDown)
{
mouseIsDragging = false;
mouseIsHeld = true;
if(e.button == 0 && GUIUtility.hotControl == 0 )
{
GUIUtility.keyboardControl = 0;
}
}
else if (e.rawType == EventType.MouseDrag)
{
mouseIsDragging = true;
}
else if (e.rawType == EventType.MouseUp)
{
mouseIsHeld = false;
}
// if (CurrentSettings.BrushesVisible)
{
// No idea what this line of code means, but it seems to stop normal mouse selection
HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive));
}
if(EditMode)
{
// In CSG mode, prevent the normal tools, so that the user must use our tools instead
Tools.current = UnityEditor.Tool.None;
}
int concaveBrushCount = 0;
for (int i = 0; i < brushes.Count; i++)
{
if(brushes[i] != null && !brushes[i].IsBrushConvex)
{
concaveBrushCount++;
}
}
if(concaveBrushCount > 0)
{
Toolbar.WarningMessage = concaveBrushCount + " Concave Brush" + (concaveBrushCount > 1 ? "es" : "") + " Detected";
}
else
{
// Toolbar.WarningMessage = "";
}
Toolbar.CSGModel = this;
Toolbar.OnSceneGUI(sceneView, e);
if (e.type == EventType.Repaint)// || e.type == EventType.Layout)
{
if(CurrentSettings.ShowExcludedPolygons)
{
List<Polygon> allPolygons = BuildContext.VisualPolygons ?? new List<Polygon>();
List<Polygon> excluded = new List<Polygon>();
for (int i = 0; i < allPolygons.Count; i++)
{
if(allPolygons[i].UserExcludeFromFinal)
{
excluded.Add(allPolygons[i]);
}
}
SabreCSGResources.GetExcludedMaterial().SetPass(0);
Mesh mesh = new Mesh();
List<int> indices = new List<int>();
BrushFactory.GenerateMeshFromPolygons(excluded.ToArray(), ref mesh, out indices);
Graphics.DrawMeshNow(mesh, Vector3.zero, Quaternion.identity);
// SabreGraphics.DrawPolygons(new Color(1,1,0,0.65f), new Color(1,0.8f,0,0.9f), excluded.ToArray());
}
if (activeTool == null || activeTool.BrushesHandleDrawing)
{
SabreCSGResources.GetSelectedBrushMaterial().SetPass(0);
// Selection
GL.Begin(GL.LINES);
Color outlineColor = Color.blue;
for (int brushIndex = 0; brushIndex < brushes.Count; brushIndex++)
{
Brush brush = brushes[brushIndex];
if(brush == null)
{
continue;
}
GameObject brushGameObject = brush.gameObject;
if(!brushGameObject.activeInHierarchy)
{
continue;
}
if (Selection.Contains(brushGameObject))
{
if (brushes[brushIndex].IsNoCSG)
{
outlineColor = new Color(1f,0.6f,1.0f);
}
else
{
if (brushes[brushIndex].Mode == CSGMode.Add)
{
outlineColor = Color.cyan;
}
else
{
outlineColor = Color.yellow;
}
}
}
else if(CurrentSettings.BrushesVisible)
{
if (brushes[brushIndex].IsNoCSG)
{
outlineColor = new Color(0.8f,0.3f,1.0f);
}
else
{
if (brushes[brushIndex].Mode == CSGMode.Add)
{
outlineColor = Color.blue;
}
else
{
outlineColor = new Color32(255, 130, 0, 255);
}
}
}
else
{
continue;
}
GL.Color(outlineColor);
Polygon[] polygons = brush.GetPolygons();
Transform brushTransform = brush.transform;
// Brush Outline
for (int i = 0; i < polygons.Length; i++)
{
Polygon polygon = polygons[i];
for (int j = 0; j < polygon.Vertices.Length; j++)
{
Vector3 position = brushTransform.TransformPoint(polygon.Vertices[j].Position);
GL.Vertex(position);
if (j < polygon.Vertices.Length - 1)
{
Vector3 position2 = brushTransform.TransformPoint(polygon.Vertices[j + 1].Position);
GL.Vertex(position2);
}
else
{
Vector3 position2 = brushTransform.TransformPoint(polygon.Vertices[0].Position);
GL.Vertex(position2);
}
}
}
}
GL.End();
for (int i = 0; i < brushes.Count; i++)
{
if (brushes[i] is PrimitiveBrush && brushes[i] != null && brushes[i].gameObject.activeInHierarchy)
{
((PrimitiveBrush)brushes[i]).OnRepaint(sceneView, e);
}
}
}
}
if (e.type == EventType.Repaint)
{
Rect rect = new Rect(0, 0, Screen.width, Screen.height);
EditorGUIUtility.AddCursorRect(rect, SabreMouse.ActiveCursor);
}
//
// int hotControl = GUIUtility.hotControl;
// if(hotControl != 0)
// Debug.Log (hotControl);
// Tools.viewTool = ViewTool.None;
PrimitiveBrush primitiveBrush = null;
List<PrimitiveBrush> primitiveBrushes = new List<PrimitiveBrush>();
for (int i = 0; i < Selection.gameObjects.Length; i++)
{
PrimitiveBrush matchedBrush = Selection.gameObjects[i].GetComponent<PrimitiveBrush>();
// If we've selected a brush that isn't a prefab in the project
if(matchedBrush != null
&& !(PrefabUtility.GetPrefabParent(matchedBrush.gameObject) == null
&& PrefabUtility.GetPrefabObject(matchedBrush.transform) != null))
{
primitiveBrushes.Add(matchedBrush);
}
}
if(primitiveBrushes.Count >= 1)
{
primitiveBrush = primitiveBrushes[0];
}
if(activeTool == null)
{
UpdateActiveTool();
}
if(activeTool != null)
{
activeTool.CSGModel = this;
activeTool.PrimaryTargetBrush = primitiveBrush;
activeTool.TargetBrushes = primitiveBrushes.ToArray();
activeTool.OnSceneGUI(sceneView, e);
}
// if(e.type == EventType.DragPerform)
// {
// Ray ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);
//
// RaycastHit hit = new RaycastHit();
//
// int layerMask = 1 << LayerMask.NameToLayer("CSGMesh");
// // Invert the layer mask
// layerMask = ~layerMask;
//
// // Shift mode means only add what they click (clicking nothing does nothing)
// if (Physics.Raycast(ray, out hit, float.PositiveInfinity, layerMask))
// {
// OnDragDrop(hit.collider.gameObject);
// }
// }
if (e.type == EventType.MouseUp && !RadialMenu.IsActive)
{
OnMouseUp(sceneView, e);
SabreMouse.ResetCursor();
}
else if (e.type == EventType.KeyDown || e.type == EventType.KeyUp)
{
OnKeyAction(sceneView, e);
}
if(CurrentSettings.OverrideFlyCamera)
{
LinearFPSCam.OnSceneGUI(sceneView);
}
RadialMenu.OnLateSceneGUI(sceneView);
}
void OnMouseUp(SceneView sceneView, Event e)
{
if (mouseIsDragging
|| (activeTool != null && activeTool.PreventBrushSelection)
|| EditorHelper.IsMousePositionNearSceneGizmo(e.mousePosition))
{
return;
}
// Left click - select
if (e.button == 0)
{
Ray ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);
List<PolygonRaycastHit> hits = RaycastBrushesAll(ray, true);
List<GameObject> hitObjects = hits.Select(hit => hit.GameObject).ToList();
GameObject selectedObject = null;
if(hits.Count == 0) // Didn't hit anything, blank the selection
{
previousHits.Clear();
lastHitSet.Clear();
}
else if(hits.Count == 1) // Only hit one thing, no ambiguity, this is what is selected
{
selectedObject = hits[0].GameObject;
previousHits.Clear();
lastHitSet.Clear();
}
else
{
if(!hitObjects.ContentsEquals(lastHitSet))
{
selectedObject = hits[0].GameObject;
previousHits.Clear();
lastHitSet = hitObjects;
}
else
{
// First try and select anything other than what has been previously hit
for (int i = 0; i < hits.Count; i++)
{
if(!previousHits.Contains(hits[i].GameObject))
{
selectedObject = hits[i].GameObject;
break;
}
}
// Only found previously hit objects
if(selectedObject == null)
{
// Walk backwards to find the oldest previous hit that has been hit by this ray
for (int i = previousHits.Count-1; i >= 0 && selectedObject == null; i--)
{
for (int j = 0; j < hits.Count; j++)
{
if(hits[j].GameObject == previousHits[i])
{
selectedObject = previousHits[i];
break;
}
}
}
}
}
}
if (EnumHelper.IsFlagSet(e.modifiers, EventModifiers.Shift)
|| EnumHelper.IsFlagSet(e.modifiers, EventModifiers.Control)
|| EnumHelper.IsFlagSet(e.modifiers, EventModifiers.Command))
{
List<UnityEngine.Object> objects = new List<UnityEngine.Object>(Selection.objects);
if (objects.Contains(selectedObject))
{
objects.Remove(selectedObject);
}
else
{
objects.Add(selectedObject);
}
Selection.objects = objects.ToArray();
}
else
{
Selection.activeGameObject = selectedObject;
}
if(selectedObject != null)
{
previousHits.Remove(selectedObject);
// Most recent hit
previousHits.Insert(0, selectedObject);
}
e.Use();
}
}
/// <summary>
/// Subscribes to both KeyDown and KeyUp events from the SceneView delegate. This allows us to easily store key
/// events in one place and mark them as used as necessary (for example to prevent error sounds on key down)
/// </summary>
void OnKeyAction(SceneView sceneView, Event e)
{
OnGenericKeyAction(sceneView, e);
}
private void OnGenericKeyAction(SceneView sceneView, Event e)
{
if (KeyMappings.EventsMatch(e, Event.KeyboardEvent(KeyMappings.Instance.ToggleMode))
|| KeyMappings.EventsMatch(e, Event.KeyboardEvent(KeyMappings.Instance.ToggleModeBack)))
{
// Toggle mode - immediately (key down)
if (e.type == EventType.KeyDown)
{
int currentModeInt = (int)CurrentSettings.CurrentMode;
int count = Enum.GetNames(typeof(MainMode)).Length;
if(KeyMappings.EventsMatch(e, Event.KeyboardEvent(KeyMappings.Instance.ToggleModeBack)))
{
currentModeInt--;
}
else
{
currentModeInt++;
}
if (currentModeInt >= count)
{
currentModeInt = 0;
}
else if (currentModeInt < 0)
{
currentModeInt = count - 1;
}
SetCurrentMode((MainMode)currentModeInt);
SceneView.RepaintAll();
}
e.Use();
}
else if (!mouseIsHeld && KeyMappings.EventsMatch(e, Event.KeyboardEvent(KeyMappings.Instance.ActivateClipMode)))
{
// Activate mode - immediately (key down)
if (e.type == EventType.KeyDown)
{
SetCurrentMode(MainMode.Clip);
// SetOverrideMode(OverrideMode.Clip);
SceneView.RepaintAll();
}
e.Use();
}
else if (!mouseIsHeld && KeyMappings.EventsMatch(e, Event.KeyboardEvent(KeyMappings.Instance.ActivateDrawMode)))
{
// Activate mode - immediately (key down)
if (e.type == EventType.KeyDown)
{
SetCurrentMode(MainMode.Draw);
// SetOverrideMode(OverrideMode.Draw);
SceneView.RepaintAll();
}
e.Use();
}
else if (KeyMappings.EventsMatch(e, Event.KeyboardEvent(KeyMappings.Instance.IncreasePosSnapping))
&& !SabreGUIHelper.AnyControlFocussed)
{
if (e.type == EventType.KeyUp)
{
CurrentSettings.ChangePosSnapDistance(2f);
SceneView.RepaintAll();
}
e.Use();
}
else if (KeyMappings.EventsMatch(e, Event.KeyboardEvent(KeyMappings.Instance.DecreasePosSnapping))
&& !SabreGUIHelper.AnyControlFocussed)
{
if (e.type == EventType.KeyUp)
{
CurrentSettings.ChangePosSnapDistance(.5f);
SceneView.RepaintAll();
}
e.Use();
}
else if (KeyMappings.EventsMatch(e, Event.KeyboardEvent(KeyMappings.Instance.TogglePosSnapping))
&& !SabreGUIHelper.AnyControlFocussed)
{
if (e.type == EventType.KeyUp)
{
CurrentSettings.PositionSnappingEnabled = !CurrentSettings.PositionSnappingEnabled;
SceneView.RepaintAll();
}
e.Use();
}
else if (KeyMappings.EventsMatch(e, Event.KeyboardEvent(KeyMappings.Instance.IncreaseAngSnapping))
&& !SabreGUIHelper.AnyControlFocussed)
{
if (e.type == EventType.KeyUp)
{
if(CurrentSettings.AngleSnapDistance >= 15)
{
CurrentSettings.AngleSnapDistance += 15;
}
else
{
CurrentSettings.AngleSnapDistance += 5;
}
SceneView.RepaintAll();
}
e.Use();
}
else if (KeyMappings.EventsMatch(e, Event.KeyboardEvent(KeyMappings.Instance.DecreaseAngSnapping))
&& !SabreGUIHelper.AnyControlFocussed)
{
if (e.type == EventType.KeyUp)
{
if(CurrentSettings.AngleSnapDistance > 15)
{
CurrentSettings.AngleSnapDistance -= 15;
}
else
{
CurrentSettings.AngleSnapDistance -= 5;
}
SceneView.RepaintAll();
}
e.Use();
}
else if (KeyMappings.EventsMatch(e, Event.KeyboardEvent(KeyMappings.Instance.ToggleAngSnapping))
&& !SabreGUIHelper.AnyControlFocussed)
{
if (e.type == EventType.KeyUp)
{
CurrentSettings.AngleSnappingEnabled = !CurrentSettings.AngleSnappingEnabled;
SceneView.RepaintAll();
}
e.Use();
}
else if (KeyMappings.EventsMatch(e, Event.KeyboardEvent(KeyMappings.Instance.ToggleBrushesHidden))
&& !SabreGUIHelper.AnyControlFocussed)
{
if (e.type == EventType.KeyUp)
{
CurrentSettings.BrushesHidden = !CurrentSettings.BrushesHidden;
UpdateBrushVisibility();
SceneView.RepaintAll();
}
e.Use();
}
else if (KeyMappings.EventsMatch(e, Event.KeyboardEvent(KeyMappings.Instance.EnableRadialMenu))
&& !SabreGUIHelper.AnyControlFocussed)
{
if (e.type == EventType.KeyUp)
{
RadialMenu.IsActive = true;
SceneView.RepaintAll();
}
e.Use();
}
else if(!mouseIsHeld && (KeyMappings.EventsMatch(e, Event.KeyboardEvent(KeyMappings.Instance.ChangeBrushToAdditive))
|| KeyMappings.EventsMatch(e, Event.KeyboardEvent(KeyMappings.Instance.ChangeBrushToAdditive2)))
)
{
if (e.type == EventType.KeyDown)
{
bool anyChanged = false;
for (int i = 0; i < Selection.gameObjects.Length; i++)
{
Brush brush = Selection.gameObjects[i].GetComponent<Brush>();
if (brush != null)
{
Undo.RecordObject(brush, "Change Brush To Add");
brush.Mode = CSGMode.Add;
anyChanged = true;
}
}
if(anyChanged)
{
// Need to update the icon for the csg mode in the hierarchy
EditorApplication.RepaintHierarchyWindow();
SceneView.RepaintAll();
}
}
e.Use();
}
else if(!mouseIsHeld && (KeyMappings.EventsMatch(e, Event.KeyboardEvent(KeyMappings.Instance.ChangeBrushToSubtractive))
|| KeyMappings.EventsMatch(e, Event.KeyboardEvent(KeyMappings.Instance.ChangeBrushToSubtractive2)))
)
{
if (e.type == EventType.KeyDown)
{
bool anyChanged = false;
for (int i = 0; i < Selection.gameObjects.Length; i++)
{
Brush brush = Selection.gameObjects[i].GetComponent<Brush>();
if (brush != null)
{
Undo.RecordObject(brush, "Change Brush To Subtract");
brush.Mode = CSGMode.Subtract;
anyChanged = true;
}
}
if(anyChanged)
{
// Need to update the icon for the csg mode in the hierarchy
EditorApplication.RepaintHierarchyWindow();
SceneView.RepaintAll();
}
}
e.Use();
}
else if(!mouseIsHeld && (KeyMappings.EventsMatch(e, Event.KeyboardEvent(KeyMappings.Instance.Group))
&& !SabreGUIHelper.AnyControlFocussed)
)
{
if (e.type == EventType.KeyDown)
{
if(Selection.activeTransform != null)
{
List<Transform> selectedTransforms = Selection.transforms.ToList();
selectedTransforms.Sort((x,y) => x.GetSiblingIndex().CompareTo(y.GetSiblingIndex()));
Transform rootTransform = Selection.activeTransform.parent;
int earliestSiblingIndex = Selection.activeTransform.GetSiblingIndex();
// Make sure we use the earliest sibling index for grouping, as they may select in reverse order up the hierarchy
for (int i = 0; i < selectedTransforms.Count; i++)
{
if(selectedTransforms[i].parent == rootTransform)
{
int siblingIndex = selectedTransforms[i].GetSiblingIndex();
if(siblingIndex < earliestSiblingIndex)
{
earliestSiblingIndex = siblingIndex;
}
}
}
// Create group
GameObject groupObject = new GameObject("Group");
Undo.RegisterCreatedObjectUndo (groupObject, "Group");
Undo.SetTransformParent(groupObject.transform, rootTransform, "Group");
groupObject.transform.position = Selection.activeTransform.position;
groupObject.transform.rotation = Selection.activeTransform.rotation;
groupObject.transform.localScale = Selection.activeTransform.localScale;
// Ensure correct sibling index
groupObject.transform.SetSiblingIndex(earliestSiblingIndex);
// Renachor
for (int i = 0; i < selectedTransforms.Count; i++)
{
Undo.SetTransformParent(selectedTransforms[i], groupObject.transform, "Group");
}
Selection.activeGameObject = groupObject;
// EditorApplication.RepaintHierarchyWindow();
// SceneView.RepaintAll();
}
}
e.Use();
}
else if(!mouseIsHeld && (KeyMappings.EventsMatch(e, Event.KeyboardEvent(KeyMappings.Instance.Ungroup))
&& !SabreGUIHelper.AnyControlFocussed)
)
{
if (e.type == EventType.KeyDown)
{
if(Selection.activeTransform != null && Selection.activeGameObject.GetComponents<MonoBehaviour>().Length == 0)
{
Transform rootTransform = Selection.activeTransform.parent;
int siblingIndex = Selection.activeTransform.GetSiblingIndex();
int childCount = Selection.activeTransform.childCount;
UnityEngine.Object[] newSelection = new UnityEngine.Object[childCount];
for (int i = 0; i < childCount; i++)
{
Transform childTransform = Selection.activeTransform.GetChild(0);
Undo.SetTransformParent(childTransform, rootTransform, "Ungroup");
childTransform.SetSiblingIndex(siblingIndex+i);
newSelection[i] = childTransform.gameObject;
}
Undo.DestroyObjectImmediate(Selection.activeGameObject);
// GameObject.DestroyImmediate(Selection.activeGameObject);
Selection.objects = newSelection;
}
}
e.Use();
}
}
#if !(UNITY_5_0 || UNITY_5_1)
void OnSelectionChanged()
{
bool anyCSGObjectsSelected = false;
bool anyNonCSGSelected = false;
List<CSGModel> foundModels = new List<CSGModel>();
Dictionary<CSGModel, List<UnityEngine.Object>> selectedBrushes = new Dictionary<CSGModel, List<UnityEngine.Object>>();
for (int i = 0; i < Selection.gameObjects.Length; i++)
{
// Skip any selected prefabs in the project window
if(PrefabUtility.GetPrefabParent(Selection.gameObjects[i]) == null
&& PrefabUtility.GetPrefabObject(Selection.gameObjects[i].transform) != null)
{
continue;
}
PrimitiveBrush primitiveBrush = Selection.gameObjects[i].GetComponent<PrimitiveBrush>();
CSGModel csgModel = Selection.gameObjects[i].GetComponent<CSGModel>();
if(primitiveBrush != null)
{
csgModel = primitiveBrush.GetCSGModel() as CSGModel;
if(csgModel != null)
{
if(!foundModels.Contains(csgModel))
{
foundModels.Add(csgModel);
selectedBrushes[csgModel] = new List<UnityEngine.Object>();
}
selectedBrushes[csgModel].Add(primitiveBrush.gameObject);
}
}
if(csgModel != null)
{
anyCSGObjectsSelected = true;
if(!foundModels.Contains(csgModel))
{
foundModels.Add(csgModel);
selectedBrushes[csgModel] = new List<UnityEngine.Object>();
}
}
else
{
CSGModel[] parentCSGModels = Selection.gameObjects[i].GetComponentsInParent<CSGModel>(true);
if(parentCSGModels.Length > 0)
{
csgModel = parentCSGModels[0];
if(Selection.gameObjects[i].GetComponent<MeshFilter>() != null
|| Selection.gameObjects[i].GetComponent<MeshCollider>() != null)
{
anyNonCSGSelected = true;
}
else
{
anyCSGObjectsSelected = true;
if(!foundModels.Contains(csgModel))
{
foundModels.Add(csgModel);
selectedBrushes[csgModel] = new List<UnityEngine.Object>();
}
}
}
else
{
anyNonCSGSelected = true;
}
}
}
if(anyCSGObjectsSelected)
{
CSGModel activeModel = null;
if(foundModels.Count == 1)
{
if(!foundModels[0].EditMode)
{
foundModels[0].EditMode = true;
}
activeModel = foundModels[0];
}
else
{
bool anyActive = false;
for (int i = 0; i < foundModels.Count; i++)
{
if(foundModels[i].EditMode)
{
anyActive = true;
activeModel = foundModels[i];
break;
}
}
if(!anyActive)
{
foundModels[0].EditMode = true;
activeModel = foundModels[0];
}
}
if(anyNonCSGSelected && activeModel != null)
{
deferredSelection = selectedBrushes[activeModel].ToArray();
}
}
else if(anyNonCSGSelected)
{
EditMode = false;
}
if(EditMode)
{
// Walk backwards until we find the last selected brush
for (int i = Selection.gameObjects.Length-1; i >= 0; i--)
{
Brush brush = Selection.gameObjects[i].GetComponent<Brush>();
if(brush != null)
{
lastSelectedBrush = brush;
break;
}
}
}
}
#endif
public void SetLastSelectedBrush(Brush brush)
{
lastSelectedBrush = brush;
}
void OnHierarchyItemGUI(int instanceID, Rect selectionRect)
{
if(Event.current.type == EventType.ExecuteCommand)
{
if(Event.current.commandName == "Duplicate")
{
if(EditorHelper.DuplicateSelection())
{
Event.current.Use();
}
}
}
GameObject gameObject = EditorUtility.InstanceIDToObject (instanceID) as GameObject;
if(Event.current.type == EventType.DragPerform)
{
if(selectionRect.Contains(Event.current.mousePosition))
{
if(gameObject != null)
{
OnDragDrop(gameObject);
}
}
}
if(gameObject != null)
{
Brush brush = gameObject.GetComponent<Brush>();
if(brush != null)
{
selectionRect.xMax -= 2;
selectionRect.xMin = selectionRect.xMax - 16;
selectionRect.height = 16;
if(brush.IsNoCSG)
{
GUI.DrawTexture(selectionRect, SabreCSGResources.NoCSGIconTexture);
}
else if(brush.Mode == CSGMode.Add)
{
GUI.DrawTexture(selectionRect, SabreCSGResources.AddIconTexture);
}
else
{
GUI.DrawTexture(selectionRect, SabreCSGResources.SubtractIconTexture);
}
Event e = Event.current;
if (e.type == EventType.KeyDown || e.type == EventType.KeyUp)
{
OnGenericKeyAction(null, e);
// if(Selection.gameObjects.Contains(gameObject))
// {
// if((KeyMappings.EventsMatch(e, Event.KeyboardEvent(KeyMappings.Instance.ChangeBrushToAdditive))
// || KeyMappings.EventsMatch(e, Event.KeyboardEvent(KeyMappings.Instance.ChangeBrushToAdditive2)))
// )
// {
// Undo.RecordObject(brush, "Change Brush To Add");
// brush.Mode = CSGMode.Add;
// EditorApplication.RepaintHierarchyWindow();
// }
// else if((KeyMappings.EventsMatch(e, Event.KeyboardEvent(KeyMappings.Instance.ChangeBrushToSubtractive))
// || KeyMappings.EventsMatch(e, Event.KeyboardEvent(KeyMappings.Instance.ChangeBrushToSubtractive2)))
// )
// {
// Undo.RecordObject(brush, "Change Brush To Subtract");
// brush.Mode = CSGMode.Subtract;
// EditorApplication.RepaintHierarchyWindow();
// }
// }
}
}
}
}
int frameIndex;
void OnEditorUpdate ()
{
if(deferredSelection != null)
{
Selection.objects = deferredSelection;
deferredSelection = null;
SceneView.RepaintAll();
EditorApplication.RepaintHierarchyWindow();
}
if(EditMode)
{
frameIndex++;
if(frameIndex > 1000)
{
frameIndex -= 1000;
}
if(AutoRebuild && gameObject.activeInHierarchy && this.enabled)
{
// if(frameIndex % 30 == 0)
{
Build(false, false);
}
}
if(CurrentSettings.OverrideFlyCamera)
{
LinearFPSCam.OnUpdate();
}
}
if(!Application.isPlaying)
{
bool buildOccurred = CSGFactory.Tick();
if(buildOccurred)
{
OnBuildComplete();
}
}
}
protected override void Update()
{
if(editMode && !anyCSGModelsInEditMode)
{
anyCSGModelsInEditMode = true;
CSGModel[] csgModels = FindObjectsOfType<CSGModel>();
for (int i = 0; i < csgModels.Length; i++)
{
if(csgModels[i] != null && csgModels[i].gameObject != null)
{
csgModels[i].UpdateBrushVisibility();
}
}
}
base.Update();
// Make sure the events we need to listen for are all bound (recompilation removes listeners, so it is
// necessary to rebind dynamically)
if(!EditorHelper.SceneViewHasDelegate(OnSceneGUI))
{
// Then resubscribe and repaint
SceneView.onSceneGUIDelegate += OnSceneGUI;
SceneView.RepaintAll();
}
#if !(UNITY_5_0 || UNITY_5_1)
if(!EditorHelper.HasDelegate(Selection.selectionChanged, (Action)OnSelectionChanged))
{
Selection.selectionChanged += OnSelectionChanged;
}
#endif
if(!EditorHelper.HasDelegate(EditorApplication.hierarchyWindowItemOnGUI, (EditorApplication.HierarchyWindowItemCallback)OnHierarchyItemGUI))
{
EditorApplication.hierarchyWindowItemOnGUI += OnHierarchyItemGUI;
}
if (EditMode)
{
if(!EditorHelper.HasDelegate(EditorApplication.projectWindowItemOnGUI, (EditorApplication.ProjectWindowItemCallback)OnProjectItemGUI))
{
EditorApplication.projectWindowItemOnGUI += OnProjectItemGUI;
}
if(!EditorHelper.HasDelegate(EditorApplication.update, (EditorApplication.CallbackFunction)OnEditorUpdate))
{
EditorApplication.update += OnEditorUpdate;
}
if(!EditorHelper.HasDelegate(Undo.undoRedoPerformed, (Undo.UndoRedoCallback)OnUndoRedoPerformed))
{
Undo.undoRedoPerformed += OnUndoRedoPerformed;
}
// Track whether all the brushes have been destroyed
bool anyBrushes = false;
if(brushes != null)
{
for (int i = 0; i < brushes.Count; i++)
{
if(brushes[i] != null)
{
anyBrushes = true;
break;
}
}
}
Toolbar.WarningMessage = "";
Brush firstBrush = GetComponentInChildren<Brush>();
if(firstBrush != null)
{
if(firstBrush.Mode == CSGMode.Subtract)
{
Toolbar.WarningMessage = "First brush must be additive";
}
// anyBrushes = true;
}
// All the brushes have been destroyed so add a default cube brush
if(!Application.isPlaying && !anyBrushes)
{
// Create the default brush
GameObject newBrushObject = CreateBrush(PrimitiveBrushType.Cube, new Vector3(0,1,0));
// Set the selection to the new object
Selection.activeGameObject = newBrushObject;
}
}
}
void OnDestroy()
{
EditorApplication.update -= OnEditorUpdate;
EditorApplication.hierarchyWindowItemOnGUI -= OnHierarchyItemGUI;
EditorApplication.projectWindowItemOnGUI -= OnProjectItemGUI;
SceneView.onSceneGUIDelegate -= OnSceneGUI;
Undo.undoRedoPerformed -= OnUndoRedoPerformed;
GridManager.UpdateGrid();
}
public void RebindToOnSceneGUI()
{
// Unbind the delegate, then rebind to ensure our method gets called last
SceneView.onSceneGUIDelegate -= OnSceneGUI;
SceneView.onSceneGUIDelegate += OnSceneGUI;
}
public void ExportOBJ ()
{
if(buildContext.VisualPolygons != null)
{
string path = EditorUtility.SaveFilePanel("Save Geometry As OBJ", "Assets", this.name + ".obj", "obj");
if(!string.IsNullOrEmpty(path))
{
OBJFactory.ExportToFile(path, transform, buildContext.VisualPolygons.DeepCopy(), GetDefaultMaterial());
AssetDatabase.Refresh();
}
}
}
public static string GetSabreCSGPath()
{
// Find all the scripts with CSGModel in their name
string[] guids = AssetDatabase.FindAssets("CSGModel t:Script");
foreach (string guid in guids)
{
// Find the path of the file
string path = AssetDatabase.GUIDToAssetPath(guid);
string suffix = "Scripts/CSGModel.cs";
// If it is the target file, i.e. CSGModel.cs not CSGModelInspector
if(path.EndsWith(suffix))
{
// Remove the suffix, to get for example Assets/SabreCSG
path = path.Remove(path.Length-suffix.Length, suffix.Length);
return path;
}
}
// None matched
return string.Empty;
}
/// <summary>
/// Marks the Build Context associated with this CSG Model as changed
/// </summary>
public void SetContextDirty()
{
EditorHelper.SetDirty(buildContextBehaviour);
}
public void UndoRecordContext(string name)
{
Undo.RecordObject(buildContextBehaviour, name);
}
private void UpdateActiveTool()
{
Tool lastTool = activeTool;
// if(CurrentSettings.OverrideMode != OverrideMode.None)
// {
// activeTool = overrideTools[CurrentSettings.OverrideMode];
// }
// else
{
activeTool = tools[CurrentSettings.CurrentMode];
}
if(activeTool != lastTool)
{
if(lastTool != null)
{
lastTool.Deactivated();
}
else // Tool was null, but is now set.
{
// Make sure brushes are updated as we may be in the Face tool which requires brushes to be hidden
UpdateBrushVisibility();
}
activeTool.ResetTool();
}
}
public Tool GetTool(MainMode mode)
{
return tools[mode];
}
public void SetCurrentMode(MainMode newMode)
{
if (newMode != CurrentSettings.CurrentMode)
{
CurrentSettings.OverrideMode = OverrideMode.None;
CurrentSettings.CurrentMode = newMode;
UpdateActiveTool();
UpdateBrushVisibility();
}
}
public void SetOverrideMode(OverrideMode newMode)
{
if(newMode != CurrentSettings.OverrideMode)
{
CurrentSettings.OverrideMode = newMode;
UpdateActiveTool();
UpdateBrushVisibility();
}
}
public void ExitOverrideMode()
{
CurrentSettings.OverrideMode = OverrideMode.None;
UpdateActiveTool();
UpdateBrushVisibility();
}
public bool EditMode
{
get
{
return this.editMode;
}
set
{
// Has edit mode changed
if (editMode != value)
{
editMode = value;
CSGModel[] csgModels = FindObjectsOfType<CSGModel>();
if (value == true) // Edit mode enabled
{
// If there are any other CSG Models in the scene, disabling their editing
if(csgModels.Length > 1)
{
for (int i = 0; i < csgModels.Length; i++)
{
if(csgModels[i] != this)
{
csgModels[i].EditMode = false;
}
}
}
// This CSG Model is now in edit mode, so we know for sure one is
anyCSGModelsInEditMode = true;
// Bind listeners
EditorApplication.update += OnEditorUpdate;
// Force the scene views to repaint (shows our own UI)
SceneView.RepaintAll();
// if(Event.current != null)
// {
// Event.current.Use();
// }
// SceneView.onSceneGUIDelegate += OnSceneGUI;
}
else // Edit mode disabled
{
// Unbind listeners
EditorApplication.update -= OnEditorUpdate;
// SceneView.onSceneGUIDelegate -= OnSceneGUI;
// Force the scene views to repaint (hides our own UI)
SceneView.RepaintAll();
// HandleUtility.Repaint();
// This CSG Model is no longer in edit mode, so find out if any are
anyCSGModelsInEditMode = false;
if(csgModels.Length > 1)
{
for (int i = 0; i < csgModels.Length; i++)
{
if(csgModels[i] != this
&& csgModels[i].EditMode)
{
anyCSGModelsInEditMode = true;
}
}
}
}
for (int i = 0; i < csgModels.Length; i++)
{
if(csgModels[i] != null && csgModels[i].gameObject != null)
{
csgModels[i].UpdateBrushVisibility();
}
}
GridManager.UpdateGrid();
}
}
}
void OnProjectItemGUI (string guid, Rect selectionRect)
{
// Debug.Log(Event.current.type.ToString());
/*
if (Event.current.type == EventType.MouseDrag)
{
if(selectionRect.Contains(Event.current.mousePosition))
{
// Debug.Log(Event.current.type.ToString());
string path = AssetDatabase.GUIDToAssetPath (guid);
if(!string.IsNullOrEmpty(path))
{
DragAndDrop.PrepareStartDrag();
DragAndDrop.paths = new string[] { path };
DragAndDrop.StartDrag ("Dragging material");
// Make sure no one else uses this event
Event.current.Use();
}
}
}
*/
}
void OnDragDrop(GameObject gameObject)
{
// PrimitiveBrush brush = gameObject.GetComponent<PrimitiveBrush>();
//
// if(brush != null)
// {
// if(DragAndDrop.objectReferences.Length == 1)
// {
// if(DragAndDrop.objectReferences[0] is Material)
// {
// brush.Material = (Material)DragAndDrop.objectReferences[0];
// DragAndDrop.AcceptDrag();
// Event.current.Use();
// }
// }
// }
}
private void OnUndoRedoPerformed()
{
// An undo or redo operation may restore a brush, so make sure we track all
brushes = new List<Brush>(transform.GetComponentsInChildren<Brush>(false));
// Tell each brush that an undo/redo has been performed so it can make sure the render mesh is updated
for (int i = 0; i < brushes.Count; i++)
{
if(brushes[i] != null)
{
brushes[i].OnUndoRedoPerformed();
}
}
activeTool.OnUndoRedoPerformed();
// If the user undos or redos a face change then a shared mesh may be updated.
// Unity won't automatically refresh the mesh filters that use a shared mesh, so we need to force refresh
// all of them so they fetch the latest revision of the mesh
Transform meshGroup = GetMeshGroupTransform();
if(meshGroup != null)
{
MeshFilter[] meshFilters = meshGroup.GetComponentsInChildren<MeshFilter>();
for (int i = 0; i < meshFilters.Length; i++)
{
meshFilters[i].ForceRefreshSharedMesh();
}
}
EditorApplication.RepaintHierarchyWindow();
}
public override bool AreBrushesVisible {
get {
if(!Application.isPlaying)
{
return anyCSGModelsInEditMode &&
CurrentSettings.BrushesVisible && (activeTool == null || activeTool.BrushesHandleDrawing);
}
return base.AreBrushesVisible;
}
}
public override void UpdateBrushVisibility ()
{
base.UpdateBrushVisibility ();
Transform meshGroup = transform.Find("MeshGroup");
if(meshGroup != null)
{
meshGroup.gameObject.SetActive(!CurrentSettings.MeshHidden);
}
}
public override Material GetDefaultFallbackMaterial ()
{
if(!Application.isPlaying)
{
// To allow users to move the SabreCSG folder, we must base the material loading on the asset path
return AssetDatabase.LoadMainAssetAtPath(GetSabreCSGPath() + "Resources/" + DEFAULT_FALLBACK_MATERIAL_PATH + ".mat") as Material;
}
else
{
return base.GetDefaultFallbackMaterial ();
}
}
public override void OnBuildProgressChanged (float progress)
{
base.OnBuildProgressChanged (progress);
EditorUtility.DisplayProgressBar("Building", "Building geometry from brushes", progress);
}
private void BreakMeshTest(Mesh mesh)
{
Vector3[] vertices = new Vector3[mesh.triangles.Length];
Vector3[] normals = new Vector3[mesh.triangles.Length];
Color32[] colors32 = new Color32[mesh.triangles.Length];
Vector2[] uvs = new Vector2[mesh.triangles.Length];
Vector4[] tangents = new Vector4[mesh.triangles.Length];
int[] triangles = new int[mesh.triangles.Length];
for (int i = 0; i < mesh.triangles.Length; i++)
{
int oldIndex = mesh.triangles[i];
vertices[i] = mesh.vertices[oldIndex];
normals[i] = mesh.normals[oldIndex];
colors32[i] = mesh.colors32[oldIndex];
uvs[i] = mesh.uv[oldIndex];
tangents[i] = mesh.tangents[oldIndex];
triangles[i] = i;
}
mesh.vertices = vertices;
mesh.normals = normals;
mesh.colors32 = colors32;
mesh.uv = uvs;
mesh.tangents = tangents;
mesh.triangles = triangles;
}
public override void OnFinalizeVisualMesh (GameObject newGameObject, Mesh mesh)
{
base.OnFinalizeVisualMesh (newGameObject, mesh);
if (buildSettings.GenerateLightmapUVs)
{
// BreakMeshTest(mesh);
// Create a copy of the mesh, which we can then unwrap
Mesh meshCopy = new Mesh();
meshCopy.vertices = mesh.vertices;
meshCopy.normals = mesh.normals;
meshCopy.colors32 = mesh.colors32;
meshCopy.uv = mesh.uv;
meshCopy.tangents = mesh.tangents;
meshCopy.triangles = mesh.triangles;
// Vector2[] perTriangleUVs = UnityEditor.Unwrapping.GeneratePerTriangleUV(meshCopy);
UnityEditor.UnwrapParam unwrapParameters = new UnityEditor.UnwrapParam()
{
angleError = buildSettings.UnwrapAngleError,
areaError = buildSettings.UnwrapAreaError,
hardAngle = buildSettings.UnwrapHardAngle,
packMargin = buildSettings.UnwrapPackMargin,
};
// Unwrap the mesh copy, note that this also changes the vertex buffer, which is why we do it on a copy
UnityEditor.Unwrapping.GenerateSecondaryUVSet(meshCopy, unwrapParameters);
// Now transfer the unwrapped UVs to the original mesh, since the two vertex counts differ
Vector2[] uv2 = new Vector2[mesh.vertices.Length];
if(meshCopy.triangles.Length == mesh.triangles.Length)
{
// VisualDebug.ClearAll();
// for (int i = 0; i < meshCopy.triangles.Length/3; i++)
// {
// int index1 = meshCopy.triangles[i*3 + 0];
// int index2 = meshCopy.triangles[i*3 + 1];
// int index3 = meshCopy.triangles[i*3 + 2];
//// if(index1 == index2 || index2 == index3 || index1 == index3)
//// {
//// Debug.LogError("Degen found");
//// }
// VisualDebug.AddLinePolygon(new Vector3[]{
// meshCopy.uv2[index1],
// meshCopy.uv2[index2],
// meshCopy.uv2[index3],
// }, Color.white);
// }
int triangleCount = mesh.triangles.Length;
for (int i = 0; i < triangleCount; i++)
{
int originalIndex = mesh.triangles[i];
int copyIndex = meshCopy.triangles[i];
// if(mesh.vertices[originalIndex] != meshCopy.vertices[copyIndex])
// {
// Debug.LogError("Vertex mismatch found");
// }
//
// if(uv2[originalIndex] != Vector2.zero
// && uv2[originalIndex] != meshCopy.uv2[copyIndex])
// {
// Debug.Log("Overwriting " + uv2[originalIndex] + " with " + meshCopy.uv2[copyIndex]);
// }
uv2[originalIndex] = meshCopy.uv2[copyIndex];
}
mesh.uv2 = uv2;
// for (int i = 0; i < mesh.triangles.Length/3; i++)
// {
// int index1 = mesh.triangles[i*3 + 0];
// int index2 = mesh.triangles[i*3 + 1];
// int index3 = mesh.triangles[i*3 + 2];
//// if(index1 == index2 || index2 == index3 || index1 == index3)
//// {
//// Debug.LogError("Degen found");
//// }
// VisualDebug.AddLinePolygon(new Vector3[]{
// mesh.uv2[index1] + Vector2.right,
// mesh.uv2[index2] + Vector2.right,
// mesh.uv2[index3] + Vector2.right,
// }, Color.blue);
// }
// for (int i = 0; i < uv2.Length/3; i++)
// {
// VisualDebug.AddLinePolygon(new Vector3[]{
// uv2[i*3 + 0] + Vector2.right,
// uv2[i*3 + 1] + Vector2.right,
// uv2[i*3 + 2] + Vector2.right,
// }, Color.blue);
// }
}
else
{
Debug.LogError("Unwrapped mesh triangle count mismatches source mesh");
}
// GameObject.DestroyImmediate(meshCopy);
}
// Apply the model layer, tag and appropriate static flags
ApplyModelAttributes(newGameObject, true);
}
public override void OnFinalizeCollisionMesh (GameObject newGameObject, Mesh mesh)
{
base.OnFinalizeCollisionMesh (newGameObject, mesh);
// Apply the model layer, tag and appropriate static flags
ApplyModelAttributes(newGameObject, false);
}
public Mesh GetMeshForMaterial(Material sourceMaterial, int fitVertices = 0)
{
if(materialMeshDictionary.Contains(sourceMaterial))
{
List<MaterialMeshDictionary.MeshObjectMapping> mappings = materialMeshDictionary[sourceMaterial];
Mesh lastMesh = mappings[mappings.Count-1].Mesh;
if(lastMesh.vertices.Length + fitVertices < MESH_VERTEX_LIMIT)
{
return lastMesh;
}
}
Mesh mesh = new Mesh();
materialMeshDictionary.Add(sourceMaterial, mesh, null);
Material materialToApply = sourceMaterial;
if(sourceMaterial == null)
{
materialToApply = GetDefaultMaterial();
}
GameObject newGameObject = CSGFactory.CreateMaterialMesh(this.transform, materialToApply, mesh);
// Apply the model layer, tag and appropriate static flags
ApplyModelAttributes(newGameObject, false);
return mesh;
}
public Mesh GetMeshForCollision(int fitVertices = 0)
{
Mesh lastMesh = collisionMeshDictionary[collisionMeshDictionary.Count-1];
if(lastMesh.vertices.Length + fitVertices < MESH_VERTEX_LIMIT)
{
return lastMesh;
}
Mesh mesh = new Mesh();
collisionMeshDictionary.Add(mesh);
GameObject newGameObject = CSGFactory.CreateCollisionMesh(this.transform, mesh);
// Apply the model layer, tag and appropriate static flags
ApplyModelAttributes(newGameObject, false);
return mesh;
}
void ApplyModelAttributes(GameObject newGameObject, bool isVisual)
{
// Inherit any static flags from the CSG model
UnityEditor.StaticEditorFlags rootStaticFlags = UnityEditor.GameObjectUtility.GetStaticEditorFlags(this.gameObject);
UnityEditor.GameObjectUtility.SetStaticEditorFlags(newGameObject, rootStaticFlags);
// Inherit the layer and tag from the CSG model
newGameObject.layer = this.gameObject.layer;
newGameObject.tag = this.gameObject.tag;
// If the mesh is lightmap UV'd then make sure the object is lightmap static
if(buildSettings.GenerateLightmapUVs)
{
UnityEditor.StaticEditorFlags staticFlags = UnityEditor.GameObjectUtility.GetStaticEditorFlags(newGameObject);
staticFlags |= UnityEditor.StaticEditorFlags.LightmapStatic;
UnityEditor.GameObjectUtility.SetStaticEditorFlags(newGameObject, staticFlags);
}
}
static void CleanupForBuild(Transform csgModelTransform)
{
Transform meshGroup = csgModelTransform.Find("MeshGroup");
if(meshGroup != null)
{
// Reanchor the meshes to the root
meshGroup.parent = null;
}
// Remove this game object
if(Application.isPlaying)
{
Destroy (csgModelTransform.gameObject);
}
else
{
DestroyImmediate (csgModelTransform.gameObject);
}
}
[PostProcessScene(1)]
public static void OnPostProcessScene()
{
CSGModel[] csgModels = FindObjectsOfType<CSGModel>();
for (int i = 0; i < csgModels.Length; i++)
{
CleanupForBuild(csgModels[i].transform);
}
}
#if UNITY_EDITOR && (UNITY_5_0 || UNITY_5_1)
void OnDrawGizmosSelected()
{
// Ensure Edit Mode is on
EditMode = true;
}
#endif
#endif
}
}
#endif
| |
#region Copyright (c) 2016 Atif Aziz. 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.
//
#endregion
namespace LinqPadless
{
#region Imports
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using KeyValuePairs;
using Mannex.IO;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using NuGet.Versioning;
using Optuple;
using Optuple.Collections;
using Optuple.Linq;
using Optuple.RegularExpressions;
using static Minifier;
using static MoreLinq.Extensions.ChooseExtension;
using static MoreLinq.Extensions.DistinctByExtension;
using static MoreLinq.Extensions.FoldExtension;
using static MoreLinq.Extensions.ForEachExtension;
using static MoreLinq.Extensions.IndexExtension;
using static MoreLinq.Extensions.PartitionExtension;
using static MoreLinq.Extensions.TakeUntilExtension;
using static MoreLinq.Extensions.ToDelimitedStringExtension;
using static MoreLinq.Extensions.ToDictionaryExtension;
using static OptionTag;
using static Optuple.OptionModule;
using MoreEnumerable = MoreLinq.MoreEnumerable;
using OptionSetArgumentParser = System.Func<System.Func<string, Mono.Options.OptionContext, bool>, string, Mono.Options.OptionContext, bool>;
#endregion
static partial class Program
{
static IEnumerable<string> GetDotnetExecutableSearchPaths(IEnumerable<string> searchPaths) =>
from sp in searchPaths
from ext in RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
? Seq.Return(".exe", ".cmd", ".bat")
: Seq.Return(string.Empty)
select Path.Join(sp, "dotnet" + ext);
static string GlobalPath =>
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "lpless");
static IEnumerable<string> GetSearchPaths(DirectoryInfo baseDir) =>
baseDir
.SelfAndParents()
.Append(new DirectoryInfo(GlobalPath))
.TakeUntil(d => File.Exists(Path.Combine(d.FullName, ".lplessroot")))
.Select(d => Path.Combine(d.FullName, ".lpless"));
static string GetCacheDirPath(IEnumerable<string> searchPaths) =>
searchPaths.Select(d => Path.Combine(d, "cache")).FirstOrDefault(Directory.Exists)
?? Path.Combine(Path.GetTempPath(), "lpless", "cache");
static int Wain(IEnumerable<string> args)
{
var verbose = Ref.Create(false);
var help = Ref.Create(false);
var force = false;
var dontExecute = false;
var outDirPath = (string) null;
var uncached = false;
var template = (string) null;
var publishTimeout = TimeSpan.FromMinutes(15);
var publishIdleTimeout = TimeSpan.FromMinutes(3);
var options = new OptionSet(CreateStrictOptionSetArgumentParser())
{
Options.Help(help),
Options.Verbose(verbose),
Options.Debug,
{ "f|force" , "force re-fresh/build", _ => force = true },
{ "x" , "do not execute", _ => dontExecute = true },
{ "b|build" , "build entirely to output directory; implies -f", _ => uncached = true },
{ "o|out|output=" , "output directory; implies -b and -f", v => outDirPath = v },
{ "t|template=" , "template", v => template = v },
{ "timeout=" , $"timeout for publishing; default is {publishTimeout.FormatHms()}",
v => publishTimeout = TimeSpanHms.Parse(v) },
{ "idle-timeout=" , $"idle timeout for publishing; default is {publishIdleTimeout.FormatHms()}",
v => publishIdleTimeout = TimeSpanHms.Parse(v) },
};
var tail = options.Parse(args);
var log = verbose ? Console.Error : null;
if (log != null)
Trace.Listeners.Add(new TextWriterTraceListener(log));
if (help || tail.Count == 0)
{
Help("main", string.Empty, options);
return 0;
}
var command = tail.First();
args = tail.Skip(1).TakeWhile(arg => arg != "--");
switch (command)
{
case CommandName.Cache : return CacheCommand(args);
case CommandName.Init : return InitCommand(args).GetAwaiter().GetResult();
case CommandName.Bundle : return BundleCommand(args);
case CommandName.Inspect: return InspectCommand(args);
case CommandName.Help : return HelpCommand(args);
case CommandName.License:
Console.WriteLine(LoadTextResource(typeof(Program), "license.txt"));
return 0;
default:
return DefaultCommand(command, args, template, outDirPath,
uncached: uncached || outDirPath != null,
inspection: Inspection.None, dontExecute: dontExecute,
force: force, publishIdleTimeout: publishIdleTimeout,
publishTimeout: publishTimeout, log: log);
}
}
static class CommandName
{
public const string Cache = "cache";
public const string Init = "init";
public const string Bundle = "bundle";
public const string Inspect = "inspect";
public const string Help = "help";
public const string License = "license";
public static readonly ImmutableArray<string> All =
ImmutableArray.Create(Cache, Init, Bundle, Inspect, Help, License);
}
static int HelpCommand(IEnumerable<string> args)
{
using var arg = args.GetEnumerator();
if (!arg.MoveNext())
{
Help();
}
else
{
var command = arg.Current;
if (CommandName.All.IndexOf(command) < 0)
throw new Exception($"\"{command}\" is an invalid command. Must be one of: {CommandName.All.ToDelimitedString(", ")}");
if (arg.MoveNext())
throw new Exception("Invalid argument: " + arg.Current);
if (command == CommandName.Help)
Help();
else
Wain(new[] { command, "--help" });
}
return 0;
static void Help() => Program.Help("help", new Mono.Options.OptionSet());
}
static int DefaultCommand(
string queryPath,
IEnumerable<string> args,
string template,
string outDirPath,
Inspection inspection,
bool uncached, bool dontExecute, bool force,
TimeSpan publishIdleTimeout, TimeSpan publishTimeout,
TextWriter log)
{
var query = LinqPadQuery.Load(Path.GetFullPath(queryPath));
if (query.ValidateSupported() is Exception e)
throw e;
switch (inspection)
{
case Inspection.Meta:
Console.WriteLine(query.MetaElement);
return 0;
case Inspection.Code:
Console.WriteLine(query.Code);
return 0;
case Inspection.Kind:
Console.WriteLine(query.Language);
return 0;
case Inspection.Namespaces:
foreach (var ns in query.Namespaces)
Console.WriteLine(ns);
return 0;
case Inspection.RemovedNamespaces:
foreach (var ns in query.NamespaceRemovals)
Console.WriteLine(ns);
return 0;
case Inspection.Loads:
foreach (var load in query.Loads)
Console.WriteLine(load.LoadPath);
return 0;
case Inspection.Packages:
foreach (var pr in
from pr in query.PackageReferences
select pr.Id
+ (pr.Version is {} v ? "=" + v : null)
+ (pr.IsPrereleaseAllowed ? "!" : null))
{
Console.WriteLine(pr);
}
return 0;
}
if (query.Loads.FirstOrNone(r => r.LoadPath.Length == 0
|| !Path.IsPathRooted(r.LoadPath)
&& r.LoadPath[0] != '.') is (true, var r))
{
throw new NotSupportedException($"Unsupported path \"{r.LoadPath}\" in load directive on line {r.LineNumber}.");
}
if (template?.Length == 0)
throw new Exception("Template name cannot be empty.");
var templateOverride = template != null;
if (!templateOverride)
{
template = (
from firstNonBlankLine in query.Code.Lines().SkipWhile(string.IsNullOrWhiteSpace).FirstOrNone()
from m in Regex.Match(firstNonBlankLine, @"(?<=//#?![\x20\t]*).+").ToOption()
select m.Value.Trim().Split2(' ', StringSplitOptions.RemoveEmptyEntries))
switch
{
(SomeT, var (t, _)) => t,
_ => "template"
};
}
var queryDir = new DirectoryInfo(Path.GetDirectoryName(query.FilePath));
var searchPaths = GetSearchPaths(queryDir).ToArray();
IReadOnlyCollection<(string Name, IStreamable Content)> templateFiles = (
from templateProjectPath in
searchPaths
.Select(d => Path.Combine(d, "templates", template))
.If(log, (ss, log) => ss.Do(() => log.WriteLine("Template searches:"))
.Do(s => log.WriteLine("- " + s)))
.FirstOrNone(Directory.Exists)
select
Directory
.GetFiles(templateProjectPath)
.Where(f => f.EndsWith(".cs", StringComparison.OrdinalIgnoreCase)
|| f.EndsWith(".csproj", StringComparison.OrdinalIgnoreCase)
|| "global.json".Equals(Path.GetFileName(f), StringComparison.OrdinalIgnoreCase))
.Select(f => (Path.GetFileName(f), Streamable.Create(() => File.OpenRead(f))))
.ToArray())
switch
{
(SomeT, var tfs) when tfs.Length > 0 => tfs,
_ => throw new Exception("No template for running query.")
};
static string MinifyLinqPadQuery(string text)
{
var eomLineNumber = LinqPad.GetEndOfMetaLineNumber(text);
return
text.Lines()
.Index(1)
.Partition(e => e.Key <= eomLineNumber, (xml, cs) => Seq.Return(xml, cs))
.Select(s => s.Values().ToDelimitedString(Environment.NewLine))
.Fold((xml, cs) => MinifyXml(xml) + "\n" + MinifyCSharp(cs));
};
var minifierTable = new (Func<string, string> Function, IEnumerable<string> Extension)[]
{
(MinifyJavaScript, Seq.Return(".json")),
(MinifyCSharp , Seq.Return(".cs")),
(MinifyXml , Seq.Return(".xml", ".csproj")),
};
var minifierByExtension =
minifierTable.SelectMany(m => m.Extension, (m, ext) => KeyValuePair.Create(ext, m.Function))
.ToDictionary(StringComparer.OrdinalIgnoreCase);
var hashSource =
MoreEnumerable
.From(() => new MemoryStream(Encoding.ASCII.GetBytes("3")))
.Concat(from rn in templateFiles.OrderBy(rn => rn.Name, StringComparer.OrdinalIgnoreCase)
select minifierByExtension.TryGetValue(Path.GetExtension(rn.Name), out var minifier)
? rn.Content.MapText(minifier)
: rn.Content
into content
select content.Open())
.If(templateOverride, ss => ss.Concat(MoreEnumerable.From(() => new MemoryStream(Utf8.BomlessEncoding.GetBytes(template)))))
.Concat(from load in query.Loads
select Streamable.ReadFile(load.Path)
.MapText(MinifyLinqPadQuery)
.Open())
.Concat(MoreEnumerable.From(() => Streamable.ReadFile(query.FilePath)
.MapText(MinifyLinqPadQuery)
.Open()))
.ToStreamable();
string hash;
using (var sha = IncrementalHash.CreateHash(HashAlgorithmName.SHA1))
using (var stream = hashSource.Open())
{
var stdout = inspection == Inspection.HashSource
? Console.OpenStandardOutput()
: null;
for (var buffer = new byte[4096]; ;)
{
var length = stream.Read(buffer, 0, buffer.Length);
if (length == 0)
break;
var span = buffer.AsSpan(0, length);
// Normalize line endings by removing CR, assuming only LF remain
do
{
const byte nul = 0, cr = (byte)'\r';
var si = span.IndexOfAny(cr, nul);
if (si < 0)
{
sha.AppendData(span);
stdout?.Write(span);
break;
}
if (span[si] == nul)
throw new NotSupportedException("Binary data is not yet supported.");
sha.AppendData(span.Slice(0, si));
stdout?.Write(span.Slice(0, si));
span = span.Slice(si + 1);
}
while (span.Length > 0);
}
if (inspection == Inspection.HashSource)
return 0;
hash = BitConverter.ToString(sha.GetHashAndReset())
.Replace("-", string.Empty)
.ToLowerInvariant();
}
if (inspection == Inspection.Hash)
{
Console.WriteLine(hash);
return 0;
}
string cacheId, cacheBaseDirPath;
if (uncached)
{
cacheId = ".";
cacheBaseDirPath = outDirPath ??
Path.Combine(queryDir.FullName, Path.GetFileNameWithoutExtension(query.FilePath));
force = true;
}
else
{
cacheId = hash;
cacheBaseDirPath = GetCacheDirPath(searchPaths);
}
var binDirPath = Path.Combine(cacheBaseDirPath, "bin", cacheId);
var srcDirPath = Path.Combine(cacheBaseDirPath, "src", cacheId);
if (!Path.IsPathFullyQualified(binDirPath))
binDirPath = Path.GetFullPath(binDirPath);
var tmpDirPath = uncached ? binDirPath : Path.Combine(cacheBaseDirPath, "bin", "!" + cacheId);
var exporting = outDirPath != null && !uncached;
if (exporting)
{
if (Directory.Exists(outDirPath))
throw new Exception("The output directory already exists.");
force = true;
}
rerun:
var dotnetSearchPaths = GetDotnetExecutableSearchPaths(searchPaths);
var dotnetPath =
dotnetSearchPaths
.If(log, (ps, log) => ps.Do(() => log.WriteLine(".NET Core CLI Searches:"))
.Do(p => log.WriteLine("- " + p)))
.FirstOrNone(File.Exists).Or("dotnet");
{
if (!force && Run() is {} exitCode)
return exitCode;
}
var buildMutex = new Mutex(initiallyOwned: true,
@"Global\lpless:" + hash,
out var isBuildMutexOwned);
try
{
if (!isBuildMutexOwned)
{
try
{
log.WriteLine("Detected competing executions and waiting for other(s) to finish...");
if (!buildMutex.WaitOne(TimeSpan.FromMinutes(1.5)))
throw new TimeoutException("Timed-out waiting for competing execution(s) to finish.");
log.WriteLine("...other is done; proceeding...");
}
catch (AbandonedMutexException)
{
log.WriteLine("...detected abandonment by other execution!");
}
if (!force)
goto rerun;
}
if (Compile(query, srcDirPath, tmpDirPath, templateFiles,
dotnetPath, publishIdleTimeout, publishTimeout,
inspection, log) is {} exitCode)
{
return exitCode;
}
if (tmpDirPath != binDirPath)
{
if (!exporting && Directory.Exists(binDirPath))
Directory.Delete(binDirPath, true);
Directory.Move(tmpDirPath, binDirPath);
}
}
catch
{
try
{
if (tmpDirPath != binDirPath)
Directory.Delete(tmpDirPath);
}
catch { /* ignore */}
throw;
}
finally
{
buildMutex.ReleaseMutex();
buildMutex.Dispose();
}
{
return Run() is {} exitCode
? exitCode
: throw new Exception("Internal error executing compilation.");
}
int? Run()
{
if (!Directory.Exists(binDirPath))
return null;
const string runtimeconfigJsonSuffix = ".runtimeconfig.json";
var binPath =
Directory.GetFiles(binDirPath, "*.json")
.FirstOrNone(p => p.EndsWith(runtimeconfigJsonSuffix, StringComparison.OrdinalIgnoreCase))
.Select(p => p[..^runtimeconfigJsonSuffix.Length] + ".dll")
.Match(p => p,
() => Directory.GetFiles(binDirPath, "*.exe")
.SingleOrDefault());
if (binPath == null)
return null;
var psi = new ProcessStartInfo { UseShellExecute = false };
if (binPath.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
{
psi.FileName = dotnetPath;
psi.ArgumentList.Add(binPath);
}
else
{
psi.FileName = binPath;
}
var env = psi.Environment;
env.Add("LPLESS_BIN_PATH", new Uri(Assembly.GetEntryAssembly().CodeBase).LocalPath);
env.Add("LPLESS_LINQ_FILE_PATH", queryPath);
env.Add("LPLESS_LINQ_FILE_HASH", hash);
args.ForEach(psi.ArgumentList.Add);
string FormatCommandLine() =>
PasteArguments.Paste(psi.ArgumentList.Prepend(psi.FileName));
if (dontExecute)
{
Console.WriteLine(FormatCommandLine());
return 0;
}
log?.WriteLine(FormatCommandLine());
const string runLogFileName = "runs.log";
var runLogPath = Path.Combine(binDirPath, runLogFileName);
var runLogLockTimeout = TimeSpan.FromSeconds(5);
var runLogLockName = string.Join("-", "lpless", hash, runLogFileName);
void LogRun(FormattableString str) =>
File.AppendAllLines(runLogPath, Seq.Return(FormattableString.Invariant(str)));
using var runLogLock = ExternalLock.EnterLocal(runLogLockName, runLogLockTimeout);
using var process = Process.Start(psi);
Debug.Assert(process != null);
var startTime = process.StartTime;
LogRun($"> {startTime:o} {process.Id}");
runLogLock.Dispose();
process.WaitForExit();
var endTime = DateTime.Now;
if (ExternalLock.TryEnterLocal(runLogLockName, runLogLockTimeout, out var mutex))
{
using var _ = mutex;
LogRun($"< {endTime:o} {startTime:o}/{process.Id} {process.ExitCode}");
}
return process.ExitCode;
}
}
static class Options
{
public static Mono.Options.Option Help(Ref<bool> value) =>
new ActionOption("?|help|h", "prints out the options", _ => value.Value = true);
public static Mono.Options.Option Verbose(Ref<bool> value) =>
new ActionOption("verbose|v", "enable additional output", _ => value.Value = true);
public static readonly Mono.Options.Option Debug =
new ActionOption("d|debug", "debug break", vs => Debugger.Launch());
}
static readonly ValueTuple Unit = default;
static int? Compile(LinqPadQuery query,
string srcDirPath, string binDirPath,
IEnumerable<(string Name, IStreamable Content)> templateFiles,
string dotnetPath, TimeSpan publishTimeout, TimeSpan publishIdleTimeout,
Inspection inspection, TextWriter log)
{
return _(IndentingLineWriter.CreateUnlessNull(log));
int? _(IndentingLineWriter log)
{
log?.WriteLines(from r in query.MetaElement.Elements("Reference")
select "Warning! Reference will be ignored: " + (string)r);
var wc = new WebClient();
NuGetVersion GetLatestPackageVersion(string id, bool isPrereleaseAllowed)
{
var latestVersion = Program.GetLatestPackageVersion(id, isPrereleaseAllowed, url =>
{
log?.WriteLine(url.OriginalString);
return wc.DownloadString(url);
});
log?.WriteLine($"{id} -> {latestVersion}");
return latestVersion;
}
var nrs =
from nr in
query.PackageReferences
.Select(r => new
{
r.Id,
Version = Option.From(r.HasVersion, r.Version),
r.IsPrereleaseAllowed,
Source = None<string>(),
Priority = 0,
})
.Concat(from lq in query.Loads
from r in lq.PackageReferences
select new
{
r.Id,
Version = Option.From(r.HasVersion, r.Version),
r.IsPrereleaseAllowed,
Source = Some(lq.LoadPath),
Priority = -1,
})
select new
{
nr.Id,
nr.Version,
ActualVersion =
nr.Version.Match(
some: Lazy.Value,
none: () => Lazy.Create(() => GetLatestPackageVersion(nr.Id, nr.IsPrereleaseAllowed))),
nr.IsPrereleaseAllowed,
nr.Priority,
nr.Source,
};
if (inspection == Inspection.ActualPackages)
{
foreach (var nr in nrs)
{
Console.WriteLine(nr.Id
+ nr.Version.Map(v => "=" + v).OrDefault()
+ (nr.IsPrereleaseAllowed ? "!" : null)
+ nr.Source.Map(s => $" <{s}>").OrDefault());
}
return 0;
}
var allQueries =
query.Loads
.Where(q => q.Language == LinqPadQueryLanguage.Statements
|| q.Language == LinqPadQueryLanguage.Expression)
.Select(q => new
{
q.GetQuery().Namespaces,
q.GetQuery().NamespaceRemovals,
Path = Some(q.LoadPath)
})
.Append(new
{
query.Namespaces,
query.NamespaceRemovals,
Path = None<string>()
})
.ToImmutableArray();
var namespaces = ImmutableArray.CreateRange(
from nss in new[]
{
from q in allQueries
let nsrs = q.NamespaceRemovals.ToHashSet(StringComparer.Ordinal)
from ns in LinqPad.DefaultNamespaces
where !nsrs.Contains(ns)
select new
{
Name = ns,
IsDefaulted = true,
QueryPath = q.Path,
},
from q in allQueries
from ns in q.Namespaces
select new
{
Name = ns,
IsDefaulted = false,
QueryPath = q.Path,
},
}
from ns in nss
select ns);
if (inspection == Inspection.ActualNamespaces)
{
foreach (var ns in namespaces)
{
Console.WriteLine(ns.Name
+ (ns.IsDefaulted ? "*" : null)
+ ns.QueryPath.Map(p => $" <{p}>").OrDefault());
}
return 0;
}
var references =
from r in nrs
select (r.Priority, Reference: new PackageReference(r.Id, r.ActualVersion.Value, r.IsPrereleaseAllowed));
GenerateExecutable(srcDirPath, binDirPath, query,
from ns in namespaces select ns.Name,
references, templateFiles,
dotnetPath, publishIdleTimeout, publishTimeout,
log);
return null;
}
}
static IEnumerable<(string Namespace, bool IsDefaulted)>
ProcessNamespaceDirectives(IEnumerable<string> namespaces, IEnumerable<string> removals) =>
LinqPad.DefaultNamespaces
.Except(removals, StringComparer.Ordinal)
.Select(ns => (ns, true))
.Concat(
from ns in namespaces
select ns.StartsWith("static ", StringComparison.Ordinal)
? ns.Split2(' ').MapItems((_, t) => (Left: "static ", Right: t))
: ns.IndexOf('=') > 0
? ns.Split2('=').MapItems((id, nst) => (Left: id + "=", Right: nst))
: (Left: null, Right: ns)
into ns
select (ns.Left + Regex.Replace(ns.Right, @"\s+", string.Empty), false))
.DistinctBy(((string Namespace, bool) e) => e.Namespace, StringComparer.Ordinal);
[Flags]
enum MainReturnTypeTraits
{
VoidTrait = 1,
TaskTrait = 2,
Int = 0,
Void = VoidTrait,
Task = TaskTrait | VoidTrait,
TaskOfInt = TaskTrait | Int,
}
static void GenerateExecutable(string srcDirPath, string binDirPath,
LinqPadQuery query,
IEnumerable<string> imports,
IEnumerable<(int Priority, PackageReference Reference)> packages,
IEnumerable<(string Name, IStreamable Content)> templateFiles,
string dotnetPath, TimeSpan publishIdleTimeout, TimeSpan publishTimeout,
IndentingLineWriter log)
{
// TODO error handling in generated code
var workingDirPath = srcDirPath;
if (Directory.Exists(workingDirPath))
{
try
{
Directory.Delete(workingDirPath, true);
}
catch (DirectoryNotFoundException)
{
// ignore in case of a race condition
}
}
Directory.CreateDirectory(workingDirPath);
var ps = packages.ToArray();
var resourceNames =
templateFiles
.ToDictionary(e => e.Name,
e => e.Content,
StringComparer.OrdinalIgnoreCase);
var projectDocument =
XDocument.Parse(resourceNames.Single(e => e.Key.EndsWith(".csproj", StringComparison.OrdinalIgnoreCase)).Value.ReadText());
var packageIdSet =
ps.Select(e => e.Reference.Id)
.ToHashSet(StringComparer.OrdinalIgnoreCase);
projectDocument
.Descendants("PackageReference")
.Where(e => packageIdSet.Contains((string) e.Attribute("Include")))
.Remove();
projectDocument.Element("Project").Add(
new XElement("ItemGroup",
from p in ps
group p by p.Reference.Id into g
select g.OrderByDescending(p => p.Priority)
.ThenByDescending(p => p.Reference.Version)
.First()
.Reference
into p
select
new XElement("PackageReference",
new XAttribute("Include", p.Id),
new XAttribute("Version", p.Version))));
var queryName = Path.GetFileNameWithoutExtension(query.FilePath);
using (var xw = XmlWriter.Create(Path.Combine(workingDirPath, queryName + ".csproj"), new XmlWriterSettings
{
Encoding = Utf8.BomlessEncoding,
Indent = true,
OmitXmlDeclaration = true,
}))
{
projectDocument.WriteTo(xw);
}
const string mainFile = "Main.cs";
var csFilePath = Path.Combine(workingDirPath, mainFile);
File.Delete(csFilePath);
var program = resourceNames[mainFile].ReadText();
var eol = Environment.NewLine;
program =
Detemplate(program, "imports",
ProcessNamespaceDirectives(imports, query.NamespaceRemovals)
.Select(e => $"using {e.Namespace};")
.ToDelimitedString(eol));
program =
Detemplate(program, "generator", () =>
{
var versionInfo = CachedVersionInfo.Value;
return $"[assembly: System.CodeDom.Compiler.GeneratedCode({SyntaxFactory.Literal(versionInfo.ProductName)}, {SyntaxFactory.Literal(versionInfo.FileVersion)})]";
});
program =
Detemplate(program, "path-string",
SyntaxFactory.Literal(query.FilePath).ToString());
program =
Detemplate(program, "source-string",
() => SyntaxFactory.Literal(query.Code).ToString());
var loads =
ImmutableArray.CreateRange(
from load in query.Loads.Index(1)
where load.Value.Language == LinqPadQueryLanguage.Program
select load.WithValue(ProgramQuery.Parse(load.Value.Code, load.Value.Path)));
program = Hooks.Aggregate(program, (p, h) =>
Detemplate(p, $"hook-{h.Name}",
Lazy.Create(() =>
loads.MapValue(h.Getter)
.Choose(e => e.Value is {} md
? Some(FormattableString.Invariant($"q => q.{md.Identifier}{e.Key}"))
: default)
.ToDelimitedString(", "))));
var noSymbols = Enumerable.Empty<string>();
var (body, symbols)
= query.Language == LinqPadQueryLanguage.Expression
? (GenerateExpressionProgram(query, program), noSymbols)
: query.Language == LinqPadQueryLanguage.Program
? GenerateProgram(query, program)
: (Detemplate(program, "statements", "#line 1" + eol + query.GetMergedCode()), noSymbols);
var baseCompilationSymbol = "LINQPAD_" +
( query.Language == LinqPadQueryLanguage.Expression ? "EXPRESSION"
: query.Language == LinqPadQueryLanguage.Program ? "PROGRAM"
: query.Language == LinqPadQueryLanguage.Statements ? "STATEMENTS"
: throw new NotSupportedException()
);
if (body != null)
File.WriteAllLines(csFilePath,
Seq.Return("#define LPLESS",
"#define LPLESS_TEMPLATE_V2",
"#define " + baseCompilationSymbol)
.Concat(from s in symbols
select $"#define {baseCompilationSymbol}_{s}")
.Append(body)
.Append(string.Empty));
foreach (var (name, content) in
from f in resourceNames
where !string.Equals(mainFile, f.Key, StringComparison.OrdinalIgnoreCase)
&& !f.Key.EndsWith(".csproj", StringComparison.OrdinalIgnoreCase)
select f)
{
using var s = content.Open();
using var w = File.Create(Path.Combine(srcDirPath, name));
s.CopyTo(w);
}
var loadedSources =
from load in query.Loads.Index(1)
where load.Value.Language == LinqPadQueryLanguage.Program
let pq = ProgramQuery.Parse(load.Value.GetQuery().FormatCodeWithLoadDirectivesCommented(), load.Value.Path)
select
load.WithValue(
ProcessNamespaceDirectives(load.Value.Namespaces, load.Value.NamespaceRemovals)
.Select(e => $"using {e.Namespace};")
.Concat(new[]
{
"partial class UserQuery",
"{",
FullSourceWithLineDirective(
pq.Others.Where(sn => !(sn is MethodDeclarationSyntax md) || md != pq.Main),
e => e is MethodDeclarationSyntax md && ( md == pq.OnInit
|| md == pq.OnStart
|| md == pq.OnFinish
|| md == pq.Main)
? md.WithIdentifier(SyntaxFactory.Identifier(md.Identifier.ValueText + load.Key))
: e),
"}",
FullSourceWithLineDirective(pq.Types),
FullSourceWithLineDirective(pq.Namespaces),
})
.Prepend("#define LPLESS"));
foreach (var (n, lines) in loadedSources)
{
using var w = new StreamWriter(Path.Combine(srcDirPath, FormattableString.Invariant($"Load{n}.cs")), false, Utf8.BomlessEncoding);
foreach (var line in lines)
w.WriteLine(line);
}
var quiet = log == null;
var publishArgs =
Seq.Return(Some("publish"),
quiet ? Some("-nologo") : default,
Some("-c"), Some("Release"),
Some($"-p:{nameof(LinqPadless)}={CachedVersionInfo.Value.FileVersion}"),
Some("-o"), Some(binDirPath))
.Choose(e => e)
.ToArray();
log?.WriteLine(PasteArguments.Paste(publishArgs.Prepend(dotnetPath)));
var publishLog = log?.Indent();
var errored = false;
List<string> pendingNonErrors = null;
foreach (var (_, line) in
Spawn(dotnetPath, publishArgs, workingDirPath,
StdOutputStreamKind.Output, StdOutputStreamKind.Error,
publishIdleTimeout, publishTimeout, killTimeout: TimeSpan.FromSeconds(15),
exitCode => new ApplicationException($"dotnet publish ended with a non-zero exit code of {exitCode}.")))
{
if (quiet
&& Regex.Match(line, @"(?<=:\s*)(error|warning|info)(?=\s+(\w{1,2}[0-9]+)\s*:)").Value is {} ms
&& ms.Length > 0)
{
if (ms == "error")
{
errored = true;
if (pendingNonErrors is {} nonErrors)
{
pendingNonErrors = null;
foreach (var nonError in nonErrors)
Console.Error.WriteLine(nonError);
}
Console.Error.WriteLine(line);
}
else if (!errored)
{
pendingNonErrors ??= new List<string>();
pendingNonErrors.Add(line);
}
}
publishLog?.WriteLines(line);
}
}
static readonly (string Name, Func<ProgramQuery, MethodDeclarationSyntax> Getter)[] Hooks =
{
("init" , ld => ld.OnInit ),
("start" , ld => ld.OnStart ),
("finish", ld => ld.OnFinish),
};
static string GenerateExpressionProgram(LinqPadQuery query, string template)
{
var eol = Environment.NewLine;
var code = query.FormatCodeWithLoadDirectivesCommented();
var program = Detemplate(template, "expression", $"#line 1 \"{query.FilePath}\"{eol}{code}");
var loads =
ImmutableArray.CreateRange(
from load in query.Loads
where load.Language == LinqPadQueryLanguage.Program
select ProgramQuery.Parse(load.Code, load.Path));
var printers =
ImmutableArray.CreateRange(
from e in
loads.SelectMany(load => load.Others.OfType<MethodDeclarationSyntax>())
.Choose(md =>
from a in md.AttributeLists
.SelectMany(attrs => attrs.Attributes)
.Where(attr =>
attr.Name.ToString() switch
{
"QueryExpressionPrinter" => true,
"QueryExpressionPrinterAttribute" => true,
_ => false
})
.FirstOrNone()
select (Method: md.Identifier.ValueText, Attribute: a))
group e.Attribute by e.Method
into g
select (Method: g.Key, Attribute: g.First()));
switch (printers.Length)
{
case 0: break;
case 1: program = Detemplate(program, "expression-printer", printers[0].Method); break;
default: throw new Exception("Ambiguous expression printers: " +
string.Join(", ",
from p in printers
select p.Attribute.SyntaxTree.GetMappedLineSpan(p.Attribute.Span) into loc
select $"{loc.Path}({loc.StartLinePosition.Line + 1},{loc.StartLinePosition.Character + 1})"));
}
return
Hooks.Aggregate(program, (p, h) =>
Detemplate(p, "expression-hook-" + h.Name,
Lazy.Create(() =>
loads.Select(h.Getter)
.Index(1)
.Choose(e => e.Value is {} md
? Some(FormattableString.Invariant($"{md.Identifier}{e.Key}();"))
: default)
.ToDelimitedString(eol))));
}
static string FullSourceWithLineDirective(IEnumerable<SyntaxNode> sns) =>
FullSourceWithLineDirective(sns, sn => sn);
static string FullSourceWithLineDirective<T>(IEnumerable<T> nns, Func<T, SyntaxNode> nf)
where T : SyntaxNode =>
nns.Select(e => "#line " +
e.GetLineNumber().ToString(CultureInfo.InvariantCulture)
+ " \"" + e.SyntaxTree.FilePath + "\""
+ Environment.NewLine
+ nf(e).ToFullString())
.Append(Environment.NewLine)
.ToDelimitedString(string.Empty);
static int GetLineNumber(this SyntaxNode node) =>
node.SyntaxTree.GetLineSpan(node.FullSpan).StartLinePosition.Line + 1;
static (string Source, IEnumerable<string> CompilationSymbols)
GenerateProgram(LinqPadQuery query, string template)
{
var parts = ProgramQuery.Parse(query.FormatCodeWithLoadDirectivesCommented(), query.FilePath);
var program =
Detemplate(template, "program-namespaces",
FullSourceWithLineDirective(parts.Namespaces));
program =
Detemplate(program, "program-types",
FullSourceWithLineDirective(parts.Types));
var main = parts.Main;
var loadedStatements = Lazy.Create(() =>
((BlockSyntax)SyntaxFactory
.ParseStatement(Seq.Return("{", query.GetMergedCode(true), ";", "}")
.ToDelimitedString(Environment.NewLine))).Statements);
var newMain =
query.Loads.Any(q => q.Language == LinqPadQueryLanguage.Expression
|| q.Language == LinqPadQueryLanguage.Statements)
? main.ExpressionBody is {} arrow
? main.WithExpressionBody(null).WithSemicolonToken(default)
.WithBody(SyntaxFactory.Block(loadedStatements.Value.Add(SyntaxFactory.ExpressionStatement(arrow.Expression))))
: main.WithBody(SyntaxFactory.Block(loadedStatements.Value.AddRange(
from stmt in main.Body.Statements.Index()
select stmt.Key == 0
? stmt.Value.WithLeadingTrivia(
SyntaxFactory.Trivia(
SyntaxFactory.LineDirectiveTrivia(SyntaxFactory.Literal(stmt.Value.GetLineNumber()),
SyntaxFactory.Literal($"\"{query.FilePath}\"", query.FilePath), true).NormalizeWhitespace()))
: stmt.Value)))
: main;
program =
Detemplate(program, "program",
FullSourceWithLineDirective(parts.Others,
e => e == main
? newMain.WithIdentifier(SyntaxFactory.Identifier("RunUserAuthoredQuery"))
: e is MethodDeclarationSyntax md && (e == parts.OnInit || e == parts.OnStart || e == parts.OnFinish)
? md.AddModifiers(SyntaxFactory.Token(SyntaxKind.PartialKeyword)
.WithTrailingTrivia(SyntaxFactory.Whitespace(" ")))
: e));
var isAsync = main.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword));
var isStatic = main.Modifiers.Any(m => m.IsKind(SyntaxKind.StaticKeyword));
var t = main.ReturnType switch
{
IdentifierNameSyntax ins when "Task".Equals(ins.Identifier.Value) =>
MainReturnTypeTraits.Task,
GenericNameSyntax gns when "Task".Equals(gns.Identifier.Value) =>
MainReturnTypeTraits.TaskOfInt,
PredefinedTypeSyntax pdts when pdts.Keyword.IsKind(SyntaxKind.VoidKeyword) =>
MainReturnTypeTraits.Void,
_ =>
MainReturnTypeTraits.Int
};
var isVoid = t.HasFlag(MainReturnTypeTraits.VoidTrait);
var isTask = t.HasFlag(MainReturnTypeTraits.TaskTrait);
var hasArgs = main.ParameterList.Parameters.Any();
/*
[ static ] ( void | int | Task | Task<int> ) Main([ string[] args ]) {}
static void Main() | STATIC, VOID
static int Main() | STATIC,
static void Main(string[] args) | STATIC, VOID, ARGS
static int Main(string[] args) | STATIC, ARGS
static Task Main() | STATIC, VOID, TASK
static Task<int> Main() | STATIC, TASK
static Task Main(string[] args) | STATIC, VOID, TASK, ARGS
static Task<int> Main(string[] args) | STATIC, TASK, ARGS
void Main() | VOID
int Main() |
void Main(string[] args) | VOID, ARGS
int Main(string[] args) | ARGS
Task Main() | VOID, TASK
Task<int> Main() | TASK
Task Main(string[] args) | VOID, TASK, ARGS
Task<int> Main(string[] args) | TASK, ARGS
*/
return (
program,
Enumerable.Empty<string>()
.If(hasArgs , ss => ss.Append("ARGS"))
.If(isVoid , ss => ss.Append("VOID"))
.If(isTask , ss => ss.Append("TASK"))
.If(isAsync , ss => ss.Append("ASYNC"))
.If(isStatic, ss => ss.Append("STATIC")));
}
static string Detemplate(string template, string name, string replacement) =>
Detemplate(template, name, Lazy.Value(replacement));
static string Detemplate(string template, string name, Func<string> replacement) =>
Detemplate(template, name, Lazy.Create(replacement));
static string Detemplate(string template, string name, Lazy<string> replacement) =>
Regex.Matches(template, @"
(?<= ^ | \r?\n )
[\x20\t]* // !? [\x20\t]* {% [\x20\t]*([a-z-]+)
(?: [\x20\t]* %}
| \s.*? // !? [\x20\t]* %}
)
[\x20\t]* (?=\r?\n)"
, RegexOptions.Singleline
| RegexOptions.IgnorePatternWhitespace)
.Aggregate((Index: 0, Text: string.Empty),
(s, m) =>
(m.Index + m.Length,
s.Text + template[s.Index..m.Index]
+ (string.Equals(name, m.Groups[1].Value, StringComparison.OrdinalIgnoreCase)
? replacement.Value
: m.Value)),
s => s.Text + template[s.Index..]);
static NuGetVersion GetLatestPackageVersion(string id, bool isPrereleaseAllowed, Func<Uri, string> downloader)
{
var atom = XNamespace.Get("http://www.w3.org/2005/Atom");
var d = XNamespace.Get("http://schemas.microsoft.com/ado/2007/08/dataservices");
var m = XNamespace.Get("http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");
var url = "https://www.nuget.org/api/v2/Search()"
+ "?$orderby=Id"
+ "&searchTerm='PackageId:" + Uri.EscapeDataString(id) + "'"
+ "&targetFramework=''"
+ "&includePrerelease=" + (isPrereleaseAllowed ? "true" : "false")
+ "&$skip=0&$top=1&semVerLevel=2.0.0";
var xml = downloader(new Uri(url));
var (_, version) =
from f in XDocument.Parse(xml).FindElement(atom + "feed")
from e in f.Elements(atom + "entry").SingleOrNone()
from p in e.FindElement(m + "properties")
from v in p.FindElement(d + "Version")
select NuGetVersion.Parse((string)v);
return version ?? throw new Exception($"Unable to determine latest{(isPrereleaseAllowed ? " (pre-release)" : null)} version of package named \"{id}\".");
}
enum StdOutputStreamKind { Output, Error }
static IEnumerable<(T, string)>
Spawn<T>(string path, IEnumerable<string> args,
string workingDirPath, T outputTag, T errorTag,
TimeSpan idleTimeout, TimeSpan executionTimeout, TimeSpan killTimeout,
Func<int, Exception> errorSelector)
{
var psi = new ProcessStartInfo
{
CreateNoWindow = true,
UseShellExecute = false,
FileName = path,
RedirectStandardError = true,
RedirectStandardOutput = true,
WorkingDirectory = workingDirPath,
};
args.ForEach(psi.ArgumentList.Add);
using var process = Process.Start(psi);
Debug.Assert(process != null);
var output = new BlockingCollection<(T, string)>();
var tsLock = new object();
var lastDataTimestamp = DateTime.MinValue;
DataReceivedEventHandler OnStdDataReceived(T tag, TaskCompletionSource<DateTime> tcs) =>
(_, e) =>
{
var now = DateTime.Now;
lock (tsLock)
{
if (now > lastDataTimestamp)
lastDataTimestamp = now;
}
if (e.Data == null)
tcs.SetResult(now);
else
output.Add((tag, e.Data));
};
var tcsStdOut = new TaskCompletionSource<DateTime>();
var tcsStdErr = new TaskCompletionSource<DateTime>();
Task.WhenAll(tcsStdOut.Task, tcsStdErr.Task)
.ContinueWith(_ => output.CompleteAdding());
process.OutputDataReceived += OnStdDataReceived(outputTag, tcsStdOut);
process.ErrorDataReceived += OnStdDataReceived(errorTag , tcsStdErr);
process.BeginOutputReadLine();
process.BeginErrorReadLine();
using var heartbeatCancellationTokenSource = new CancellationTokenSource();
var heartbeatCancellationToken = heartbeatCancellationTokenSource.Token;
using var timeoutCancellationTokenSource = new CancellationTokenSource();
if (executionTimeout > TimeSpan.Zero)
timeoutCancellationTokenSource.CancelAfter(executionTimeout);
var isClinicallyDead = false;
async Task Heartbeat()
{
var delay = idleTimeout;
while (!heartbeatCancellationToken.IsCancellationRequested)
{
await Task.Delay(delay, heartbeatCancellationToken);
TimeSpan durationSinceLastData;
lock (tsLock) durationSinceLastData = DateTime.Now - lastDataTimestamp;
if (idleTimeout > TimeSpan.Zero && durationSinceLastData > idleTimeout)
{
isClinicallyDead = true;
timeoutCancellationTokenSource.Cancel();
break;
}
delay = idleTimeout - durationSinceLastData;
}
}
var heartbeatTask = Heartbeat();
using (var e = output.GetConsumingEnumerable(timeoutCancellationTokenSource.Token)
.GetEnumerator())
{
while (true)
{
try
{
if (!e.MoveNext())
break;
}
catch (OperationCanceledException)
{
break;
}
yield return e.Current;
}
}
heartbeatCancellationTokenSource.Cancel();
try
{
heartbeatTask.GetAwaiter().GetResult(); // await graceful shutdown
}
catch (OperationCanceledException) { } // expected so ignore
catch (Exception e)
{
Debug.WriteLine(e);
}
if (isClinicallyDead
|| !process.WaitForExit(executionTimeout > TimeSpan.Zero
? (int)executionTimeout.TotalMilliseconds
: Timeout.Infinite))
{
try
{
process.Kill();
}
catch (Win32Exception e) // If Kill call is made while the process is terminating,
{ // a Win32Exception is thrown for "Access Denied" (2).
Debug.WriteLine(e);
}
var error = $"Timeout expired waiting for process {process.Id} to {(isClinicallyDead ? "respond" : "exit")}.";
// Killing of a process executes asynchronously so wait for the process to exit
if (!process.WaitForExit(killTimeout > TimeSpan.Zero
? (int)killTimeout.TotalMilliseconds
: Timeout.Infinite))
{
error += " The process did not terminate on time on killing either.";
}
throw new TimeoutException(error);
}
var exitCode = process.ExitCode;
if (exitCode != 0)
throw errorSelector(exitCode);
}
static OptionSetArgumentParser CreateStrictOptionSetArgumentParser()
{
var hasTailStarted = false;
return (impl, arg, context) =>
{
if (hasTailStarted) // once a tail, always a tail
return false;
var isOption = impl(arg, context);
if (!isOption)
{
if (arg.Length > 0 && arg[0] == '-' && !hasTailStarted)
throw new Exception("Invalid argument: " + arg);
hasTailStarted = true;
}
return isOption;
};
}
}
static class Utf8
{
public static readonly Encoding BomlessEncoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.